| Issue |
241260
|
| Summary |
[clang][TBAA] `_Bool` TBAA name depends on -std; C17+C23 LTO gives NoAlias (miscompile at -O3)
|
| Labels |
clang
|
| Assignees |
|
| Reporter |
jeffchen006
|
The TBAA scalar node for `_Bool` is named from the printing policy of the language mode: `"_Bool"` in C17, `"bool"` in C23 and C++. With LTO between a C17 TU and a C23 TU, the two nodes are siblings, so accesses to the same `_Bool` object are NoAlias.
**Reproducer** (`repro_a.c`, `repro_b.c`)
`repro_a.c`:
```c
/* TU 1, compiled with -std=c17. Same type _Bool as in repro_b.c. */
void set(_Bool *p) { *p = 1; }
```
`repro_b.c`:
```c
/* TU 2, compiled with -std=c23, linked with repro_a.c (C17) by LTO.
f(&x, &x): set(q) writes 1 to the same _Bool that *p reads.
Correct output: 1 (clang -O0, gcc). clang -O3 -flto: 0. */
int printf(const char *, ...);
void set(_Bool *p);
static int f(_Bool *p, _Bool *q) {
*p = 0;
set(q); /* q == p */
return *p; /* 1 */
}
int (*volatile fp)(_Bool *, _Bool *) = f; /* keeps f out of main */
int main(void) {
_Bool x = 0;
printf("%d\n", fp(&x, &x));
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 -std=c17 -O0 -flto -c repro_a.c -o ./a.o
$ clang -std=c23 -O0 -flto -c repro_b.c -o ./b.o
$ clang -O0 -flto -fuse-ld=lld ./a.o ./b.o -o ./m
$ ./m
-O0: 1
$ clang -std=c17 -O3 -flto -c repro_a.c -o ./a.o
$ clang -std=c23 -O3 -flto -c repro_b.c -o ./b.o
$ clang -O3 -flto -fuse-ld=lld ./a.o ./b.o -o ./m
$ ./m
-O3: 0
```
Expected (as `-O0`, gcc): `1`. `-O3` prints `0`.
**Why the expected output is right**
One `_Bool` object, accessed only through `_Bool` lvalues; C23 `bool` is the same type as `_Bool`. Each TU is UB-free in its own standard. UBSan/ASan/MSan at -O0 (each TU with its own -std) are clean.
**Potential Root cause**
`clang/lib/CodeGen/CodeGenTBAA.cpp`, `getTypeInfoHelper`, default case of the builtin switch: `createScalarTypeNode(BTy->getName(Features), getChar(), Size)`. `Features` gives a PrintingPolicy with `Bool = LO.Bool`, and `BuiltinType::getName` returns `Policy.Bool ? "bool" : "_Bool"`. After LTO, `set()` (C17) is inlined into `f()` (C23) and instcombine forwards `*p = 0`. Pointer and struct-path nodes copy this name too. (`half`/`__fp16` have the same policy dependence.)
**Possible Proposed fix**
```diff
- return createScalarTypeNode(BTy->getName(Features), getChar(), Size);
+ PrintingPolicy TBAAPolicy(Features);
+ TBAAPolicy.Bool = true; // one spelling in every language mode
+ TBAAPolicy.Half = false;
+ return createScalarTypeNode(BTy->getName(TBAAPolicy), getChar(), Size);
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs