| Issue |
241278
|
| Summary |
[clang][CodeGen] Destructor alias drops noexcept: throwing base dtor escapes (miscompile at -O3)
|
| Labels |
clang
|
| Assignees |
|
| Reporter |
jeffchen006
|
`Derived::~Derived() noexcept` only calls `Base::~Base()` (`noexcept(false)`). At -O1+ clang emits `Derived`'s destructor as an alias of `Base::~Base`. The alias has no terminate scope, so an exception escapes a `noexcept` destructor instead of calling `std::terminate`.
**Reproducer** (`repro.cpp`)
```cpp
// ~Derived is noexcept, so the exception thrown by ~Base inside it must call std::terminate.
// Correct: "terminate called ..." and abort (exit code 134), nothing on stdout.
// clang++ -O1..-O3 prints "caught 42" (Derived's destructor is aliased to Base's).
extern "C" int printf(const char *, ...);
struct Base { virtual ~Base() noexcept(false) { throw 42; } };
struct Derived : Base { ~Derived() noexcept {} };
int main() {
Base *p = new Derived;
try {
p->~Base();
} catch (int e) {
printf("caught %d\n", e);
}
}
```
**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=c++17 -O0 repro.cpp -o ./o0
$ ./o0
terminate called after throwing an instance of 'int'
Aborted
O0 rc=134
$ clang++ -std=c++17 -O3 repro.cpp -o ./o3
$ ./o3
caught 42
O3 rc=0
```
Expected (as `-O0`, g++): `std::terminate` (abort, rc 134). `-O3` prints `caught 42`.
**Why the expected output is right**
`p->~Base()` is a virtual call whose final overrider is `Derived::~Derived` (noexcept). It calls `Base::~Base`, which throws; the exception leaves a noexcept function, so `std::terminate` is called ([except.spec]/5). UBSan/ASan/MSan (libc++) at -O0 are clean.
**Potential Root cause**
`clang/lib/CodeGen/CGCXX.cpp`, `CodeGenModule::TryEmitBaseDestructorAsAlias` (-O1+ only): it replaces `Derived::~Derived` with `Base::~Base` when the body is trivial, there is one non-virtual base at offset 0, and the calling conventions match. It does not compare exception specifications. For linkonce_odr it uses `addReplacement`, so the vtable slot of Derived gets `@_ZN4BaseD2Ev`. Not an LLVM pass: the FE IR at -O3 already has it.
**Possible Proposed fix**
After the calling-convention check:
```diff
+ if (D->getType()->castAs<FunctionProtoType>()->isNothrow() &&
+ !BaseD->getType()->castAs<FunctionProtoType>()->isNothrow())
+ return true;
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs