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 /// Replace all SwitchInst instructions with chained branch instructions.
53 class LowerSwitch : public FunctionPass {
55 static char ID; // Pass identification, replacement for typeid
56 LowerSwitch() : FunctionPass(ID) {
57 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
60 bool runOnFunction(Function &F) override;
62 void getAnalysisUsage(AnalysisUsage &AU) const override {
63 // This is a cluster of orthogonal Transforms
64 AU.addPreserved<UnifyFunctionExitNodes>();
65 AU.addPreservedID(LowerInvokePassID);
73 CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
74 : Low(low), High(high), BB(bb) {}
77 typedef std::vector<CaseRange> CaseVector;
78 typedef std::vector<CaseRange>::iterator CaseItr;
80 void processSwitchInst(SwitchInst *SI, SmallPtrSetImpl<BasicBlock*> &DeleteList);
82 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
83 ConstantInt *LowerBound, ConstantInt *UpperBound,
84 Value *Val, BasicBlock *Predecessor,
85 BasicBlock *OrigBlock, BasicBlock *Default,
86 const std::vector<IntRange> &UnreachableRanges);
87 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
89 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
92 /// The comparison function for sorting the switch case values in the vector.
93 /// WARNING: Case ranges should be disjoint!
95 bool operator () (const LowerSwitch::CaseRange& C1,
96 const LowerSwitch::CaseRange& C2) {
98 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
99 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
100 return CI1->getValue().slt(CI2->getValue());
105 char LowerSwitch::ID = 0;
106 INITIALIZE_PASS(LowerSwitch, "lowerswitch",
107 "Lower SwitchInst's to branches", false, false)
109 // Publicly exposed interface to pass...
110 char &llvm::LowerSwitchID = LowerSwitch::ID;
111 // createLowerSwitchPass - Interface to this file...
112 FunctionPass *llvm::createLowerSwitchPass() {
113 return new LowerSwitch();
116 bool LowerSwitch::runOnFunction(Function &F) {
117 bool Changed = false;
118 SmallPtrSet<BasicBlock*, 8> DeleteList;
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 the block is a dead Default block that will be deleted later, don't
124 // waste time processing it.
125 if (DeleteList.count(Cur))
128 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
130 processSwitchInst(SI, DeleteList);
134 for (BasicBlock* BB: DeleteList) {
141 /// Used for debugging purposes.
142 static raw_ostream& operator<<(raw_ostream &O,
143 const LowerSwitch::CaseVector &C)
145 static raw_ostream& operator<<(raw_ostream &O,
146 const LowerSwitch::CaseVector &C) {
149 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
150 E = C.end(); B != E; ) {
151 O << *B->Low << " -" << *B->High;
152 if (++B != E) O << ", ";
158 /// \brief Update the first occurrence of the "switch statement" BB in the PHI
159 /// node with the "new" BB. The other occurrences will:
161 /// 1) Be updated by subsequent calls to this function. Switch statements may
162 /// have more than one outcoming edge into the same BB if they all have the same
163 /// value. When the switch statement is converted these incoming edges are now
164 /// coming from multiple BBs.
165 /// 2) Removed if subsequent incoming values now share the same case, i.e.,
166 /// multiple outcome edges are condensed into one. This is necessary to keep the
167 /// number of phi values equal to the number of branches to SuccBB.
168 static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
169 unsigned NumMergedCases) {
170 for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
172 PHINode *PN = cast<PHINode>(I);
174 // Only update the first occurrence.
175 unsigned Idx = 0, E = PN->getNumIncomingValues();
176 unsigned LocalNumMergedCases = NumMergedCases;
177 for (; Idx != E; ++Idx) {
178 if (PN->getIncomingBlock(Idx) == OrigBB) {
179 PN->setIncomingBlock(Idx, NewBB);
184 // Remove additional occurrences coming from condensed cases and keep the
185 // number of incoming values equal to the number of branches to SuccBB.
186 SmallVector<unsigned, 8> Indices;
187 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
188 if (PN->getIncomingBlock(Idx) == OrigBB) {
189 Indices.push_back(Idx);
190 LocalNumMergedCases--;
192 // Remove incoming values in the reverse order to prevent invalidating
193 // *successive* index.
194 for (auto III = Indices.rbegin(), IIE = Indices.rend(); III != IIE; ++III)
195 PN->removeIncomingValue(*III);
199 /// Convert the switch statement into a binary lookup of the case values.
200 /// The function recursively builds this tree. LowerBound and UpperBound are
201 /// used to keep track of the bounds for Val that have already been checked by
202 /// a block emitted by one of the previous calls to switchConvert in the call
205 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
206 ConstantInt *UpperBound, Value *Val,
207 BasicBlock *Predecessor, BasicBlock *OrigBlock,
209 const std::vector<IntRange> &UnreachableRanges) {
210 unsigned Size = End - Begin;
213 // Check if the Case Range is perfectly squeezed in between
214 // already checked Upper and Lower bounds. If it is then we can avoid
215 // emitting the code that checks if the value actually falls in the range
216 // because the bounds already tell us so.
217 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
218 unsigned NumMergedCases = 0;
219 if (LowerBound && UpperBound)
221 UpperBound->getSExtValue() - LowerBound->getSExtValue();
222 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
225 return newLeafBlock(*Begin, Val, OrigBlock, Default);
228 unsigned Mid = Size / 2;
229 std::vector<CaseRange> LHS(Begin, Begin + Mid);
230 DEBUG(dbgs() << "LHS: " << LHS << "\n");
231 std::vector<CaseRange> RHS(Begin + Mid, End);
232 DEBUG(dbgs() << "RHS: " << RHS << "\n");
234 CaseRange &Pivot = *(Begin + Mid);
235 DEBUG(dbgs() << "Pivot ==> "
236 << Pivot.Low->getValue()
237 << " -" << Pivot.High->getValue() << "\n");
239 // NewLowerBound here should never be the integer minimal value.
240 // This is because it is computed from a case range that is never
241 // the smallest, so there is always a case range that has at least
243 ConstantInt *NewLowerBound = Pivot.Low;
245 // Because NewLowerBound is never the smallest representable integer
246 // it is safe here to subtract one.
247 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
248 NewLowerBound->getValue() - 1);
250 if (!UnreachableRanges.empty()) {
251 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
252 int64_t GapLow = LHS.back().High->getSExtValue() + 1;
253 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
254 IntRange Gap = { GapLow, GapHigh };
255 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
256 NewUpperBound = LHS.back().High;
259 DEBUG(dbgs() << "LHS Bounds ==> ";
261 dbgs() << LowerBound->getSExtValue();
265 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
266 dbgs() << "RHS Bounds ==> ";
267 dbgs() << NewLowerBound->getSExtValue() << " - ";
269 dbgs() << UpperBound->getSExtValue() << "\n";
274 // Create a new node that checks if the value is < pivot. Go to the
275 // left branch if it is and right branch if not.
276 Function* F = OrigBlock->getParent();
277 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
279 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
280 Val, Pivot.Low, "Pivot");
282 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
283 NewUpperBound, Val, NewNode, OrigBlock,
284 Default, UnreachableRanges);
285 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
286 UpperBound, Val, NewNode, OrigBlock,
287 Default, UnreachableRanges);
289 Function::iterator FI = OrigBlock;
290 F->getBasicBlockList().insert(++FI, NewNode);
291 NewNode->getInstList().push_back(Comp);
293 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
297 /// Create a new leaf block for the binary lookup tree. It checks if the
298 /// switch's value == the case's value. If not, then it jumps to the default
299 /// branch. At this point in the tree, the value can't be another valid case
300 /// value, so the jump to the "default" branch is warranted.
301 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
302 BasicBlock* OrigBlock,
305 Function* F = OrigBlock->getParent();
306 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
307 Function::iterator FI = OrigBlock;
308 F->getBasicBlockList().insert(++FI, NewLeaf);
311 ICmpInst* Comp = nullptr;
312 if (Leaf.Low == Leaf.High) {
313 // Make the seteq instruction...
314 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
315 Leaf.Low, "SwitchLeaf");
317 // Make range comparison
318 if (Leaf.Low->isMinValue(true /*isSigned*/)) {
319 // Val >= Min && Val <= Hi --> Val <= Hi
320 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
322 } else if (Leaf.Low->isZero()) {
323 // Val >= 0 && Val <= Hi --> Val <=u Hi
324 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
327 // Emit V-Lo <=u Hi-Lo
328 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
329 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
330 Val->getName()+".off",
332 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
333 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
338 // Make the conditional branch...
339 BasicBlock* Succ = Leaf.BB;
340 BranchInst::Create(Succ, Default, Comp, NewLeaf);
342 // If there were any PHI nodes in this successor, rewrite one entry
343 // from OrigBlock to come from NewLeaf.
344 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
345 PHINode* PN = cast<PHINode>(I);
346 // Remove all but one incoming entries from the cluster
347 uint64_t Range = Leaf.High->getSExtValue() -
348 Leaf.Low->getSExtValue();
349 for (uint64_t j = 0; j < Range; ++j) {
350 PN->removeIncomingValue(OrigBlock);
353 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
354 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
355 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
361 /// Transform simple list of Cases into list of CaseRange's.
362 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
363 unsigned numCmps = 0;
365 // Start with "simple" cases
366 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
367 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
368 i.getCaseSuccessor()));
370 std::sort(Cases.begin(), Cases.end(), CaseCmp());
372 // Merge case into clusters
373 if (Cases.size() >= 2) {
374 CaseItr I = Cases.begin();
375 for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
376 int64_t nextValue = J->Low->getSExtValue();
377 int64_t currentValue = I->High->getSExtValue();
378 BasicBlock* nextBB = J->BB;
379 BasicBlock* currentBB = I->BB;
381 // If the two neighboring cases go to the same destination, merge them
382 // into a single case.
383 assert(nextValue > currentValue && "Cases should be strictly ascending");
384 if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
386 // FIXME: Combine branch weights.
387 } else if (++I != J) {
391 Cases.erase(std::next(I), Cases.end());
394 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
395 if (I->Low != I->High)
396 // A range counts double, since it requires two compares.
403 /// Replace the specified switch instruction with a sequence of chained if-then
404 /// insts in a balanced binary search.
405 void LowerSwitch::processSwitchInst(SwitchInst *SI,
406 SmallPtrSetImpl<BasicBlock*> &DeleteList) {
407 BasicBlock *CurBlock = SI->getParent();
408 BasicBlock *OrigBlock = CurBlock;
409 Function *F = CurBlock->getParent();
410 Value *Val = SI->getCondition(); // The value we are switching on...
411 BasicBlock* Default = SI->getDefaultDest();
413 // If there is only the default destination, just branch.
414 if (!SI->getNumCases()) {
415 BranchInst::Create(Default, CurBlock);
416 SI->eraseFromParent();
420 // Prepare cases vector.
422 unsigned numCmps = Clusterify(Cases, SI);
423 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
424 << ". Total compares: " << numCmps << "\n");
425 DEBUG(dbgs() << "Cases: " << Cases << "\n");
428 ConstantInt *LowerBound = nullptr;
429 ConstantInt *UpperBound = nullptr;
430 std::vector<IntRange> UnreachableRanges;
432 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
433 // Make the bounds tightly fitted around the case value range, because we
434 // know that the value passed to the switch must be exactly one of the case
436 assert(!Cases.empty());
437 LowerBound = Cases.front().Low;
438 UpperBound = Cases.back().High;
440 DenseMap<BasicBlock *, unsigned> Popularity;
442 BasicBlock *PopSucc = nullptr;
444 IntRange R = { INT64_MIN, INT64_MAX };
445 UnreachableRanges.push_back(R);
446 for (const auto &I : Cases) {
447 int64_t Low = I.Low->getSExtValue();
448 int64_t High = I.High->getSExtValue();
450 IntRange &LastRange = UnreachableRanges.back();
451 if (LastRange.Low == Low) {
452 // There is nothing left of the previous range.
453 UnreachableRanges.pop_back();
455 // Terminate the previous range.
456 assert(Low > LastRange.Low);
457 LastRange.High = Low - 1;
459 if (High != INT64_MAX) {
460 IntRange R = { High + 1, INT64_MAX };
461 UnreachableRanges.push_back(R);
465 int64_t N = High - Low + 1;
466 unsigned &Pop = Popularity[I.BB];
467 if ((Pop += N) > MaxPop) {
473 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
474 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
476 assert(I->Low <= I->High);
479 assert(Next->Low > I->High);
484 // Use the most popular block as the new default, reducing the number of
486 assert(MaxPop > 0 && PopSucc);
488 Cases.erase(std::remove_if(
489 Cases.begin(), Cases.end(),
490 [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
493 // If there are no cases left, just branch.
495 BranchInst::Create(Default, CurBlock);
496 SI->eraseFromParent();
501 // Create a new, empty default block so that the new hierarchy of
502 // if-then statements go to this and the PHI nodes are happy.
503 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
504 F->getBasicBlockList().insert(Default, NewDefault);
505 BranchInst::Create(Default, NewDefault);
507 // If there is an entry in any PHI nodes for the default edge, make sure
508 // to update them as well.
509 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
510 PHINode *PN = cast<PHINode>(I);
511 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
512 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
513 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
516 BasicBlock *SwitchBlock =
517 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
518 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
520 // Branch to our shiny new if-then stuff...
521 BranchInst::Create(SwitchBlock, OrigBlock);
523 // We are now done with the switch instruction, delete it.
524 BasicBlock *OldDefault = SI->getDefaultDest();
525 CurBlock->getInstList().erase(SI);
527 // If the Default block has no more predecessors just add it to DeleteList.
528 if (pred_begin(OldDefault) == pred_end(OldDefault))
529 DeleteList.insert(OldDefault);