Issue 241262
Summary [clang][CodeGen] __builtin_bswapg / __builtin_bitreverseg evaluate the argument twice (miscompile at -O3)
Labels clang
Assignees
Reporter jeffchen006
    `__builtin_bswapg(x)` and `__builtin_bitreverseg(x)` emit the argument two times. With a statement _expression_ that declares a local, the second emission reads the first local after its `lifetime.end`, and -O3 folds that read to poison.

**Reproducer** (`repro.c`)
```c
/* __builtin_bswapg of a statement _expression_. bswap(0x0102030405060708) is
   0x0807060504030201, so the program must print 1. Clang -O3 prints 0. */
int printf(const char *, ...);
unsigned long long g = 0x0102030405060708;
int main(void) {
 unsigned long long r = __builtin_bswapg(({ unsigned long long a = g; a; }));
  printf("%d\n", r == 0x0807060504030201);
  return 0;
}
```

**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.c -o o0
$ ./o0
1
$ clang -O3 repro.c -o o3
$ ./o3
0
```
Expected (as `-O0`): `1`. `-O3` prints `0`.

**Why the expected output is right**
One volatile read of an initialized global inside a GNU statement _expression_; the result is a byte swap of an `unsigned long long`. The argument must be evaluated exactly once. UBSan/ASan/MSan at -O0 are clean. (gcc has no `__builtin_bswapg`.)

**Potential Root cause**
`clang/lib/CodeGen/CGBuiltin.cpp`, `CodeGenFunction::EmitBuiltinExpr`, cases `BI__builtin_bswapg` and `BI__builtin_bitreverseg`: they call `EmitScalarExpr(E->getArg(0))` for the type, then `emitBuiltinWithOneOverloadedType<1>(*this, E, ...)`, which emits `E->getArg(0)` a second time. The second emission makes a new alloca for the local, but `setAddrOfLocalVar` keeps the first map entry, so the read uses the first alloca after `llvm.lifetime.end`. (From f210fc1a1ca6 #162433 and 5d057a125cba #179126.)

**Possible Proposed fix**
Use the value already emitted:
```diff
   case Builtin::BI__builtin_bswapg: {
     Value *ArgValue = EmitScalarExpr(E->getArg(0));
     ...
-    return RValue::get(
-        emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bswap));
+    return RValue::get(Builder.CreateUnaryIntrinsic(Intrinsic::bswap, ArgValue));
```
and the same for `BI__builtin_bitreverseg` with `Intrinsic::bitreverse`.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to