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/ADT/STLExtras.h"
18 #include "llvm/IR/CFG.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/Pass.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.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(ConstantInt *low, ConstantInt *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, SmallPtrSetImpl<BasicBlock*> &DeleteList);
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;
119 SmallPtrSet<BasicBlock*, 8> DeleteList;
121 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
122 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
124 // If the block is a dead Default block that will be deleted later, don't
125 // waste time processing it.
126 if (DeleteList.count(Cur))
129 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
131 processSwitchInst(SI, DeleteList);
135 for (BasicBlock* BB: DeleteList) {
142 // operator<< - Used for debugging purposes.
144 static raw_ostream& operator<<(raw_ostream &O,
145 const LowerSwitch::CaseVector &C)
147 static raw_ostream& operator<<(raw_ostream &O,
148 const LowerSwitch::CaseVector &C) {
151 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
152 E = C.end(); B != E; ) {
153 O << *B->Low << " -" << *B->High;
154 if (++B != E) O << ", ";
160 // \brief Update the first occurrence of the "switch statement" BB in the PHI
161 // node with the "new" BB. The other occurrences will:
163 // 1) Be updated by subsequent calls to this function. Switch statements may
164 // have more than one outcoming edge into the same BB if they all have the same
165 // value. When the switch statement is converted these incoming edges are now
166 // coming from multiple BBs.
167 // 2) Removed if subsequent incoming values now share the same case, i.e.,
168 // multiple outcome edges are condensed into one. This is necessary to keep the
169 // number of phi values equal to the number of branches to SuccBB.
170 static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
171 unsigned NumMergedCases) {
172 for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
174 PHINode *PN = cast<PHINode>(I);
176 // Only update the first occurrence.
177 unsigned Idx = 0, E = PN->getNumIncomingValues();
178 unsigned LocalNumMergedCases = NumMergedCases;
179 for (; Idx != E; ++Idx) {
180 if (PN->getIncomingBlock(Idx) == OrigBB) {
181 PN->setIncomingBlock(Idx, NewBB);
186 // Remove additional occurrences coming from condensed cases and keep the
187 // number of incoming values equal to the number of branches to SuccBB.
188 SmallVector<unsigned, 8> Indices;
189 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
190 if (PN->getIncomingBlock(Idx) == OrigBB) {
191 Indices.push_back(Idx);
192 LocalNumMergedCases--;
194 // Remove incoming values in the reverse order to prevent invalidating
195 // *successive* index.
196 for (auto III = Indices.rbegin(), IIE = Indices.rend(); III != IIE; ++III)
197 PN->removeIncomingValue(*III);
201 // switchConvert - Convert the switch statement into a binary lookup of
202 // the case values. The function recursively builds this tree.
203 // LowerBound and UpperBound are used to keep track of the bounds for Val
204 // that have already been checked by a block emitted by one of the previous
205 // calls to switchConvert in the call stack.
207 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
208 ConstantInt *UpperBound, Value *Val,
209 BasicBlock *Predecessor, BasicBlock *OrigBlock,
211 const std::vector<IntRange> &UnreachableRanges) {
212 unsigned Size = End - Begin;
215 // Check if the Case Range is perfectly squeezed in between
216 // already checked Upper and Lower bounds. If it is then we can avoid
217 // emitting the code that checks if the value actually falls in the range
218 // because the bounds already tell us so.
219 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
220 unsigned NumMergedCases = 0;
221 if (LowerBound && UpperBound)
223 UpperBound->getSExtValue() - LowerBound->getSExtValue();
224 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
227 return newLeafBlock(*Begin, Val, OrigBlock, Default);
230 unsigned Mid = Size / 2;
231 std::vector<CaseRange> LHS(Begin, Begin + Mid);
232 DEBUG(dbgs() << "LHS: " << LHS << "\n");
233 std::vector<CaseRange> RHS(Begin + Mid, End);
234 DEBUG(dbgs() << "RHS: " << RHS << "\n");
236 CaseRange &Pivot = *(Begin + Mid);
237 DEBUG(dbgs() << "Pivot ==> "
238 << Pivot.Low->getValue()
239 << " -" << Pivot.High->getValue() << "\n");
241 // NewLowerBound here should never be the integer minimal value.
242 // This is because it is computed from a case range that is never
243 // the smallest, so there is always a case range that has at least
245 ConstantInt *NewLowerBound = Pivot.Low;
247 // Because NewLowerBound is never the smallest representable integer
248 // it is safe here to subtract one.
249 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
250 NewLowerBound->getValue() - 1);
252 if (!UnreachableRanges.empty()) {
253 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
254 int64_t GapLow = LHS.back().High->getSExtValue() + 1;
255 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
256 IntRange Gap = { GapLow, GapHigh };
257 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
258 NewUpperBound = LHS.back().High;
261 DEBUG(dbgs() << "LHS Bounds ==> ";
263 dbgs() << LowerBound->getSExtValue();
267 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
268 dbgs() << "RHS Bounds ==> ";
269 dbgs() << NewLowerBound->getSExtValue() << " - ";
271 dbgs() << UpperBound->getSExtValue() << "\n";
276 // Create a new node that checks if the value is < pivot. Go to the
277 // left branch if it is and right branch if not.
278 Function* F = OrigBlock->getParent();
279 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
281 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
282 Val, Pivot.Low, "Pivot");
284 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
285 NewUpperBound, Val, NewNode, OrigBlock,
286 Default, UnreachableRanges);
287 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
288 UpperBound, Val, NewNode, OrigBlock,
289 Default, UnreachableRanges);
291 Function::iterator FI = OrigBlock;
292 F->getBasicBlockList().insert(++FI, NewNode);
293 NewNode->getInstList().push_back(Comp);
295 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
299 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
300 // checks if the switch's value == the case's value. If not, then it
301 // jumps to the default branch. At this point in the tree, the value
302 // can't be another valid case value, so the jump to the "default" branch
305 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
306 BasicBlock* OrigBlock,
309 Function* F = OrigBlock->getParent();
310 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
311 Function::iterator FI = OrigBlock;
312 F->getBasicBlockList().insert(++FI, NewLeaf);
315 ICmpInst* Comp = nullptr;
316 if (Leaf.Low == Leaf.High) {
317 // Make the seteq instruction...
318 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
319 Leaf.Low, "SwitchLeaf");
321 // Make range comparison
322 if (Leaf.Low->isMinValue(true /*isSigned*/)) {
323 // Val >= Min && Val <= Hi --> Val <= Hi
324 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
326 } else if (Leaf.Low->isZero()) {
327 // Val >= 0 && Val <= Hi --> Val <=u Hi
328 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
331 // Emit V-Lo <=u Hi-Lo
332 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
333 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
334 Val->getName()+".off",
336 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
337 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
342 // Make the conditional branch...
343 BasicBlock* Succ = Leaf.BB;
344 BranchInst::Create(Succ, Default, Comp, NewLeaf);
346 // If there were any PHI nodes in this successor, rewrite one entry
347 // from OrigBlock to come from NewLeaf.
348 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
349 PHINode* PN = cast<PHINode>(I);
350 // Remove all but one incoming entries from the cluster
351 uint64_t Range = Leaf.High->getSExtValue() -
352 Leaf.Low->getSExtValue();
353 for (uint64_t j = 0; j < Range; ++j) {
354 PN->removeIncomingValue(OrigBlock);
357 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
358 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
359 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
365 // Clusterify - Transform simple list of Cases into list of CaseRange's
366 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
367 unsigned numCmps = 0;
369 // Start with "simple" cases
370 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
371 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
372 i.getCaseSuccessor()));
374 std::sort(Cases.begin(), Cases.end(), CaseCmp());
376 // Merge case into clusters
377 if (Cases.size() >= 2) {
378 CaseItr I = Cases.begin();
379 for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
380 int64_t nextValue = J->Low->getSExtValue();
381 int64_t currentValue = I->High->getSExtValue();
382 BasicBlock* nextBB = J->BB;
383 BasicBlock* currentBB = I->BB;
385 // If the two neighboring cases go to the same destination, merge them
386 // into a single case.
387 assert(nextValue > currentValue && "Cases should be strictly ascending");
388 if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
390 // FIXME: Combine branch weights.
391 } else if (++I != J) {
395 Cases.erase(std::next(I), Cases.end());
398 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
399 if (I->Low != I->High)
400 // A range counts double, since it requires two compares.
407 // processSwitchInst - Replace the specified switch instruction with a sequence
408 // of chained if-then insts in a balanced binary search.
410 void LowerSwitch::processSwitchInst(SwitchInst *SI,
411 SmallPtrSetImpl<BasicBlock*> &DeleteList) {
412 BasicBlock *CurBlock = SI->getParent();
413 BasicBlock *OrigBlock = CurBlock;
414 Function *F = CurBlock->getParent();
415 Value *Val = SI->getCondition(); // The value we are switching on...
416 BasicBlock* Default = SI->getDefaultDest();
418 // If there is only the default destination, just branch.
419 if (!SI->getNumCases()) {
420 BranchInst::Create(Default, CurBlock);
421 SI->eraseFromParent();
425 // Prepare cases vector.
427 unsigned numCmps = Clusterify(Cases, SI);
428 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
429 << ". Total compares: " << numCmps << "\n");
430 DEBUG(dbgs() << "Cases: " << Cases << "\n");
433 ConstantInt *LowerBound = nullptr;
434 ConstantInt *UpperBound = nullptr;
435 std::vector<IntRange> UnreachableRanges;
437 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
438 // Make the bounds tightly fitted around the case value range, because we
439 // know that the value passed to the switch must be exactly one of the case
441 assert(!Cases.empty());
442 LowerBound = Cases.front().Low;
443 UpperBound = Cases.back().High;
445 DenseMap<BasicBlock *, unsigned> Popularity;
447 BasicBlock *PopSucc = nullptr;
449 IntRange R = { INT64_MIN, INT64_MAX };
450 UnreachableRanges.push_back(R);
451 for (const auto &I : Cases) {
452 int64_t Low = I.Low->getSExtValue();
453 int64_t High = I.High->getSExtValue();
455 IntRange &LastRange = UnreachableRanges.back();
456 if (LastRange.Low == Low) {
457 // There is nothing left of the previous range.
458 UnreachableRanges.pop_back();
460 // Terminate the previous range.
461 assert(Low > LastRange.Low);
462 LastRange.High = Low - 1;
464 if (High != INT64_MAX) {
465 IntRange R = { High + 1, INT64_MAX };
466 UnreachableRanges.push_back(R);
470 int64_t N = High - Low + 1;
471 unsigned &Pop = Popularity[I.BB];
472 if ((Pop += N) > MaxPop) {
478 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
479 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
481 assert(I->Low <= I->High);
484 assert(Next->Low > I->High);
489 // Use the most popular block as the new default, reducing the number of
491 assert(MaxPop > 0 && PopSucc);
493 Cases.erase(std::remove_if(
494 Cases.begin(), Cases.end(),
495 [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
498 // If there are no cases left, just branch.
500 BranchInst::Create(Default, CurBlock);
501 SI->eraseFromParent();
506 // Create a new, empty default block so that the new hierarchy of
507 // if-then statements go to this and the PHI nodes are happy.
508 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
509 F->getBasicBlockList().insert(Default, NewDefault);
510 BranchInst::Create(Default, NewDefault);
512 // If there is an entry in any PHI nodes for the default edge, make sure
513 // to update them as well.
514 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
515 PHINode *PN = cast<PHINode>(I);
516 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
517 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
518 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
521 BasicBlock *SwitchBlock =
522 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
523 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
525 // Branch to our shiny new if-then stuff...
526 BranchInst::Create(SwitchBlock, OrigBlock);
528 // We are now done with the switch instruction, delete it.
529 BasicBlock *OldDefault = SI->getDefaultDest();
530 CurBlock->getInstList().erase(SI);
532 // If the Default block has no more predecessors just add it to DeleteList.
533 if (pred_begin(OldDefault) == pred_end(OldDefault))
534 DeleteList.insert(OldDefault);