Skip to content

const ref declarations don't result in const pointers in generated code #27218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
bradcray opened this issue May 6, 2025 · 1 comment
Open

Comments

@bradcray
Copy link
Member

bradcray commented May 6, 2025

In a demo today, @jabraham17 asked a question revealing that when we pass an argument by const ref intent, we create a non-const pointer in the generated C code (and I strongly suspect the same is true in the LLVM back-end as well). The same seems to be true for a standalone const ref declaration. Note that we do check that we don't take a non-const ref to a const value, so we are not permitting modifications to const things as a result of this (so far as I can determine), but are simply not providing as much semantic information to the back-end C compiler as we could be.

I determined this by looking at patterns like:

proc foo(const ref x = 0) {  // or `extern proc foo(const ref x = 0)`
  writeln("x is: ", x);
}

var x = 42;

foo(x);

const ref r = x;

writeln(r);

and finding that:

  • foo() was declared to take an int64_t* rather than a const int64_t*
  • we passed x using &x rather than (const int64_t*)&x
    • (and similarly for an extern proc where the temp we inserted had type int64_t* rather than const int64_t*
  • r is declared to have type int64_t* rather than const int64_t*
@bradcray
Copy link
Member Author

bradcray commented May 6, 2025

One note here is that if we did generate const pointers in this case, we'd likely find cases that break today, particularly in interop scenarios where we're getting away with white lies. For example, https://github.com/chapel-lang/chapel/blob/main/test/extern/passArrays/passArrayAndSizeWithDefault.chpl declares the extern proc using const ref yet the C decalaration takes a non-const pointer (see https://github.com/chapel-lang/chapel/blob/main/test/extern/passArrays/printArr.h). So if this issue were resolved, we'd either need to add a const in the C routine (which seems best) or change the Chapel declaration to simply be ref. This was the original case that Jade asked about, mentioned above. The question would be how many other such cases are getting away with this.

(Note that I'm not suggesting we shouldn't use such cases as a rationale for not fixing/improving this… just noting that it may require other clean-ups, similar to when we had c_ptrConst start generating const annotations).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant