LowerSwitch: replace unreachable default with popular case destination
[oota-llvm.git] / lib / Transforms / Utils / LowerSwitch.cpp
1 //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
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"
29 #include <algorithm>
30 using namespace llvm;
31
32 #define DEBUG_TYPE "lower-switch"
33
34 namespace {
35   struct IntRange {
36     int64_t Low, High;
37   };
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.
42
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;
50   }
51
52   /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
53   /// instructions.
54   class LowerSwitch : public FunctionPass {
55   public:
56     static char ID; // Pass identification, replacement for typeid
57     LowerSwitch() : FunctionPass(ID) {
58       initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
59     } 
60
61     bool runOnFunction(Function &F) override;
62
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);
68     }
69
70     struct CaseRange {
71       Constant* Low;
72       Constant* High;
73       BasicBlock* BB;
74
75       CaseRange(Constant *low = nullptr, Constant *high = nullptr,
76                 BasicBlock *bb = nullptr) :
77         Low(low), High(high), BB(bb) { }
78     };
79
80     typedef std::vector<CaseRange> CaseVector;
81     typedef std::vector<CaseRange>::iterator CaseItr;
82   private:
83     void processSwitchInst(SwitchInst *SI);
84
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,
91                              BasicBlock *Default);
92     unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
93   };
94
95   /// The comparison function for sorting the switch case values in the vector.
96   /// WARNING: Case ranges should be disjoint!
97   struct CaseCmp {
98     bool operator () (const LowerSwitch::CaseRange& C1,
99                       const LowerSwitch::CaseRange& C2) {
100
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());
104     }
105   };
106 }
107
108 char LowerSwitch::ID = 0;
109 INITIALIZE_PASS(LowerSwitch, "lowerswitch",
110                 "Lower SwitchInst's to branches", false, false)
111
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();
117 }
118
119 bool LowerSwitch::runOnFunction(Function &F) {
120   bool Changed = false;
121
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
124
125     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
126       Changed = true;
127       processSwitchInst(SI);
128     }
129   }
130
131   return Changed;
132 }
133
134 // operator<< - Used for debugging purposes.
135 //
136 static raw_ostream& operator<<(raw_ostream &O,
137                                const LowerSwitch::CaseVector &C)
138     LLVM_ATTRIBUTE_USED;
139 static raw_ostream& operator<<(raw_ostream &O,
140                                const LowerSwitch::CaseVector &C) {
141   O << "[";
142
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 << ", ";
147   }
148
149   return O << "]";
150 }
151
152 // \brief Update the first occurrence of the "switch statement" BB in the PHI
153 // node with the "new" BB. The other occurrences will:
154 //
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();
165        I != IE; ++I) {
166     PHINode *PN = cast<PHINode>(I);
167
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);
174         break;
175       }
176     }
177
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--;
184       }
185   }
186 }
187
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.
193 BasicBlock *
194 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
195                            ConstantInt *UpperBound, Value *Val,
196                            BasicBlock *Predecessor, BasicBlock *OrigBlock,
197                            BasicBlock *Default,
198                            const std::vector<IntRange> &UnreachableRanges) {
199   unsigned Size = End - Begin;
200
201   if (Size == 1) {
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)
209         NumMergedCases =
210             UpperBound->getSExtValue() - LowerBound->getSExtValue();
211       fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
212       return Begin->BB;
213     }
214     return newLeafBlock(*Begin, Val, OrigBlock, Default);
215   }
216
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");
222
223   CaseRange &Pivot = *(Begin + Mid);
224   DEBUG(dbgs() << "Pivot ==> "
225                << cast<ConstantInt>(Pivot.Low)->getValue()
226                << " -" << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
227
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
231   // a smaller value.
232   ConstantInt *NewLowerBound = cast<ConstantInt>(Pivot.Low);
233
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);
238
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);
246   }
247
248   DEBUG(dbgs() << "LHS Bounds ==> ";
249         if (LowerBound) {
250           dbgs() << cast<ConstantInt>(LowerBound)->getSExtValue();
251         } else {
252           dbgs() << "NONE";
253         }
254         dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
255         dbgs() << "RHS Bounds ==> ";
256         dbgs() << NewLowerBound->getSExtValue() << " - ";
257         if (UpperBound) {
258           dbgs() << cast<ConstantInt>(UpperBound)->getSExtValue() << "\n";
259         } else {
260           dbgs() << "NONE\n";
261         });
262
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");
267
268   ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
269                                 Val, Pivot.Low, "Pivot");
270
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);
277
278   Function::iterator FI = OrigBlock;
279   F->getBasicBlockList().insert(++FI, NewNode);
280   NewNode->getInstList().push_back(Comp);
281
282   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
283   return NewNode;
284 }
285
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
290 // is warranted.
291 //
292 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
293                                       BasicBlock* OrigBlock,
294                                       BasicBlock* Default)
295 {
296   Function* F = OrigBlock->getParent();
297   BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
298   Function::iterator FI = OrigBlock;
299   F->getBasicBlockList().insert(++FI, NewLeaf);
300
301   // Emit comparison
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");
307   } else {
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,
312                           "SwitchLeaf");
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,
316                           "SwitchLeaf");      
317     } else {
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",
322                                                    NewLeaf);
323       Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
324       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
325                           "SwitchLeaf");
326     }
327   }
328
329   // Make the conditional branch...
330   BasicBlock* Succ = Leaf.BB;
331   BranchInst::Create(Succ, Default, Comp, NewLeaf);
332
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);
342     }
343     
344     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
345     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
346     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
347   }
348
349   return NewLeaf;
350 }
351
352 // Clusterify - Transform simple list of Cases into list of CaseRange's
353 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
354   unsigned numCmps = 0;
355
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()));
360   
361   std::sort(Cases.begin(), Cases.end(), CaseCmp());
362
363   // Merge case into clusters
364   if (Cases.size()>=2)
365     for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
366          J != Cases.end();) {
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;
371
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)) {
375         I->High = J->High;
376         J = Cases.erase(J);
377       } else {
378         I = J++;
379       }
380     }
381
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.
385       ++numCmps;
386   }
387
388   return numCmps;
389 }
390
391 // processSwitchInst - Replace the specified switch instruction with a sequence
392 // of chained if-then insts in a balanced binary search.
393 //
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();
400
401   // If there is only the default destination, just branch.
402   if (!SI->getNumCases()) {
403     BranchInst::Create(Default, CurBlock);
404     SI->eraseFromParent();
405     return;
406   }
407
408   // Prepare cases vector.
409   CaseVector Cases;
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");
414   (void)numCmps;
415
416   ConstantInt *LowerBound = nullptr;
417   ConstantInt *UpperBound = nullptr;
418   std::vector<IntRange> UnreachableRanges;
419
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
423     // values.
424     assert(!Cases.empty());
425     LowerBound = cast<ConstantInt>(Cases.front().Low);
426     UpperBound = cast<ConstantInt>(Cases.back().High);
427
428     DenseMap<BasicBlock *, unsigned> Popularity;
429     unsigned MaxPop = 0;
430     BasicBlock *PopSucc = nullptr;
431
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();
437
438       IntRange &LastRange = UnreachableRanges.back();
439       if (LastRange.Low == Low) {
440         // There is nothing left of the previous range.
441         UnreachableRanges.pop_back();
442       } else {
443         // Terminate the previous range.
444         assert(Low > LastRange.Low);
445         LastRange.High = Low - 1;
446       }
447       if (High != INT64_MAX) {
448         IntRange R = { High + 1, INT64_MAX };
449         UnreachableRanges.push_back(R);
450       }
451
452       // Count popularity.
453       int64_t N = High - Low + 1;
454       unsigned &Pop = Popularity[I.BB];
455       if ((Pop += N) > MaxPop) {
456         MaxPop = Pop;
457         PopSucc = I.BB;
458       }
459     }
460 #ifndef NDEBUG
461     /* UnreachableRanges should be sorted and the ranges non-adjacent. */
462     for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
463          I != E; ++I) {
464       assert(I->Low <= I->High);
465       auto Next = I + 1;
466       if (Next != E) {
467         assert(Next->Low > I->High);
468       }
469     }
470 #endif
471
472     // Use the most popular block as the new default, reducing the number of
473     // cases.
474     assert(MaxPop > 0 && PopSucc);
475     Default = PopSucc;
476     for (CaseItr I = Cases.begin(); I != Cases.end();) {
477       if (I->BB == PopSucc)
478         I = Cases.erase(I);
479       else
480         ++I;
481     }
482
483     // If there are no cases left, just branch.
484     if (Cases.empty()) {
485       BranchInst::Create(Default, CurBlock);
486       SI->eraseFromParent();
487       return;
488     }
489   }
490
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);
496
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);
504   }
505
506   BasicBlock *SwitchBlock =
507       switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
508                     OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
509
510   // Branch to our shiny new if-then stuff...
511   BranchInst::Create(SwitchBlock, OrigBlock);
512
513   // We are now done with the switch instruction, delete it.
514   BasicBlock *OldDefault = SI->getDefaultDest();
515   CurBlock->getInstList().erase(SI);
516
517   // If the Default block has no more predecessors just remove it.
518   if (pred_begin(OldDefault) == pred_end(OldDefault))
519     DeleteDeadBlock(OldDefault);
520 }