Issue 241248
Summary [clang][TBAA] C enum pointer vs int pointer members give different struct-path nodes (miscompile at -O3)
Labels clang
Assignees
Reporter jeffchen006
    In C23, `enum E : int` is compatible with `int`, so two `struct S` that differ only in `enum E *` vs `int *` members are compatible. Clang gives them different struct-path TBAA base nodes, and a store and a load of the same `int` member are treated as NoAlias.

**Reproducer** (`repro.c`)
```c
int printf(const char *, ...);

enum E : int { A };              /* C23: enum E is compatible with int */
struct S { enum E *e; int v; };

int f(struct S *p, void *vq) {
  /* C23 6.2.7p1: same tag, same member names, compatible member types
     (enum E * and int *), so this struct S is compatible with the one above. */
  struct S { int *e; int v; } *q = vq;
  p->v = 1;
 q->v = 2;
  return p->v;                   /* p and q point to the same object: 2 */
}

int main(void) {
  struct S s = {0, 0};
 printf("%d\n", f(&s, &s));
  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=c23 -O0 repro.c -o ./o0
$ ./o0
2
$ clang -std=c23 -O3 repro.c -o ./o3
$ ./o3
1
```
Expected (as `-O0`): `2`. `-O3` prints `1`.

**Why the expected output is right**
C23 6.7.3.3: `enum E : int` is compatible with `int`; 6.7.6.1p2: pointers to compatible types are compatible; 6.2.7p1: the two `struct S` are compatible. Both accesses are `int` lvalues on one `int` object. UBSan/ASan/MSan at -O0 are clean. Only `-fno-strict-aliasing` (or `-fno-pointer-tbaa`) removes the difference.

**Possible Root cause**
`clang/lib/CodeGen/CodeGenTBAA.cpp`, `CodeGenTBAA::getTypeInfoHelper`, pointer branch: a builtin pointee gets `"p1 <builtin>"`, a named record gets a mangled name, and any other pointee, also an enum, gets `getAnyPtr()`. So `int *` -> `p1 int`, but `enum E *` -> `any pointer`. `getBaseTypeInfoHelper` builds the C struct-path base node from the field nodes, so the two compatible structs get two unrelated base nodes, and struct-path TBAA says NoAlias for the same member.

**Possible Proposed fix**
In C, map an enum pointee to its integer type before naming (the scalar enum case already does this):
```diff
     } while (Ty->isPointerType());
+    if (!Features.CPlusPlus)
+      if (const auto *ET = dyn_cast<EnumType>(Ty))
+ if (QualType IT = ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
+ !IT.isNull())
+          Ty = Context.getCanonicalType(IT).getTypePtr();
 if (Ty->isVoidType())
```

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

Reply via email to