Issue 239072
Summary [clang] Adding final prevents devirtualization of a virtual call in the destructor
Labels clang
Assignees
Reporter yqtian-se
    With `-O2`, adding `final` to `B` prevents Clang from devirtualizing a virtual call in `B::~B()`
after an inline helper is expanded. Without `final`, Clang resolves the same call to `A::f()` and
folds its result to `1`. The `final` specifier only restricts the possible dynamic types, so it should not remove this optimization opportunity.

## Reproducer

```cpp
struct A {
 virtual ~A() {}
  virtual int f() { return 1; }
};
int sink(int);
inline int via(A& a) { return a.f(); }

struct B final : A {
  ~B();
};
B::~B() { sink(via(*this)); }
```

```text
clang++ -std=c++17 -O2 -S -emit-llvm testcase.cpp -o -
```

Compiler Explorer compares the testcase with the control that removes only `final`:
https://godbolt.org/z/z58Kae9vT

Compiler version:
clang version 24.0.0git (https://github.com/llvm/llvm-project.git d4d37b824b91d8ef5115a1ae071e2a6709e8f120)
Target: x86_64-unknown-linux-gnu

## Actual and expected behavior

**Actual behavior:** With `final`, both emitted variants of `B::~B()` load the vptr, load the function from its slot, and call it indirectly:

```llvm
%vtable = load ptr, ptr %this
%slot = getelementptr inbounds i8, ptr %vtable, i64 16
%fn = load ptr, ptr %slot
%result = invoke i32 %fn(ptr %this)
```

Removing only `final` makes Clang emit the vptr store for `B` and fold the call and its result:

```llvm
store ptr getelementptr inbounds (i8, ptr @_ZTV1B, i64 16), ptr %this
%result = invoke i32 @_Z4sinki(i32 1)
```

The indirect call remains with `-O3` and with `-fstrict-vtable-pointers`. 
GCC trunk emits a direct
call for both forms.

**Expected behavior:** Clang should resolve the call to `A::f()` and pass `1` to `sink`, as it does
without `final`. While `B::~B()` is executing, the dynamic type is `B`; because `B` is `final`, the
vptr is known to point to `B`'s vtable at entry.

## related commit

Commit [`7eae8c6e62b2`](https://github.com/llvm/llvm-project/commit/7eae8c6e62b2a91e71aade19324b9d2242bcb4ab)
made `canSkipVTablePointerInitialization` return true for an effectively final class. Its commit message states that the vptr is already known to point to the current class's vtable. Skipping the redundant store is valid, but the generated IR does not otherwise preserve that known vptr value.
After `via` is inlined, the optimizer therefore sees an unconstrained vptr load and leaves the virtual call indirect.

The optimization could retain the known vptr fact when the store is skipped, rather than relying on the otherwise redundant store to communicate the dynamic type.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to