| Issue |
241245
|
| Summary |
[GlobalOpt] Evaluator binds a byval argument to the caller object instead of a copy (miscompile at -O3)
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
jeffchen006
|
GlobalOpt evaluates a static constructor that passes a global struct by value. The Evaluator does not make a copy for the `byval` argument, so a later write to the global changes the parameter.
**Reproducer** (`repro.cpp`)
```cpp
// f receives s, a copy of g made before the call (pass by value).
// f then sets g.a = 1; the copy must keep s.a == 0. Correct output: 0
extern "C" int printf(const char *, ...);
struct S { long a, b, c; };
S g;
int n; // always 0; the recursive call only stops inlining of f
long seen;
void f(S s) {
if (n)
f(s);
g.a = 1;
seen = s.a;
}
int init = (f(g), 0); // dynamic initializer: runs before main
int main() {
printf("%ld\n", seen);
}
```
**Commands and output** (clang version 24.0.0git (https://github.com/llvm/llvm-project.git 8207e9143575), Target: x86_64-unknown-linux-gnu):
```console
$ clang++ -O0 repro.cpp -o o0
$ ./o0
0
$ clang++ -O3 repro.cpp -o o3
$ ./o3
1
```
Expected (as `-O0`, gcc -O0/-O2): `0`. `-O3` prints `1`.
**Why the expected output is right**
A struct passed by value is a copy made before the call (C11 6.5.2.2p4, C++ [expr.call]), so writing the global does not change the parameter. Integer stores only. UBSan/ASan at -O0 are clean (MSan is clean on the C version of this test).
**Potential Root cause**
`llvm/lib/Transforms/Utils/Evaluator.cpp`, `Evaluator::getFormalParams` puts the actual argument (`@g` itself) into `Formals`; `EvaluateFunction` binds it to the formal `ptr byval(%struct.S)`. The Evaluator does not handle `byval`/`inalloca`/`preallocated`, so the parameter is an alias of `@g`. The store `g.a = 100` goes to `MutatedMemory[@g]` and the load of `s.a` reads it back. GlobalOpt then commits `@seen = 100` and deletes the ctor.
**Possible Proposed fix**
Bail out on pass-pointee-by-value arguments in `getFormalParams`:
```diff
- for (Value *Arg : CB.args())
- Formals.push_back(getVal(Arg));
+ for (unsigned I = 0, E = CB.arg_size(); I != E; ++I) {
+ if (CB.isPassPointeeByValueArgument(I)) // byval, inalloca, preallocated
+ return false;
+ Formals.push_back(getVal(CB.getArgOperand(I)));
+ }
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs