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.addPreservedID(LowerInvokePassID);
74 CaseRange(Constant *low, Constant *high, BasicBlock *bb)
75 : Low(low), High(high), BB(bb) {}
78 typedef std::vector<CaseRange> CaseVector;
79 typedef std::vector<CaseRange>::iterator CaseItr;
81 void processSwitchInst(SwitchInst *SI);
83 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
84 ConstantInt *LowerBound, ConstantInt *UpperBound,
85 Value *Val, BasicBlock *Predecessor,
86 BasicBlock *OrigBlock, BasicBlock *Default,
87 const std::vector<IntRange> &UnreachableRanges);
88 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
90 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
93 /// The comparison function for sorting the switch case values in the vector.
94 /// WARNING: Case ranges should be disjoint!
96 bool operator () (const LowerSwitch::CaseRange& C1,
97 const LowerSwitch::CaseRange& C2) {
99 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
100 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
101 return CI1->getValue().slt(CI2->getValue());
106 char LowerSwitch::ID = 0;
107 INITIALIZE_PASS(LowerSwitch, "lowerswitch",
108 "Lower SwitchInst's to branches", false, false)
110 // Publicly exposed interface to pass...
111 char &llvm::LowerSwitchID = LowerSwitch::ID;
112 // createLowerSwitchPass - Interface to this file...
113 FunctionPass *llvm::createLowerSwitchPass() {
114 return new LowerSwitch();
117 bool LowerSwitch::runOnFunction(Function &F) {
118 bool Changed = false;
120 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
121 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
123 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
125 processSwitchInst(SI);
132 // operator<< - Used for debugging purposes.
134 static raw_ostream& operator<<(raw_ostream &O,
135 const LowerSwitch::CaseVector &C)
137 static raw_ostream& operator<<(raw_ostream &O,
138 const LowerSwitch::CaseVector &C) {
141 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
142 E = C.end(); B != E; ) {
143 O << *B->Low << " -" << *B->High;
144 if (++B != E) O << ", ";
150 // \brief Update the first occurrence of the "switch statement" BB in the PHI
151 // node with the "new" BB. The other occurrences will:
153 // 1) Be updated by subsequent calls to this function. Switch statements may
154 // have more than one outcoming edge into the same BB if they all have the same
155 // value. When the switch statement is converted these incoming edges are now
156 // coming from multiple BBs.
157 // 2) Removed if subsequent incoming values now share the same case, i.e.,
158 // multiple outcome edges are condensed into one. This is necessary to keep the
159 // number of phi values equal to the number of branches to SuccBB.
160 static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
161 unsigned NumMergedCases) {
162 for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
164 PHINode *PN = cast<PHINode>(I);
166 // Only update the first occurence.
167 unsigned Idx = 0, E = PN->getNumIncomingValues();
168 unsigned LocalNumMergedCases = NumMergedCases;
169 for (; Idx != E; ++Idx) {
170 if (PN->getIncomingBlock(Idx) == OrigBB) {
171 PN->setIncomingBlock(Idx, NewBB);
176 // Remove additional occurences coming from condensed cases and keep the
177 // number of incoming values equal to the number of branches to SuccBB.
178 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
179 if (PN->getIncomingBlock(Idx) == OrigBB) {
180 PN->removeIncomingValue(Idx);
181 LocalNumMergedCases--;
186 // switchConvert - Convert the switch statement into a binary lookup of
187 // the case values. The function recursively builds this tree.
188 // LowerBound and UpperBound are used to keep track of the bounds for Val
189 // that have already been checked by a block emitted by one of the previous
190 // calls to switchConvert in the call stack.
192 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
193 ConstantInt *UpperBound, Value *Val,
194 BasicBlock *Predecessor, BasicBlock *OrigBlock,
196 const std::vector<IntRange> &UnreachableRanges) {
197 unsigned Size = End - Begin;
200 // Check if the Case Range is perfectly squeezed in between
201 // already checked Upper and Lower bounds. If it is then we can avoid
202 // emitting the code that checks if the value actually falls in the range
203 // because the bounds already tell us so.
204 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
205 unsigned NumMergedCases = 0;
206 if (LowerBound && UpperBound)
208 UpperBound->getSExtValue() - LowerBound->getSExtValue();
209 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
212 return newLeafBlock(*Begin, Val, OrigBlock, Default);
215 unsigned Mid = Size / 2;
216 std::vector<CaseRange> LHS(Begin, Begin + Mid);
217 DEBUG(dbgs() << "LHS: " << LHS << "\n");
218 std::vector<CaseRange> RHS(Begin + Mid, End);
219 DEBUG(dbgs() << "RHS: " << RHS << "\n");
221 CaseRange &Pivot = *(Begin + Mid);
222 DEBUG(dbgs() << "Pivot ==> "
223 << cast<ConstantInt>(Pivot.Low)->getValue()
224 << " -" << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
226 // NewLowerBound here should never be the integer minimal value.
227 // This is because it is computed from a case range that is never
228 // the smallest, so there is always a case range that has at least
230 ConstantInt *NewLowerBound = cast<ConstantInt>(Pivot.Low);
232 // Because NewLowerBound is never the smallest representable integer
233 // it is safe here to subtract one.
234 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
235 NewLowerBound->getValue() - 1);
237 if (!UnreachableRanges.empty()) {
238 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
239 int64_t GapLow = cast<ConstantInt>(LHS.back().High)->getSExtValue() + 1;
240 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
241 IntRange Gap = { GapLow, GapHigh };
242 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
243 NewUpperBound = cast<ConstantInt>(LHS.back().High);
246 DEBUG(dbgs() << "LHS Bounds ==> ";
248 dbgs() << cast<ConstantInt>(LowerBound)->getSExtValue();
252 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
253 dbgs() << "RHS Bounds ==> ";
254 dbgs() << NewLowerBound->getSExtValue() << " - ";
256 dbgs() << cast<ConstantInt>(UpperBound)->getSExtValue() << "\n";
261 // Create a new node that checks if the value is < pivot. Go to the
262 // left branch if it is and right branch if not.
263 Function* F = OrigBlock->getParent();
264 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
266 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
267 Val, Pivot.Low, "Pivot");
269 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
270 NewUpperBound, Val, NewNode, OrigBlock,
271 Default, UnreachableRanges);
272 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
273 UpperBound, Val, NewNode, OrigBlock,
274 Default, UnreachableRanges);
276 Function::iterator FI = OrigBlock;
277 F->getBasicBlockList().insert(++FI, NewNode);
278 NewNode->getInstList().push_back(Comp);
280 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
284 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
285 // checks if the switch's value == the case's value. If not, then it
286 // jumps to the default branch. At this point in the tree, the value
287 // can't be another valid case value, so the jump to the "default" branch
290 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
291 BasicBlock* OrigBlock,
294 Function* F = OrigBlock->getParent();
295 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
296 Function::iterator FI = OrigBlock;
297 F->getBasicBlockList().insert(++FI, NewLeaf);
300 ICmpInst* Comp = nullptr;
301 if (Leaf.Low == Leaf.High) {
302 // Make the seteq instruction...
303 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
304 Leaf.Low, "SwitchLeaf");
306 // Make range comparison
307 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
308 // Val >= Min && Val <= Hi --> Val <= Hi
309 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
311 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
312 // Val >= 0 && Val <= Hi --> Val <=u Hi
313 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
316 // Emit V-Lo <=u Hi-Lo
317 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
318 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
319 Val->getName()+".off",
321 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
322 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
327 // Make the conditional branch...
328 BasicBlock* Succ = Leaf.BB;
329 BranchInst::Create(Succ, Default, Comp, NewLeaf);
331 // If there were any PHI nodes in this successor, rewrite one entry
332 // from OrigBlock to come from NewLeaf.
333 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
334 PHINode* PN = cast<PHINode>(I);
335 // Remove all but one incoming entries from the cluster
336 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
337 cast<ConstantInt>(Leaf.Low)->getSExtValue();
338 for (uint64_t j = 0; j < Range; ++j) {
339 PN->removeIncomingValue(OrigBlock);
342 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
343 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
344 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
350 // Clusterify - Transform simple list of Cases into list of CaseRange's
351 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
352 unsigned numCmps = 0;
354 // Start with "simple" cases
355 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
356 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
357 i.getCaseSuccessor()));
359 std::sort(Cases.begin(), Cases.end(), CaseCmp());
361 // Merge case into clusters
363 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
365 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
366 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
367 BasicBlock* nextBB = J->BB;
368 BasicBlock* currentBB = I->BB;
370 // If the two neighboring cases go to the same destination, merge them
371 // into a single case.
372 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
380 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
381 if (I->Low != I->High)
382 // A range counts double, since it requires two compares.
389 // processSwitchInst - Replace the specified switch instruction with a sequence
390 // of chained if-then insts in a balanced binary search.
392 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
393 BasicBlock *CurBlock = SI->getParent();
394 BasicBlock *OrigBlock = CurBlock;
395 Function *F = CurBlock->getParent();
396 Value *Val = SI->getCondition(); // The value we are switching on...
397 BasicBlock* Default = SI->getDefaultDest();
399 // If there is only the default destination, just branch.
400 if (!SI->getNumCases()) {
401 BranchInst::Create(Default, CurBlock);
402 SI->eraseFromParent();
406 // Prepare cases vector.
408 unsigned numCmps = Clusterify(Cases, SI);
409 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
410 << ". Total compares: " << numCmps << "\n");
411 DEBUG(dbgs() << "Cases: " << Cases << "\n");
414 ConstantInt *LowerBound = nullptr;
415 ConstantInt *UpperBound = nullptr;
416 std::vector<IntRange> UnreachableRanges;
418 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
419 // Make the bounds tightly fitted around the case value range, becase we
420 // know that the value passed to the switch must be exactly one of the case
422 assert(!Cases.empty());
423 LowerBound = cast<ConstantInt>(Cases.front().Low);
424 UpperBound = cast<ConstantInt>(Cases.back().High);
426 DenseMap<BasicBlock *, unsigned> Popularity;
428 BasicBlock *PopSucc = nullptr;
430 IntRange R = { INT64_MIN, INT64_MAX };
431 UnreachableRanges.push_back(R);
432 for (const auto &I : Cases) {
433 int64_t Low = cast<ConstantInt>(I.Low)->getSExtValue();
434 int64_t High = cast<ConstantInt>(I.High)->getSExtValue();
436 IntRange &LastRange = UnreachableRanges.back();
437 if (LastRange.Low == Low) {
438 // There is nothing left of the previous range.
439 UnreachableRanges.pop_back();
441 // Terminate the previous range.
442 assert(Low > LastRange.Low);
443 LastRange.High = Low - 1;
445 if (High != INT64_MAX) {
446 IntRange R = { High + 1, INT64_MAX };
447 UnreachableRanges.push_back(R);
451 int64_t N = High - Low + 1;
452 unsigned &Pop = Popularity[I.BB];
453 if ((Pop += N) > MaxPop) {
459 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
460 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
462 assert(I->Low <= I->High);
465 assert(Next->Low > I->High);
470 // Use the most popular block as the new default, reducing the number of
472 assert(MaxPop > 0 && PopSucc);
474 for (CaseItr I = Cases.begin(); I != Cases.end();) {
475 if (I->BB == PopSucc)
481 // If there are no cases left, just branch.
483 BranchInst::Create(Default, CurBlock);
484 SI->eraseFromParent();
489 // Create a new, empty default block so that the new hierarchy of
490 // if-then statements go to this and the PHI nodes are happy.
491 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
492 F->getBasicBlockList().insert(Default, NewDefault);
493 BranchInst::Create(Default, NewDefault);
495 // If there is an entry in any PHI nodes for the default edge, make sure
496 // to update them as well.
497 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
498 PHINode *PN = cast<PHINode>(I);
499 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
500 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
501 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
504 BasicBlock *SwitchBlock =
505 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
506 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
508 // Branch to our shiny new if-then stuff...
509 BranchInst::Create(SwitchBlock, OrigBlock);
511 // We are now done with the switch instruction, delete it.
512 BasicBlock *OldDefault = SI->getDefaultDest();
513 CurBlock->getInstList().erase(SI);
515 // If the Default block has no more predecessors just remove it.
516 if (pred_begin(OldDefault) == pred_end(OldDefault))
517 DeleteDeadBlock(OldDefault);