1//===- JumpTableToSwitch.cpp ----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Transforms/Scalar/JumpTableToSwitch.h"
10#include "llvm/ADT/STLExtras.h"
11#include "llvm/ADT/SmallVector.h"
12#include "llvm/ADT/Statistic.h"
13#include "llvm/Analysis/ConstantFolding.h"
14#include "llvm/Analysis/DomTreeUpdater.h"
15#include "llvm/Analysis/OptimizationRemarkEmitter.h"
16#include "llvm/Analysis/PostDominators.h"
17#include "llvm/IR/IRBuilder.h"
18#include "llvm/IR/LLVMContext.h"
19#include "llvm/IR/ProfDataUtils.h"
20#include "llvm/ProfileData/InstrProf.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Transforms/Utils/BasicBlockUtils.h"
23#include <limits>
24
25using namespace llvm;
26
27static cl::opt<unsigned>
28 JumpTableSizeThreshold("jump-table-to-switch-size-threshold", cl::Hidden,
29 cl::desc("Only split jump tables with size less or "
30 "equal than JumpTableSizeThreshold."),
31 cl::init(Val: 10));
32
33// TODO: Consider adding a cost model for profitability analysis of this
34// transformation. Currently we replace a jump table with a switch if all the
35// functions in the jump table are smaller than the provided threshold.
36static cl::opt<unsigned> FunctionSizeThreshold(
37 "jump-table-to-switch-function-size-threshold", cl::Hidden,
38 cl::desc("Only split jump tables containing functions whose sizes are less "
39 "or equal than this threshold."),
40 cl::init(Val: 50));
41
42#define DEBUG_TYPE "jump-table-to-switch"
43
44STATISTIC(NumEligibleJumpTables, "The number of jump tables seen by the pass "
45 "that can be converted if deemed profitable.");
46STATISTIC(NumJumpTablesConverted,
47 "The number of jump tables converted into switches.");
48
49namespace {
50struct JumpTableTy {
51 Value *Index;
52 SmallVector<Function *, 10> Funcs;
53};
54} // anonymous namespace
55
56static std::optional<JumpTableTy> parseJumpTable(GetElementPtrInst *GEP,
57 PointerType *PtrTy,
58 FunctionType *CallFTy) {
59 Constant *Ptr = dyn_cast<Constant>(Val: GEP->getPointerOperand());
60 if (!Ptr)
61 return std::nullopt;
62
63 GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: Ptr);
64 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
65 return std::nullopt;
66
67 Function &F = *GEP->getParent()->getParent();
68 const DataLayout &DL = F.getDataLayout();
69 const unsigned BitWidth =
70 DL.getIndexSizeInBits(AS: GEP->getPointerAddressSpace());
71 SmallMapVector<Value *, APInt, 4> VariableOffsets;
72 APInt ConstantOffset(BitWidth, 0);
73 if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
74 return std::nullopt;
75 if (VariableOffsets.size() != 1)
76 return std::nullopt;
77 // TODO: consider supporting more general patterns
78 if (!ConstantOffset.isZero())
79 return std::nullopt;
80 APInt StrideBytes = VariableOffsets.front().second;
81 const uint64_t JumpTableSizeBytes = GV->getGlobalSize(DL);
82 if (JumpTableSizeBytes % StrideBytes.getZExtValue() != 0)
83 return std::nullopt;
84 ++NumEligibleJumpTables;
85 const uint64_t N = JumpTableSizeBytes / StrideBytes.getZExtValue();
86 if (N > JumpTableSizeThreshold)
87 return std::nullopt;
88
89 JumpTableTy JumpTable;
90 JumpTable.Index = VariableOffsets.front().first;
91 JumpTable.Funcs.reserve(N);
92 for (uint64_t Index = 0; Index < N; ++Index) {
93 // ConstantOffset is zero.
94 APInt Offset = Index * StrideBytes;
95 Constant *C =
96 ConstantFoldLoadFromConst(C: GV->getInitializer(), Ty: PtrTy, Offset, DL);
97 auto *Func = dyn_cast_or_null<Function>(Val: C);
98 if (!Func || Func->isDeclaration() || Func->getFunctionType() != CallFTy ||
99 Func->getInstructionCount() > FunctionSizeThreshold)
100 return std::nullopt;
101 JumpTable.Funcs.push_back(Elt: Func);
102 }
103 return JumpTable;
104}
105
106static BasicBlock *
107expandToSwitch(CallBase *CB, const JumpTableTy &JT, DomTreeUpdater &DTU,
108 OptimizationRemarkEmitter &ORE,
109 llvm::function_ref<GlobalValue::GUID(const Function &)>
110 GetGuidForFunction) {
111 ++NumJumpTablesConverted;
112 const bool IsVoid = CB->getType() == Type::getVoidTy(C&: CB->getContext());
113
114 SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
115 BasicBlock *BB = CB->getParent();
116 BasicBlock *Tail = SplitBlock(Old: BB, SplitPt: CB, DTU: &DTU, LI: nullptr, MSSAU: nullptr,
117 BBName: BB->getName() + Twine(".tail"));
118 DTUpdates.push_back(Elt: {DominatorTree::Delete, BB, Tail});
119 BB->getTerminator()->eraseFromParent();
120
121 Function &F = *BB->getParent();
122 BasicBlock *BBUnreachable = BasicBlock::Create(
123 Context&: F.getContext(), Name: "default.switch.case.unreachable", Parent: &F, InsertBefore: Tail);
124 IRBuilder<> BuilderUnreachable(BBUnreachable);
125 BuilderUnreachable.CreateUnreachable();
126
127 IRBuilder<> Builder(BB);
128 SwitchInst *Switch = Builder.CreateSwitch(V: JT.Index, Dest: BBUnreachable);
129 DTUpdates.push_back(Elt: {DominatorTree::Insert, BB, BBUnreachable});
130
131 IRBuilder<> BuilderTail(CB);
132 PHINode *PHI =
133 IsVoid ? nullptr : BuilderTail.CreatePHI(Ty: CB->getType(), NumReservedValues: JT.Funcs.size());
134 const auto *ProfMD = CB->getMetadata(KindID: LLVMContext::MD_prof);
135
136 SmallVector<uint64_t> BranchWeights;
137 DenseMap<GlobalValue::GUID, uint64_t> GuidToCounter;
138 const bool HadProfile = isValueProfileMD(ProfileData: ProfMD);
139 if (HadProfile) {
140 // The assumptions, coming in, are that the functions in JT.Funcs are
141 // defined in this module (from parseJumpTable).
142 assert(llvm::all_of(
143 JT.Funcs, [](const Function *F) { return F && !F->isDeclaration(); }));
144 BranchWeights.reserve(N: JT.Funcs.size() + 1);
145 // The first is the default target, which is the unreachable block created
146 // above.
147 BranchWeights.push_back(Elt: 0U);
148 uint64_t TotalCount = 0;
149 auto Targets = getValueProfDataFromInst(
150 Inst: *CB, ValueKind: InstrProfValueKind::IPVK_IndirectCallTarget,
151 MaxNumValueData: std::numeric_limits<uint32_t>::max(), TotalC&: TotalCount);
152
153 for (const auto &[G, C] : Targets) {
154 [[maybe_unused]] auto It = GuidToCounter.insert(KV: {G, C});
155 // We should always be inserting as it is verifier-enforced IR invariant
156 // that VP metadata does not have duplicate values.
157 assert(It.second);
158 }
159 }
160 for (auto [Index, Func] : llvm::enumerate(First: JT.Funcs)) {
161 BasicBlock *B = BasicBlock::Create(Context&: Func->getContext(),
162 Name: "call." + Twine(Index), Parent: &F, InsertBefore: Tail);
163 DTUpdates.push_back(Elt: {DominatorTree::Insert, BB, B});
164 DTUpdates.push_back(Elt: {DominatorTree::Insert, B, Tail});
165
166 CallBase *Call = cast<CallBase>(Val: CB->clone());
167 // The MD_prof metadata (VP kind), if it existed, can be dropped, it doesn't
168 // make sense on a direct call. Note that the values are used for the branch
169 // weights of the switch.
170 Call->setMetadata(KindID: LLVMContext::MD_prof, Node: nullptr);
171 Call->setCalledFunction(Func);
172 Call->insertInto(ParentBB: B, It: B->end());
173 Switch->addCase(
174 OnVal: cast<ConstantInt>(Val: ConstantInt::get(Ty: JT.Index->getType(), V: Index)), Dest: B);
175 GlobalValue::GUID FctID = GetGuidForFunction(*Func);
176 // It'd be OK to _not_ find target functions in GuidToCounter, e.g. suppose
177 // just some of the jump targets are taken (for the given profile).
178 BranchWeights.push_back(Elt: FctID == 0U ? 0U
179 : GuidToCounter.lookup_or(Val: FctID, Default: 0U));
180 UncondBrInst::Create(Target: Tail, InsertBefore: B);
181 if (PHI)
182 PHI->addIncoming(V: Call, BB: B);
183 }
184 DTU.applyUpdates(Updates: DTUpdates);
185 ORE.emit(RemarkBuilder: [&]() {
186 return OptimizationRemark(DEBUG_TYPE, "ReplacedJumpTableWithSwitch", CB)
187 << "expanded indirect call into switch";
188 });
189 // Only set branch weights on the switch if we have non-zero branch weights.
190 // We can have no non-zero branch weights while having VP metadata if for
191 // example, all of the functions are external and not instrumented.
192 if (HadProfile && llvm::any_of(Range&: BranchWeights, P: not_equal_to(Arg: 0))) {
193 setBranchWeights(I&: *Switch, Weights: downscaleWeights(Weights: BranchWeights),
194 /*IsExpected=*/false);
195 } else
196 setExplicitlyUnknownBranchWeights(I&: *Switch, DEBUG_TYPE);
197 if (PHI)
198 CB->replaceAllUsesWith(V: PHI);
199 CB->eraseFromParent();
200 return Tail;
201}
202
203PreservedAnalyses JumpTableToSwitchPass::run(Function &F,
204 FunctionAnalysisManager &AM) {
205 OptimizationRemarkEmitter &ORE =
206 AM.getResult<OptimizationRemarkEmitterAnalysis>(IR&: F);
207 DominatorTree *DT = AM.getCachedResult<DominatorTreeAnalysis>(IR&: F);
208 PostDominatorTree *PDT = AM.getCachedResult<PostDominatorTreeAnalysis>(IR&: F);
209 DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
210 bool Changed = false;
211 auto FuncToGuid = [&](const Function &Fct) {
212 if (const auto MaybeGUID = Fct.getGUIDIfAssigned(); MaybeGUID)
213 return *MaybeGUID;
214
215 return Function::getGUIDAssumingExternalLinkage(
216 GlobalName: getIRPGOFuncName(F: Fct, InLTO));
217 };
218
219 for (BasicBlock &BB : make_early_inc_range(Range&: F)) {
220 BasicBlock *CurrentBB = &BB;
221 while (CurrentBB) {
222 BasicBlock *SplittedOutTail = nullptr;
223 for (Instruction &I : make_early_inc_range(Range&: *CurrentBB)) {
224 auto *Call = dyn_cast<CallInst>(Val: &I);
225 if (!Call || Call->getCalledFunction() || Call->isMustTailCall())
226 continue;
227 auto *L = dyn_cast<LoadInst>(Val: Call->getCalledOperand());
228 // Skip atomic or volatile loads.
229 if (!L || !L->isSimple())
230 continue;
231 auto *GEP = dyn_cast<GetElementPtrInst>(Val: L->getPointerOperand());
232 if (!GEP)
233 continue;
234 auto *PtrTy = dyn_cast<PointerType>(Val: L->getType());
235 assert(PtrTy && "call operand must be a pointer");
236 std::optional<JumpTableTy> JumpTable =
237 parseJumpTable(GEP, PtrTy, CallFTy: Call->getFunctionType());
238 if (!JumpTable)
239 continue;
240 SplittedOutTail =
241 expandToSwitch(CB: Call, JT: *JumpTable, DTU, ORE, GetGuidForFunction: FuncToGuid);
242 Changed = true;
243 break;
244 }
245 CurrentBB = SplittedOutTail ? SplittedOutTail : nullptr;
246 }
247 }
248
249 if (!Changed)
250 return PreservedAnalyses::all();
251
252 PreservedAnalyses PA;
253 if (DT)
254 PA.preserve<DominatorTreeAnalysis>();
255 if (PDT)
256 PA.preserve<PostDominatorTreeAnalysis>();
257 return PA;
258}
259