Skip to content

Commit 6480240

Browse files
committed
[TailRecursionElim] Adjust function entry count
1 parent d659046 commit 6480240

File tree

5 files changed

+189
-11
lines changed

5 files changed

+189
-11
lines changed

llvm/include/llvm/Passes/PassBuilder.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -763,6 +763,8 @@ class PassBuilder {
763763
IntrusiveRefCntPtr<vfs::FileSystem> FS);
764764
void addPostPGOLoopRotation(ModulePassManager &MPM, OptimizationLevel Level);
765765

766+
bool isInstrumentedPGOUse() const;
767+
766768
// Extension Point callbacks
767769
SmallVector<std::function<void(FunctionPassManager &, OptimizationLevel)>, 2>
768770
PeepholeEPCallbacks;

llvm/include/llvm/Transforms/Scalar/TailRecursionElimination.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,12 @@ namespace llvm {
5858

5959
class Function;
6060

61-
struct TailCallElimPass : PassInfoMixin<TailCallElimPass> {
61+
class TailCallElimPass : public PassInfoMixin<TailCallElimPass> {
62+
const bool UpdateFunctionEntryCount;
63+
64+
public:
65+
TailCallElimPass(bool UpdateFunctionEntryCount = true)
66+
: UpdateFunctionEntryCount(UpdateFunctionEntryCount) {}
6267
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
6368
};
6469
}

llvm/lib/Passes/PassBuilderPipelines.cpp

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -628,7 +628,8 @@ PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
628628
!Level.isOptimizingForSize())
629629
FPM.addPass(PGOMemOPSizeOpt());
630630

631-
FPM.addPass(TailCallElimPass());
631+
FPM.addPass(TailCallElimPass(/*UpdateFunctionEntryCount=*/
632+
isInstrumentedPGOUse()));
632633
FPM.addPass(
633634
SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
634635

@@ -1581,7 +1582,8 @@ PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
15811582
OptimizePM.addPass(DivRemPairsPass());
15821583

15831584
// Try to annotate calls that were created during optimization.
1584-
OptimizePM.addPass(TailCallElimPass());
1585+
OptimizePM.addPass(
1586+
TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
15851587

15861588
// LoopSink (and other loop passes since the last simplifyCFG) might have
15871589
// resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
@@ -2069,7 +2071,8 @@ PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
20692071

20702072
// LTO provides additional opportunities for tailcall elimination due to
20712073
// link-time inlining, and visibility of nocapture attribute.
2072-
FPM.addPass(TailCallElimPass());
2074+
FPM.addPass(
2075+
TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
20732076

20742077
// Run a few AA driver optimizations here and now to cleanup the code.
20752078
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
@@ -2350,3 +2353,8 @@ AAManager PassBuilder::buildDefaultAAPipeline() {
23502353

23512354
return AA;
23522355
}
2356+
2357+
bool PassBuilder::isInstrumentedPGOUse() const {
2358+
return (PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
2359+
!UseCtxProfile.empty();
2360+
}

llvm/lib/Transforms/Scalar/TailRecursionElimination.cpp

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
#include "llvm/ADT/STLExtras.h"
5454
#include "llvm/ADT/SmallPtrSet.h"
5555
#include "llvm/ADT/Statistic.h"
56+
#include "llvm/Analysis/BlockFrequencyInfo.h"
5657
#include "llvm/Analysis/DomTreeUpdater.h"
5758
#include "llvm/Analysis/GlobalsModRef.h"
5859
#include "llvm/Analysis/InstructionSimplify.h"
@@ -75,10 +76,12 @@
7576
#include "llvm/IR/Module.h"
7677
#include "llvm/InitializePasses.h"
7778
#include "llvm/Pass.h"
79+
#include "llvm/Support/CommandLine.h"
7880
#include "llvm/Support/Debug.h"
7981
#include "llvm/Support/raw_ostream.h"
8082
#include "llvm/Transforms/Scalar.h"
8183
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
84+
#include <cmath>
8285
using namespace llvm;
8386

8487
#define DEBUG_TYPE "tailcallelim"
@@ -87,6 +90,11 @@ STATISTIC(NumEliminated, "Number of tail calls removed");
8790
STATISTIC(NumRetDuped, "Number of return duplicated");
8891
STATISTIC(NumAccumAdded, "Number of accumulators introduced");
8992

93+
static cl::opt<bool> ForceDisableBFI(
94+
"tre-disable-entrycount-recompute", cl::init(false), cl::Hidden,
95+
cl::desc("Force disabling recomputing of function entry count, on "
96+
"successful tail recursion elimination."));
97+
9098
/// Scan the specified function for alloca instructions.
9199
/// If it contains any dynamic allocas, returns false.
92100
static bool canTRE(Function &F) {
@@ -409,6 +417,8 @@ class TailRecursionEliminator {
409417
AliasAnalysis *AA;
410418
OptimizationRemarkEmitter *ORE;
411419
DomTreeUpdater &DTU;
420+
BlockFrequencyInfo *const BFI;
421+
const uint64_t OrigEntryBBFreq;
412422

413423
// The below are shared state we want to have available when eliminating any
414424
// calls in the function. There values should be populated by
@@ -438,8 +448,20 @@ class TailRecursionEliminator {
438448

439449
TailRecursionEliminator(Function &F, const TargetTransformInfo *TTI,
440450
AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
441-
DomTreeUpdater &DTU)
442-
: F(F), TTI(TTI), AA(AA), ORE(ORE), DTU(DTU) {}
451+
DomTreeUpdater &DTU, BlockFrequencyInfo *BFI)
452+
: F(F), TTI(TTI), AA(AA), ORE(ORE), DTU(DTU), BFI(BFI),
453+
OrigEntryBBFreq(
454+
BFI ? BFI->getBlockFreq(&F.getEntryBlock()).getFrequency() : 0U) {
455+
if (BFI) {
456+
auto EC = F.getEntryCount();
457+
(void)EC;
458+
assert(
459+
(EC.has_value() && EC->getCount() != 0 && OrigEntryBBFreq) &&
460+
"If the function has an entry count, its entry basic block should "
461+
"have a non-zero frequency. Pass a nullptr BFI if the function has "
462+
"no entry count");
463+
}
464+
}
443465

444466
CallInst *findTRECandidate(BasicBlock *BB);
445467

@@ -460,7 +482,7 @@ class TailRecursionEliminator {
460482
public:
461483
static bool eliminate(Function &F, const TargetTransformInfo *TTI,
462484
AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
463-
DomTreeUpdater &DTU);
485+
DomTreeUpdater &DTU, BlockFrequencyInfo *BFI);
464486
};
465487
} // namespace
466488

@@ -746,6 +768,21 @@ bool TailRecursionEliminator::eliminateCall(CallInst *CI) {
746768
CI->eraseFromParent(); // Remove call.
747769
DTU.applyUpdates({{DominatorTree::Insert, BB, HeaderBB}});
748770
++NumEliminated;
771+
if (OrigEntryBBFreq) {
772+
assert(F.getEntryCount().has_value());
773+
// This pass is not expected to remove BBs, only add an entry BB. For that
774+
// reason, and because the BB here isn't the new entry BB, the BFI lookup is
775+
// expected to succeed.
776+
assert(&F.getEntryBlock() != BB);
777+
auto RelativeBBFreq =
778+
static_cast<double>(BFI->getBlockFreq(BB).getFrequency()) /
779+
static_cast<double>(OrigEntryBBFreq);
780+
auto OldEntryCount = F.getEntryCount()->getCount();
781+
auto ToSubtract =
782+
static_cast<uint64_t>(std::round(RelativeBBFreq * OldEntryCount));
783+
assert(OldEntryCount > ToSubtract);
784+
F.setEntryCount(OldEntryCount - ToSubtract, F.getEntryCount()->getType());
785+
}
749786
return true;
750787
}
751788

@@ -872,7 +909,8 @@ bool TailRecursionEliminator::eliminate(Function &F,
872909
const TargetTransformInfo *TTI,
873910
AliasAnalysis *AA,
874911
OptimizationRemarkEmitter *ORE,
875-
DomTreeUpdater &DTU) {
912+
DomTreeUpdater &DTU,
913+
BlockFrequencyInfo *BFI) {
876914
if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
877915
return false;
878916

@@ -888,7 +926,7 @@ bool TailRecursionEliminator::eliminate(Function &F,
888926
return MadeChange;
889927

890928
// Change any tail recursive calls to loops.
891-
TailRecursionEliminator TRE(F, TTI, AA, ORE, DTU);
929+
TailRecursionEliminator TRE(F, TTI, AA, ORE, DTU, BFI);
892930

893931
for (BasicBlock &BB : F)
894932
MadeChange |= TRE.processBlock(BB);
@@ -930,7 +968,8 @@ struct TailCallElim : public FunctionPass {
930968
return TailRecursionEliminator::eliminate(
931969
F, &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
932970
&getAnalysis<AAResultsWrapperPass>().getAAResults(),
933-
&getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(), DTU);
971+
&getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(), DTU,
972+
nullptr);
934973
}
935974
};
936975
}
@@ -953,14 +992,22 @@ PreservedAnalyses TailCallElimPass::run(Function &F,
953992

954993
TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
955994
AliasAnalysis &AA = AM.getResult<AAManager>(F);
995+
// This must come first. It needs the 2 analyses, meaning, if it came after
996+
// the lines asking for the cached result, should they be nullptr (which, in
997+
// the case of the PDT, is likely), updates to the trees would be missed.
998+
auto *BFI = (!ForceDisableBFI && UpdateFunctionEntryCount &&
999+
F.getEntryCount().has_value() && F.getEntryCount()->getCount())
1000+
? &AM.getResult<BlockFrequencyAnalysis>(F)
1001+
: nullptr;
9561002
auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
9571003
auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
9581004
auto *PDT = AM.getCachedResult<PostDominatorTreeAnalysis>(F);
9591005
// There is no noticable performance difference here between Lazy and Eager
9601006
// UpdateStrategy based on some test results. It is feasible to switch the
9611007
// UpdateStrategy to Lazy if we find it profitable later.
9621008
DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
963-
bool Changed = TailRecursionEliminator::eliminate(F, &TTI, &AA, &ORE, DTU);
1009+
bool Changed =
1010+
TailRecursionEliminator::eliminate(F, &TTI, &AA, &ORE, DTU, BFI);
9641011

9651012
if (!Changed)
9661013
return PreservedAnalyses::all();
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --check-globals
2+
; RUN: opt -passes=tailcallelim -S %s -o - | FileCheck %s
3+
4+
; Test that tail call elimination correctly adjusts function entry counts
5+
; when eliminating tail recursive calls.
6+
7+
; Basic test: eliminate a tail call and adjust entry count
8+
define i32 @test_basic_entry_count_adjustment(i32 %n) !prof !0 {
9+
; CHECK-LABEL: @test_basic_entry_count_adjustment(
10+
; CHECK-NEXT: entry:
11+
; CHECK-NEXT: br label [[TAILRECURSE:%.*]]
12+
; CHECK: tailrecurse:
13+
; CHECK-NEXT: [[N_TR:%.*]] = phi i32 [ [[N:%.*]], [[ENTRY:%.*]] ], [ [[SUB:%.*]], [[IF_THEN:%.*]] ]
14+
; CHECK-NEXT: [[CMP:%.*]] = icmp sgt i32 [[N_TR]], 0
15+
; CHECK-NEXT: br i1 [[CMP]], label [[IF_THEN]], label [[IF_ELSE:%.*]], !prof [[PROF1:![0-9]+]]
16+
; CHECK: if.then:
17+
; CHECK-NEXT: [[SUB]] = sub i32 [[N_TR]], 1
18+
; CHECK-NEXT: br label [[TAILRECURSE]]
19+
; CHECK: if.else:
20+
; CHECK-NEXT: ret i32 0
21+
;
22+
entry:
23+
%cmp = icmp sgt i32 %n, 0
24+
br i1 %cmp, label %if.then, label %if.else, !prof !1
25+
26+
if.then: ; preds = %entry
27+
%sub = sub i32 %n, 1
28+
%call = tail call i32 @test_basic_entry_count_adjustment(i32 %sub)
29+
ret i32 %call
30+
31+
if.else: ; preds = %entry
32+
ret i32 0
33+
}
34+
35+
; Test multiple tail calls in different blocks with different frequencies
36+
define i32 @test_multiple_blocks_entry_count(i32 %n, i32 %flag) !prof !2 {
37+
; CHECK-LABEL: @test_multiple_blocks_entry_count(
38+
; CHECK-NEXT: entry:
39+
; CHECK-NEXT: br label [[TAILRECURSE:%.*]]
40+
; CHECK: tailrecurse:
41+
; CHECK-NEXT: [[N_TR:%.*]] = phi i32 [ [[N:%.*]], [[ENTRY:%.*]] ], [ [[SUB1:%.*]], [[BLOCK1:%.*]] ], [ [[SUB2:%.*]], [[BLOCK2:%.*]] ]
42+
; CHECK-NEXT: [[CMP:%.*]] = icmp sgt i32 [[N_TR]], 0
43+
; CHECK-NEXT: br i1 [[CMP]], label [[CHECK_FLAG:%.*]], label [[BASE_CASE:%.*]]
44+
; CHECK: check.flag:
45+
; CHECK-NEXT: [[CMP_FLAG:%.*]] = icmp eq i32 [[FLAG:%.*]], 1
46+
; CHECK-NEXT: br i1 [[CMP_FLAG]], label [[BLOCK1]], label [[BLOCK2]], !prof [[PROF3:![0-9]+]]
47+
; CHECK: block1:
48+
; CHECK-NEXT: [[SUB1]] = sub i32 [[N_TR]], 1
49+
; CHECK-NEXT: br label [[TAILRECURSE]]
50+
; CHECK: block2:
51+
; CHECK-NEXT: [[SUB2]] = sub i32 [[N_TR]], 2
52+
; CHECK-NEXT: br label [[TAILRECURSE]]
53+
; CHECK: base.case:
54+
; CHECK-NEXT: ret i32 1
55+
;
56+
entry:
57+
%cmp = icmp sgt i32 %n, 0
58+
br i1 %cmp, label %check.flag, label %base.case
59+
60+
check.flag:
61+
%cmp.flag = icmp eq i32 %flag, 1
62+
br i1 %cmp.flag, label %block1, label %block2, !prof !3
63+
64+
block1: ; preds = %check.flag
65+
%sub1 = sub i32 %n, 1
66+
%call1 = tail call i32 @test_multiple_blocks_entry_count(i32 %sub1, i32 %flag)
67+
ret i32 %call1
68+
69+
block2: ; preds = %check.flag
70+
%sub2 = sub i32 %n, 2
71+
%call2 = tail call i32 @test_multiple_blocks_entry_count(i32 %sub2, i32 %flag)
72+
ret i32 %call2
73+
74+
base.case: ; preds = %entry
75+
ret i32 1
76+
}
77+
78+
; Test function without entry count (should not crash)
79+
define i32 @test_no_entry_count(i32 %n) {
80+
; CHECK-LABEL: @test_no_entry_count(
81+
; CHECK-NEXT: entry:
82+
; CHECK-NEXT: br label [[TAILRECURSE:%.*]]
83+
; CHECK: tailrecurse:
84+
; CHECK-NEXT: [[N_TR:%.*]] = phi i32 [ [[N:%.*]], [[ENTRY:%.*]] ], [ [[SUB:%.*]], [[IF_THEN:%.*]] ]
85+
; CHECK-NEXT: [[CMP:%.*]] = icmp sgt i32 [[N_TR]], 0
86+
; CHECK-NEXT: br i1 [[CMP]], label [[IF_THEN]], label [[IF_ELSE:%.*]]
87+
; CHECK: if.then:
88+
; CHECK-NEXT: [[SUB]] = sub i32 [[N_TR]], 1
89+
; CHECK-NEXT: br label [[TAILRECURSE]]
90+
; CHECK: if.else:
91+
; CHECK-NEXT: ret i32 0
92+
;
93+
entry:
94+
%cmp = icmp sgt i32 %n, 0
95+
br i1 %cmp, label %if.then, label %if.else
96+
97+
if.then: ; preds = %entry
98+
%sub = sub i32 %n, 1
99+
%call = tail call i32 @test_no_entry_count(i32 %sub)
100+
ret i32 %call
101+
102+
if.else: ; preds = %entry
103+
ret i32 0
104+
}
105+
106+
; Function entry count metadata
107+
!0 = !{!"function_entry_count", i64 1000}
108+
!1 = !{!"branch_weights", i32 800, i32 200}
109+
!2 = !{!"function_entry_count", i64 2000}
110+
!3 = !{!"branch_weights", i32 100, i32 500}
111+
;.
112+
; CHECK: [[META0:![0-9]+]] = !{!"function_entry_count", i64 200}
113+
; CHECK: [[PROF1]] = !{!"branch_weights", i32 800, i32 200}
114+
; CHECK: [[META2:![0-9]+]] = !{!"function_entry_count", i64 859}
115+
; CHECK: [[PROF3]] = !{!"branch_weights", i32 100, i32 500}
116+
;.

0 commit comments

Comments
 (0)