Skip to content

Commit 0b5d559

Browse files
committed
[WPD]: Enable speculative devirtualizatoin.
- Add cl::opt 'devirtualize-speculatively' to enable it. - Flag is disabled by default. - It works regardless of the visibility of the object.
1 parent 3c75065 commit 0b5d559

File tree

3 files changed

+187
-15
lines changed

3 files changed

+187
-15
lines changed

llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp

Lines changed: 49 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
// returns 0, or a single vtable's function returns 1, replace each virtual
2525
// call with a comparison of the vptr against that vtable's address.
2626
//
27-
// This pass is intended to be used during the regular and thin LTO pipelines:
27+
// This pass is intended to be used during the regular/thin and non-LTO
28+
// pipelines:
2829
//
2930
// During regular LTO, the pass determines the best optimization for each
3031
// virtual call and applies the resolutions directly to virtual calls that are
@@ -48,6 +49,14 @@
4849
// is supported.
4950
// - Import phase: (same as with hybrid case above).
5051
//
52+
// During Speculative devirtualization mode -not restricted to LTO-:
53+
// - The pass applies speculative devirtualization without requiring any type of
54+
// visibility.
55+
// - Skips other features like virtual constant propagation, uniform return
56+
// value optimization, unique return value optimization and branch funnels as
57+
// they need LTO.
58+
// - This mode is enabled via 'devirtualize-speculatively' flag.
59+
//
5160
//===----------------------------------------------------------------------===//
5261

5362
#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
@@ -61,7 +70,9 @@
6170
#include "llvm/Analysis/AssumptionCache.h"
6271
#include "llvm/Analysis/BasicAliasAnalysis.h"
6372
#include "llvm/Analysis/BlockFrequencyInfo.h"
73+
#include "llvm/Analysis/ModuleSummaryAnalysis.h"
6474
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
75+
#include "llvm/Analysis/ProfileSummaryInfo.h"
6576
#include "llvm/Analysis/TypeMetadataUtils.h"
6677
#include "llvm/Bitcode/BitcodeReader.h"
6778
#include "llvm/Bitcode/BitcodeWriter.h"
@@ -120,6 +131,13 @@ STATISTIC(NumVirtConstProp1Bit,
120131
"Number of 1 bit virtual constant propagations");
121132
STATISTIC(NumVirtConstProp, "Number of virtual constant propagations");
122133

134+
// TODO: This option eventually should support any public visibility vtables
135+
// with/out LTO.
136+
static cl::opt<bool> ClDevirtualizeSpeculatively(
137+
"devirtualize-speculatively",
138+
cl::desc("Enable speculative devirtualization optimization"),
139+
cl::init(false));
140+
123141
static cl::opt<PassSummaryAction> ClSummaryAction(
124142
"wholeprogramdevirt-summary-action",
125143
cl::desc("What to do with the summary when running this pass"),
@@ -1083,10 +1101,10 @@ bool DevirtModule::tryFindVirtualCallTargets(
10831101
if (!TM.Bits->GV->isConstant())
10841102
return false;
10851103

1086-
// We cannot perform whole program devirtualization analysis on a vtable
1087-
// with public LTO visibility.
1088-
if (TM.Bits->GV->getVCallVisibility() ==
1089-
GlobalObject::VCallVisibilityPublic)
1104+
// Without ClDevirtualizeSpeculatively, we cannot perform whole program
1105+
// devirtualization analysis on a vtable with public LTO visibility.
1106+
if (!ClDevirtualizeSpeculatively && TM.Bits->GV->getVCallVisibility() ==
1107+
GlobalObject::VCallVisibilityPublic)
10901108
return false;
10911109

10921110
Function *Fn = nullptr;
@@ -1105,6 +1123,12 @@ bool DevirtModule::tryFindVirtualCallTargets(
11051123
if (Fn->getName() == "__cxa_pure_virtual")
11061124
continue;
11071125

1126+
// In most cases empty functions will be overridden by the
1127+
// implementation of the derived class, so we can skip them.
1128+
if (ClDevirtualizeSpeculatively && Fn->getReturnType()->isVoidTy() &&
1129+
Fn->getInstructionCount() <= 1)
1130+
continue;
1131+
11081132
// We can disregard unreachable functions as possible call targets, as
11091133
// unreachable functions shouldn't be called.
11101134
if (mustBeUnreachableFunction(Fn, ExportSummary))
@@ -1223,10 +1247,12 @@ void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
12231247
CallTrap->setDebugLoc(CB.getDebugLoc());
12241248
}
12251249

1226-
// If fallback checking is enabled, add support to compare the virtual
1227-
// function pointer to the devirtualized target. In case of a mismatch,
1228-
// fall back to indirect call.
1229-
if (DevirtCheckMode == WPDCheckMode::Fallback) {
1250+
// If fallback checking or speculative devirtualization are enabled,
1251+
// add support to compare the virtual function pointer to the
1252+
// devirtualized target. In case of a mismatch, fall back to indirect
1253+
// call.
1254+
if (DevirtCheckMode == WPDCheckMode::Fallback ||
1255+
ClDevirtualizeSpeculatively) {
12301256
MDNode *Weights = MDBuilder(M.getContext()).createLikelyBranchWeights();
12311257
// Version the indirect call site. If the called value is equal to the
12321258
// given callee, 'NewInst' will be executed, otherwise the original call
@@ -1325,10 +1351,10 @@ bool DevirtModule::trySingleImplDevirt(
13251351
if (!IsExported)
13261352
return false;
13271353

1328-
// If the only implementation has local linkage, we must promote to external
1329-
// to make it visible to thin LTO objects. We can only get here during the
1330-
// ThinLTO export phase.
1331-
if (TheFn->hasLocalLinkage()) {
1354+
// Out of speculative devirtualization mode, if the only implementation has
1355+
// local linkage, we must promote to external to make it visible to thin LTO
1356+
// objects.
1357+
if (!ClDevirtualizeSpeculatively && TheFn->hasLocalLinkage()) {
13321358
std::string NewName = (TheFn->getName() + ".llvm.merged").str();
13331359

13341360
// Since we are renaming the function, any comdats with the same name must
@@ -2350,6 +2376,11 @@ bool DevirtModule::run() {
23502376

23512377
Function *TypeTestFunc =
23522378
Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_test);
2379+
// If we are in speculative devirtualization mode, we can work on the public
2380+
// type test intrinsics.
2381+
if (!TypeTestFunc && ClDevirtualizeSpeculatively)
2382+
TypeTestFunc =
2383+
Intrinsic::getDeclarationIfExists(&M, Intrinsic::public_type_test);
23532384
Function *TypeCheckedLoadFunc =
23542385
Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_checked_load);
23552386
Function *TypeCheckedLoadRelativeFunc = Intrinsic::getDeclarationIfExists(
@@ -2472,8 +2503,11 @@ bool DevirtModule::run() {
24722503
.WPDRes[S.first.ByteOffset];
24732504
if (tryFindVirtualCallTargets(TargetsForSlot, TypeMemberInfos,
24742505
S.first.ByteOffset, ExportSummary)) {
2475-
2476-
if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) {
2506+
bool SingleImplDevirt =
2507+
trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res);
2508+
// Out of speculative devirtualization mode, Try to apply virtual constant
2509+
// propagation or branch funneling.
2510+
if (!SingleImplDevirt && !ClDevirtualizeSpeculatively) {
24772511
DidVirtualConstProp |=
24782512
tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
24792513

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
; -stats requires asserts
2+
; REQUIRES: asserts
3+
4+
; Check that we can still devirtualize outside LTO mode when speculative devirtualization is enabled.
5+
; Check that we skip devirtualization for empty functions in speculative devirtualization mode
6+
7+
; RUN: opt -S -passes=wholeprogramdevirt -devirtualize-speculatively \
8+
; RUN: -pass-remarks=wholeprogramdevirt -stats %s 2>&1 | FileCheck %s
9+
10+
target datalayout = "e-p:64:64"
11+
target triple = "x86_64-unknown-linux-gnu"
12+
13+
; CHECK: remark: devirt-single.cc:30:32: single-impl: devirtualized a call to vf
14+
; CHECK: remark: devirt-single.cc:41:32: single-impl: devirtualized a call to vf
15+
; CHECK: remark: devirt-single.cc:51:32: single-impl: devirtualized a call to vf
16+
; CHECK: remark: devirt-single.cc:13:0: devirtualized vf
17+
; CHECK-NOT: devirtualized
18+
19+
@vt1 = constant [1 x ptr] [ptr @vf], !type !8
20+
@vt2 = constant [1 x ptr] [ptr @vf_empty], !type !12
21+
22+
define i1 @vf(ptr %this) #0 !dbg !7 {
23+
ret i1 true
24+
}
25+
26+
; This should NOT be devirtualized because during non-lto empty functions
27+
; are skipped.
28+
define void @vf_empty(ptr %this) !dbg !11 {
29+
ret void
30+
}
31+
32+
; CHECK: define void @call
33+
define void @call(ptr %obj) #1 !dbg !5 {
34+
%vtable = load ptr, ptr %obj
35+
%p = call i1 @llvm.type.test(ptr %vtable, metadata !"typeid")
36+
call void @llvm.assume(i1 %p)
37+
%fptr = load ptr, ptr %vtable
38+
; CHECK: if.true.direct_targ:
39+
; CHECK: call i1 @vf(
40+
; CHECK: if.false.orig_indirect:
41+
; CHECK: call i1 %fptr(
42+
call i1 %fptr(ptr %obj), !dbg !6
43+
ret void
44+
}
45+
46+
47+
; CHECK: define void @call1
48+
define void @call1(ptr %obj) #1 !dbg !9 {
49+
%vtable = load ptr, ptr %obj
50+
%p = call i1 @llvm.type.test(ptr %vtable, metadata !"typeid1")
51+
call void @llvm.assume(i1 %p)
52+
%fptr = load ptr, ptr %vtable, align 8
53+
; CHECK: call i1 %fptr
54+
%1 = call i1 %fptr(ptr %obj), !dbg !10
55+
ret void
56+
}
57+
declare ptr @llvm.load.relative.i32(ptr, i32)
58+
59+
@vt3 = private unnamed_addr constant [1 x i32] [
60+
i32 trunc (i64 sub (i64 ptrtoint (ptr dso_local_equivalent @vf to i64), i64 ptrtoint (ptr @vt3 to i64)) to i32)
61+
], align 4, !type !15
62+
63+
; CHECK: define void @call2
64+
define void @call2(ptr %obj) #1 !dbg !13 {
65+
%vtable = load ptr, ptr %obj
66+
%p = call i1 @llvm.type.test(ptr %vtable, metadata !"typeid2")
67+
call void @llvm.assume(i1 %p)
68+
%fptr = call ptr @llvm.load.relative.i32(ptr %vtable, i32 0)
69+
; CHECK: if.true.direct_targ:
70+
; CHECK: call i1 @vf(
71+
; CHECK: if.false.orig_indirect:
72+
; CHECK: call i1 %fptr(
73+
call i1 %fptr(ptr %obj), !dbg !14
74+
ret void
75+
}
76+
77+
@_ZTV1A.local = private unnamed_addr constant { [3 x i32] } { [3 x i32] [
78+
i32 0, ; offset to top
79+
i32 0, ; rtti
80+
i32 trunc (i64 sub (i64 ptrtoint (ptr dso_local_equivalent @vf to i64), i64 ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1A.local, i32 0, i32 0, i32 2) to i64)) to i32) ; vf_emptyunc offset
81+
] }, align 4, !type !18
82+
83+
; CHECK: define void @call3
84+
define void @call3(ptr %obj) #1 !dbg !16 {
85+
%vtable = load ptr, ptr %obj
86+
%p = call i1 @llvm.type.test(ptr %vtable, metadata !"typeid3")
87+
call void @llvm.assume(i1 %p)
88+
%fptr = call ptr @llvm.load.relative.i32(ptr %vtable, i32 8)
89+
; CHECK: if.true.direct_targ:
90+
; CHECK: call i1 @vf(
91+
; CHECK: if.false.orig_indirect:
92+
; CHECK: call i1 %fptr(
93+
call i1 %fptr(ptr %obj), !dbg !17
94+
ret void
95+
}
96+
97+
98+
declare i1 @llvm.type.test(ptr, metadata)
99+
declare void @llvm.assume(i1)
100+
101+
!llvm.dbg.cu = !{!0}
102+
!llvm.module.flags = !{!2, !3}
103+
!llvm.ident = !{!4}
104+
105+
!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "clang version 4.0.0 (trunk 278098)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug)
106+
!1 = !DIFile(filename: "devirt-single.cc", directory: ".")
107+
!2 = !{i32 2, !"Dwarf Version", i32 4}
108+
!3 = !{i32 2, !"Debug Info Version", i32 3}
109+
!4 = !{!"clang version 4.0.0 (trunk 278098)"}
110+
!5 = distinct !DISubprogram(name: "call", linkageName: "_Z4callPv", scope: !1, file: !1, line: 29, isLocal: false, isDefinition: true, scopeLine: 9, flags: DIFlagPrototyped, isOptimized: false, unit: !0)
111+
!6 = !DILocation(line: 30, column: 32, scope: !5)
112+
!7 = distinct !DISubprogram(name: "vf", linkageName: "_ZN3vt12vfEv", scope: !1, file: !1, line: 13, isLocal: false, isDefinition: true, scopeLine: 13, flags: DIFlagPrototyped, isOptimized: false, unit: !0)
113+
!8 = !{i32 0, !"typeid"}
114+
115+
!9 = distinct !DISubprogram(name: "call1", linkageName: "_Z5call1Pv", scope: !1, file: !1, line: 31, isLocal: false, isDefinition: true, scopeLine: 9, flags: DIFlagPrototyped, isOptimized: false, unit: !0)
116+
!10 = !DILocation(line: 35, column: 32, scope: !9)
117+
!11 = distinct !DISubprogram(name: "vf_empty", linkageName: "_ZN3vt18vf_emptyEv", scope: !1, file: !1, line: 23, isLocal: false, isDefinition: true, scopeLine: 23, flags: DIFlagPrototyped, isOptimized: false, unit: !0)
118+
!12 = !{i32 0, !"typeid1"}
119+
120+
!13 = distinct !DISubprogram(name: "call2", linkageName: "_Z5call2Pv", scope: !1, file: !1, line: 40, isLocal: false, isDefinition: true, scopeLine: 9, flags: DIFlagPrototyped, isOptimized: false, unit: !0)
121+
!14 = !DILocation(line: 41, column: 32, scope: !13)
122+
!15 = !{i32 0, !"typeid2"}
123+
124+
!16 = distinct !DISubprogram(name: "call3", linkageName: "_Z5call3Pv", scope: !1, file: !1, line: 50, isLocal: false, isDefinition: true, scopeLine: 9, flags: DIFlagPrototyped, isOptimized: false, unit: !0)
125+
!17 = !DILocation(line: 51, column: 32, scope: !16)
126+
!18 = !{i32 0, !"typeid3"}
127+
128+
129+
130+
; CHECK: 1 wholeprogramdevirt - Number of whole program devirtualization targets
131+
; CHECK: 3 wholeprogramdevirt - Number of single implementation devirtualizations

llvm/test/Transforms/WholeProgramDevirt/virtual-const-prop-check.ll

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111
; Check wildcard
1212
; RUN: opt -S -passes=wholeprogramdevirt -whole-program-visibility -pass-remarks=wholeprogramdevirt -wholeprogramdevirt-skip=vf?i1 %s 2>&1 | FileCheck %s --check-prefix=SKIP
1313

14+
; Check that no stats are reported in speculative devirtualization mode as the virtual const prop is disabled.
15+
; RUN: opt -S -passes=wholeprogramdevirt -devirtualize-speculatively -stats %s 2>&1 | FileCheck %s --check-prefix=CHECK-SPECULATIVE-WPD
16+
1417
target datalayout = "e-p:64:64"
1518
target triple = "x86_64-unknown-linux-gnu"
1619

@@ -225,3 +228,7 @@ declare ptr @llvm.load.relative.i32(ptr, i32)
225228
; CHECK: 2 wholeprogramdevirt - Number of unique return value optimizations
226229
; CHECK: 2 wholeprogramdevirt - Number of virtual constant propagations
227230
; CHECK: 2 wholeprogramdevirt - Number of 1 bit virtual constant propagations
231+
232+
; CHECK-SPECULATIVE-WPD-NOT: 0 wholeprogramdevirt - Number of unique return value optimizations
233+
; CHECK-SPECULATIVE-WPD-NOT: 0 wholeprogramdevirt - Number of virtual constant propagations
234+
; CHECK-SPECULATIVE-WPD-NOT: 0 wholeprogramdevirt - Number of 1 bit virtual constant propagations

0 commit comments

Comments
 (0)