1 //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The LowerSwitch transformation rewrites switch instructions with a sequence
11 // of branches, which allows targets to get away with not implementing the
12 // switch instruction until it is convenient.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
32 #define DEBUG_TYPE "lower-switch"
38 // Return true iff R is covered by Ranges.
39 static bool IsInRanges(const IntRange &R,
40 const std::vector<IntRange> &Ranges) {
41 // Note: Ranges must be sorted, non-overlapping and non-adjacent.
43 // Find the first range whose High field is >= R.High,
44 // then check if the Low field is <= R.Low. If so, we
45 // have a Range that covers R.
46 auto I = std::lower_bound(
47 Ranges.begin(), Ranges.end(), R,
48 [](const IntRange &A, const IntRange &B) { return A.High < B.High; });
49 return I != Ranges.end() && I->Low <= R.Low;
52 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
54 class LowerSwitch : public FunctionPass {
56 static char ID; // Pass identification, replacement for typeid
57 LowerSwitch() : FunctionPass(ID) {
58 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
61 bool runOnFunction(Function &F) override;
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 // This is a cluster of orthogonal Transforms
65 AU.addPreserved<UnifyFunctionExitNodes>();
66 AU.addPreserved("mem2reg");
67 AU.addPreservedID(LowerInvokePassID);
75 CaseRange(Constant *low = nullptr, Constant *high = nullptr,
76 BasicBlock *bb = nullptr) :
77 Low(low), High(high), BB(bb) { }
80 typedef std::vector<CaseRange> CaseVector;
81 typedef std::vector<CaseRange>::iterator CaseItr;
83 void processSwitchInst(SwitchInst *SI);
85 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
86 ConstantInt *LowerBound, ConstantInt *UpperBound,
87 Value *Val, BasicBlock *Predecessor,
88 BasicBlock *OrigBlock, BasicBlock *Default,
89 const std::vector<IntRange> &UnreachableRanges);
90 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
92 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
95 /// The comparison function for sorting the switch case values in the vector.
96 /// WARNING: Case ranges should be disjoint!
98 bool operator () (const LowerSwitch::CaseRange& C1,
99 const LowerSwitch::CaseRange& C2) {
101 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
102 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
103 return CI1->getValue().slt(CI2->getValue());
108 char LowerSwitch::ID = 0;
109 INITIALIZE_PASS(LowerSwitch, "lowerswitch",
110 "Lower SwitchInst's to branches", false, false)
112 // Publicly exposed interface to pass...
113 char &llvm::LowerSwitchID = LowerSwitch::ID;
114 // createLowerSwitchPass - Interface to this file...
115 FunctionPass *llvm::createLowerSwitchPass() {
116 return new LowerSwitch();
119 bool LowerSwitch::runOnFunction(Function &F) {
120 bool Changed = false;
122 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
123 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
125 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
127 processSwitchInst(SI);
134 // operator<< - Used for debugging purposes.
136 static raw_ostream& operator<<(raw_ostream &O,
137 const LowerSwitch::CaseVector &C)
139 static raw_ostream& operator<<(raw_ostream &O,
140 const LowerSwitch::CaseVector &C) {
143 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
144 E = C.end(); B != E; ) {
145 O << *B->Low << " -" << *B->High;
146 if (++B != E) O << ", ";
152 // \brief Update the first occurrence of the "switch statement" BB in the PHI
153 // node with the "new" BB. The other occurrences will:
155 // 1) Be updated by subsequent calls to this function. Switch statements may
156 // have more than one outcoming edge into the same BB if they all have the same
157 // value. When the switch statement is converted these incoming edges are now
158 // coming from multiple BBs.
159 // 2) Removed if subsequent incoming values now share the same case, i.e.,
160 // multiple outcome edges are condensed into one. This is necessary to keep the
161 // number of phi values equal to the number of branches to SuccBB.
162 static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
163 unsigned NumMergedCases) {
164 for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
166 PHINode *PN = cast<PHINode>(I);
168 // Only update the first occurence.
169 unsigned Idx = 0, E = PN->getNumIncomingValues();
170 unsigned LocalNumMergedCases = NumMergedCases;
171 for (; Idx != E; ++Idx) {
172 if (PN->getIncomingBlock(Idx) == OrigBB) {
173 PN->setIncomingBlock(Idx, NewBB);
178 // Remove additional occurences coming from condensed cases and keep the
179 // number of incoming values equal to the number of branches to SuccBB.
180 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
181 if (PN->getIncomingBlock(Idx) == OrigBB) {
182 PN->removeIncomingValue(Idx);
183 LocalNumMergedCases--;
188 // switchConvert - Convert the switch statement into a binary lookup of
189 // the case values. The function recursively builds this tree.
190 // LowerBound and UpperBound are used to keep track of the bounds for Val
191 // that have already been checked by a block emitted by one of the previous
192 // calls to switchConvert in the call stack.
194 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
195 ConstantInt *UpperBound, Value *Val,
196 BasicBlock *Predecessor, BasicBlock *OrigBlock,
198 const std::vector<IntRange> &UnreachableRanges) {
199 unsigned Size = End - Begin;
202 // Check if the Case Range is perfectly squeezed in between
203 // already checked Upper and Lower bounds. If it is then we can avoid
204 // emitting the code that checks if the value actually falls in the range
205 // because the bounds already tell us so.
206 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
207 unsigned NumMergedCases = 0;
208 if (LowerBound && UpperBound)
210 UpperBound->getSExtValue() - LowerBound->getSExtValue();
211 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
214 return newLeafBlock(*Begin, Val, OrigBlock, Default);
217 unsigned Mid = Size / 2;
218 std::vector<CaseRange> LHS(Begin, Begin + Mid);
219 DEBUG(dbgs() << "LHS: " << LHS << "\n");
220 std::vector<CaseRange> RHS(Begin + Mid, End);
221 DEBUG(dbgs() << "RHS: " << RHS << "\n");
223 CaseRange &Pivot = *(Begin + Mid);
224 DEBUG(dbgs() << "Pivot ==> "
225 << cast<ConstantInt>(Pivot.Low)->getValue()
226 << " -" << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
228 // NewLowerBound here should never be the integer minimal value.
229 // This is because it is computed from a case range that is never
230 // the smallest, so there is always a case range that has at least
232 ConstantInt *NewLowerBound = cast<ConstantInt>(Pivot.Low);
234 // Because NewLowerBound is never the smallest representable integer
235 // it is safe here to subtract one.
236 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
237 NewLowerBound->getValue() - 1);
239 if (!UnreachableRanges.empty()) {
240 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
241 int64_t GapLow = cast<ConstantInt>(LHS.back().High)->getSExtValue() + 1;
242 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
243 IntRange Gap = { GapLow, GapHigh };
244 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
245 NewUpperBound = cast<ConstantInt>(LHS.back().High);
248 DEBUG(dbgs() << "LHS Bounds ==> ";
250 dbgs() << cast<ConstantInt>(LowerBound)->getSExtValue();
254 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
255 dbgs() << "RHS Bounds ==> ";
256 dbgs() << NewLowerBound->getSExtValue() << " - ";
258 dbgs() << cast<ConstantInt>(UpperBound)->getSExtValue() << "\n";
263 // Create a new node that checks if the value is < pivot. Go to the
264 // left branch if it is and right branch if not.
265 Function* F = OrigBlock->getParent();
266 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
268 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
269 Val, Pivot.Low, "Pivot");
271 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
272 NewUpperBound, Val, NewNode, OrigBlock,
273 Default, UnreachableRanges);
274 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
275 UpperBound, Val, NewNode, OrigBlock,
276 Default, UnreachableRanges);
278 Function::iterator FI = OrigBlock;
279 F->getBasicBlockList().insert(++FI, NewNode);
280 NewNode->getInstList().push_back(Comp);
282 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
286 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
287 // checks if the switch's value == the case's value. If not, then it
288 // jumps to the default branch. At this point in the tree, the value
289 // can't be another valid case value, so the jump to the "default" branch
292 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
293 BasicBlock* OrigBlock,
296 Function* F = OrigBlock->getParent();
297 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
298 Function::iterator FI = OrigBlock;
299 F->getBasicBlockList().insert(++FI, NewLeaf);
302 ICmpInst* Comp = nullptr;
303 if (Leaf.Low == Leaf.High) {
304 // Make the seteq instruction...
305 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
306 Leaf.Low, "SwitchLeaf");
308 // Make range comparison
309 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
310 // Val >= Min && Val <= Hi --> Val <= Hi
311 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
313 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
314 // Val >= 0 && Val <= Hi --> Val <=u Hi
315 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
318 // Emit V-Lo <=u Hi-Lo
319 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
320 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
321 Val->getName()+".off",
323 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
324 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
329 // Make the conditional branch...
330 BasicBlock* Succ = Leaf.BB;
331 BranchInst::Create(Succ, Default, Comp, NewLeaf);
333 // If there were any PHI nodes in this successor, rewrite one entry
334 // from OrigBlock to come from NewLeaf.
335 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
336 PHINode* PN = cast<PHINode>(I);
337 // Remove all but one incoming entries from the cluster
338 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
339 cast<ConstantInt>(Leaf.Low)->getSExtValue();
340 for (uint64_t j = 0; j < Range; ++j) {
341 PN->removeIncomingValue(OrigBlock);
344 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
345 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
346 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
352 // Clusterify - Transform simple list of Cases into list of CaseRange's
353 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
354 unsigned numCmps = 0;
356 // Start with "simple" cases
357 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
358 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
359 i.getCaseSuccessor()));
361 std::sort(Cases.begin(), Cases.end(), CaseCmp());
363 // Merge case into clusters
365 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
367 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
368 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
369 BasicBlock* nextBB = J->BB;
370 BasicBlock* currentBB = I->BB;
372 // If the two neighboring cases go to the same destination, merge them
373 // into a single case.
374 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
382 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
383 if (I->Low != I->High)
384 // A range counts double, since it requires two compares.
391 // processSwitchInst - Replace the specified switch instruction with a sequence
392 // of chained if-then insts in a balanced binary search.
394 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
395 BasicBlock *CurBlock = SI->getParent();
396 BasicBlock *OrigBlock = CurBlock;
397 Function *F = CurBlock->getParent();
398 Value *Val = SI->getCondition(); // The value we are switching on...
399 BasicBlock* Default = SI->getDefaultDest();
401 // If there is only the default destination, just branch.
402 if (!SI->getNumCases()) {
403 BranchInst::Create(Default, CurBlock);
404 SI->eraseFromParent();
408 // Prepare cases vector.
410 unsigned numCmps = Clusterify(Cases, SI);
411 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
412 << ". Total compares: " << numCmps << "\n");
413 DEBUG(dbgs() << "Cases: " << Cases << "\n");
416 ConstantInt *LowerBound = nullptr;
417 ConstantInt *UpperBound = nullptr;
418 std::vector<IntRange> UnreachableRanges;
420 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
421 // Make the bounds tightly fitted around the case value range, becase we
422 // know that the value passed to the switch must be exactly one of the case
424 assert(!Cases.empty());
425 LowerBound = cast<ConstantInt>(Cases.front().Low);
426 UpperBound = cast<ConstantInt>(Cases.back().High);
428 DenseMap<BasicBlock *, unsigned> Popularity;
430 BasicBlock *PopSucc = nullptr;
432 IntRange R = { INT64_MIN, INT64_MAX };
433 UnreachableRanges.push_back(R);
434 for (const auto &I : Cases) {
435 int64_t Low = cast<ConstantInt>(I.Low)->getSExtValue();
436 int64_t High = cast<ConstantInt>(I.High)->getSExtValue();
438 IntRange &LastRange = UnreachableRanges.back();
439 if (LastRange.Low == Low) {
440 // There is nothing left of the previous range.
441 UnreachableRanges.pop_back();
443 // Terminate the previous range.
444 assert(Low > LastRange.Low);
445 LastRange.High = Low - 1;
447 if (High != INT64_MAX) {
448 IntRange R = { High + 1, INT64_MAX };
449 UnreachableRanges.push_back(R);
453 int64_t N = High - Low + 1;
454 unsigned &Pop = Popularity[I.BB];
455 if ((Pop += N) > MaxPop) {
461 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
462 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
464 assert(I->Low <= I->High);
467 assert(Next->Low > I->High);
472 // Use the most popular block as the new default, reducing the number of
474 assert(MaxPop > 0 && PopSucc);
476 for (CaseItr I = Cases.begin(); I != Cases.end();) {
477 if (I->BB == PopSucc)
483 // If there are no cases left, just branch.
485 BranchInst::Create(Default, CurBlock);
486 SI->eraseFromParent();
491 // Create a new, empty default block so that the new hierarchy of
492 // if-then statements go to this and the PHI nodes are happy.
493 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
494 F->getBasicBlockList().insert(Default, NewDefault);
495 BranchInst::Create(Default, NewDefault);
497 // If there is an entry in any PHI nodes for the default edge, make sure
498 // to update them as well.
499 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
500 PHINode *PN = cast<PHINode>(I);
501 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
502 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
503 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
506 BasicBlock *SwitchBlock =
507 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
508 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
510 // Branch to our shiny new if-then stuff...
511 BranchInst::Create(SwitchBlock, OrigBlock);
513 // We are now done with the switch instruction, delete it.
514 BasicBlock *OldDefault = SI->getDefaultDest();
515 CurBlock->getInstList().erase(SI);
517 // If the Default block has no more predecessors just remove it.
518 if (pred_begin(OldDefault) == pred_end(OldDefault))
519 DeleteDeadBlock(OldDefault);