Issue 241258
Summary [clang][CodeGen] vptr change in ctor/dtor laundered only on `this` (strict vtable ptrs) (miscompile at -O3)
Labels clang
Assignees
Reporter jeffchen006
    During destruction the dynamic type changes (D -> B). Clang launders only the destructor's own `this`. A pointer to the same object saved earlier (`self`) still has the invariant.group fact of the D vptr, and GVN forwards it, so `self->f()` calls `D::f` instead of `B::f`.

**Reproducer** (`repro.cpp`)
```cpp
// When ~B runs, the object under destruction is the B subobject of d, and
// self points to it, so self->f() calls B::f ([class.cdtor]/4).
// Correct output: 1 (clang++ -O0, g++).  clang++ -O3 -fstrict-vtable-pointers: 2.
extern "C" int printf(const char *, ...);

int r;

struct B {
  B *self;
  virtual int f() { return 1; }
 ~B() { r = self->f(); }  // must call B::f
};

struct D : B {
  D() { self = this; }
  int f() override { return 2; }
};

int main() {
  { D d; }
  printf("%d\n", r);
}
```

**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 -fstrict-vtable-pointers repro.cpp -o ./o0
$ ./o0
1
$ clang++ -O3 -fstrict-vtable-pointers repro.cpp -o ./o3
$ ./o3
2
```
Expected (as `-O0`, g++ -O0/-O2): `1`. `-O3` prints `2`.

**Why the expected output is right**
In `~B` the object under destruction is the B subobject of `d`; `self` points to it, so `self->f()` is allowed by [class.cdtor]/4 and calls `B::f`. UBSan/ASan/MSan (libc++) at -O0 are clean.

**Potential Root cause**
`clang/lib/CodeGen/CGClass.cpp`: under `-fstrict-vtable-pointers` a vptr phase change is modelled only by laundering the cdtor's `this` (`EmitCtorPrologue`, `EmitDestructorBody`). The new vptr is stored with `!invariant.group` (`InitializeVTablePointer`) and every vptr load has `!invariant.group` (`GetVTablePtr`). A pointer made before the phase change keeps the old fact. After inlining, `self` is `&d`; D() stored the D vptr through it with `!invariant.group`, and GVN (MemDep invariant.group dependency) forwards it. By the LangRef rule the FE IR is already wrong; GVN is correct.

**Possible Proposed fix**
No small local front-end fix is fully sound (any pointer that escaped before the phase change can be used after it). Options: (1) do not put `!invariant.group` on vptr stores in ctors/dtors (tested; loses some devirtualization); (2) change the invariant.group model so that a tagged vptr store ends the invariance for all pointers that may alias, and teach MemDep/GVN to stop there.

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

Reply via email to