[LPM] Stop using the string based preservation API. It is an
[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.addPreservedID(LowerInvokePassID);
67     }
68
69     struct CaseRange {
70       Constant* Low;
71       Constant* High;
72       BasicBlock* BB;
73
74       CaseRange(Constant *low = nullptr, Constant *high = nullptr,
75                 BasicBlock *bb = nullptr) :
76         Low(low), High(high), BB(bb) { }
77     };
78
79     typedef std::vector<CaseRange> CaseVector;
80     typedef std::vector<CaseRange>::iterator CaseItr;
81   private:
82     void processSwitchInst(SwitchInst *SI);
83
84     BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
85                               ConstantInt *LowerBound, ConstantInt *UpperBound,
86                               Value *Val, BasicBlock *Predecessor,
87                               BasicBlock *OrigBlock, BasicBlock *Default,
88                               const std::vector<IntRange> &UnreachableRanges);
89     BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
90                              BasicBlock *Default);
91     unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
92   };
93
94   /// The comparison function for sorting the switch case values in the vector.
95   /// WARNING: Case ranges should be disjoint!
96   struct CaseCmp {
97     bool operator () (const LowerSwitch::CaseRange& C1,
98                       const LowerSwitch::CaseRange& C2) {
99
100       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
101       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
102       return CI1->getValue().slt(CI2->getValue());
103     }
104   };
105 }
106
107 char LowerSwitch::ID = 0;
108 INITIALIZE_PASS(LowerSwitch, "lowerswitch",
109                 "Lower SwitchInst's to branches", false, false)
110
111 // Publicly exposed interface to pass...
112 char &llvm::LowerSwitchID = LowerSwitch::ID;
113 // createLowerSwitchPass - Interface to this file...
114 FunctionPass *llvm::createLowerSwitchPass() {
115   return new LowerSwitch();
116 }
117
118 bool LowerSwitch::runOnFunction(Function &F) {
119   bool Changed = false;
120
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
123
124     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
125       Changed = true;
126       processSwitchInst(SI);
127     }
128   }
129
130   return Changed;
131 }
132
133 // operator<< - Used for debugging purposes.
134 //
135 static raw_ostream& operator<<(raw_ostream &O,
136                                const LowerSwitch::CaseVector &C)
137     LLVM_ATTRIBUTE_USED;
138 static raw_ostream& operator<<(raw_ostream &O,
139                                const LowerSwitch::CaseVector &C) {
140   O << "[";
141
142   for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
143          E = C.end(); B != E; ) {
144     O << *B->Low << " -" << *B->High;
145     if (++B != E) O << ", ";
146   }
147
148   return O << "]";
149 }
150
151 // \brief Update the first occurrence of the "switch statement" BB in the PHI
152 // node with the "new" BB. The other occurrences will:
153 //
154 // 1) Be updated by subsequent calls to this function.  Switch statements may
155 // have more than one outcoming edge into the same BB if they all have the same
156 // value. When the switch statement is converted these incoming edges are now
157 // coming from multiple BBs.
158 // 2) Removed if subsequent incoming values now share the same case, i.e.,
159 // multiple outcome edges are condensed into one. This is necessary to keep the
160 // number of phi values equal to the number of branches to SuccBB.
161 static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
162                     unsigned NumMergedCases) {
163   for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
164        I != IE; ++I) {
165     PHINode *PN = cast<PHINode>(I);
166
167     // Only update the first occurence.
168     unsigned Idx = 0, E = PN->getNumIncomingValues();
169     unsigned LocalNumMergedCases = NumMergedCases;
170     for (; Idx != E; ++Idx) {
171       if (PN->getIncomingBlock(Idx) == OrigBB) {
172         PN->setIncomingBlock(Idx, NewBB);
173         break;
174       }
175     }
176
177     // Remove additional occurences coming from condensed cases and keep the
178     // number of incoming values equal to the number of branches to SuccBB.
179     for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
180       if (PN->getIncomingBlock(Idx) == OrigBB) {
181         PN->removeIncomingValue(Idx);
182         LocalNumMergedCases--;
183       }
184   }
185 }
186
187 // switchConvert - Convert the switch statement into a binary lookup of
188 // the case values. The function recursively builds this tree.
189 // LowerBound and UpperBound are used to keep track of the bounds for Val
190 // that have already been checked by a block emitted by one of the previous
191 // calls to switchConvert in the call stack.
192 BasicBlock *
193 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
194                            ConstantInt *UpperBound, Value *Val,
195                            BasicBlock *Predecessor, BasicBlock *OrigBlock,
196                            BasicBlock *Default,
197                            const std::vector<IntRange> &UnreachableRanges) {
198   unsigned Size = End - Begin;
199
200   if (Size == 1) {
201     // Check if the Case Range is perfectly squeezed in between
202     // already checked Upper and Lower bounds. If it is then we can avoid
203     // emitting the code that checks if the value actually falls in the range
204     // because the bounds already tell us so.
205     if (Begin->Low == LowerBound && Begin->High == UpperBound) {
206       unsigned NumMergedCases = 0;
207       if (LowerBound && UpperBound)
208         NumMergedCases =
209             UpperBound->getSExtValue() - LowerBound->getSExtValue();
210       fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
211       return Begin->BB;
212     }
213     return newLeafBlock(*Begin, Val, OrigBlock, Default);
214   }
215
216   unsigned Mid = Size / 2;
217   std::vector<CaseRange> LHS(Begin, Begin + Mid);
218   DEBUG(dbgs() << "LHS: " << LHS << "\n");
219   std::vector<CaseRange> RHS(Begin + Mid, End);
220   DEBUG(dbgs() << "RHS: " << RHS << "\n");
221
222   CaseRange &Pivot = *(Begin + Mid);
223   DEBUG(dbgs() << "Pivot ==> "
224                << cast<ConstantInt>(Pivot.Low)->getValue()
225                << " -" << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
226
227   // NewLowerBound here should never be the integer minimal value.
228   // This is because it is computed from a case range that is never
229   // the smallest, so there is always a case range that has at least
230   // a smaller value.
231   ConstantInt *NewLowerBound = cast<ConstantInt>(Pivot.Low);
232
233   // Because NewLowerBound is never the smallest representable integer
234   // it is safe here to subtract one.
235   ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
236                                                 NewLowerBound->getValue() - 1);
237
238   if (!UnreachableRanges.empty()) {
239     // Check if the gap between LHS's highest and NewLowerBound is unreachable.
240     int64_t GapLow = cast<ConstantInt>(LHS.back().High)->getSExtValue() + 1;
241     int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
242     IntRange Gap = { GapLow, GapHigh };
243     if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
244       NewUpperBound = cast<ConstantInt>(LHS.back().High);
245   }
246
247   DEBUG(dbgs() << "LHS Bounds ==> ";
248         if (LowerBound) {
249           dbgs() << cast<ConstantInt>(LowerBound)->getSExtValue();
250         } else {
251           dbgs() << "NONE";
252         }
253         dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
254         dbgs() << "RHS Bounds ==> ";
255         dbgs() << NewLowerBound->getSExtValue() << " - ";
256         if (UpperBound) {
257           dbgs() << cast<ConstantInt>(UpperBound)->getSExtValue() << "\n";
258         } else {
259           dbgs() << "NONE\n";
260         });
261
262   // Create a new node that checks if the value is < pivot. Go to the
263   // left branch if it is and right branch if not.
264   Function* F = OrigBlock->getParent();
265   BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
266
267   ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
268                                 Val, Pivot.Low, "Pivot");
269
270   BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
271                                       NewUpperBound, Val, NewNode, OrigBlock,
272                                       Default, UnreachableRanges);
273   BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
274                                       UpperBound, Val, NewNode, OrigBlock,
275                                       Default, UnreachableRanges);
276
277   Function::iterator FI = OrigBlock;
278   F->getBasicBlockList().insert(++FI, NewNode);
279   NewNode->getInstList().push_back(Comp);
280
281   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
282   return NewNode;
283 }
284
285 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
286 // checks if the switch's value == the case's value. If not, then it
287 // jumps to the default branch. At this point in the tree, the value
288 // can't be another valid case value, so the jump to the "default" branch
289 // is warranted.
290 //
291 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
292                                       BasicBlock* OrigBlock,
293                                       BasicBlock* Default)
294 {
295   Function* F = OrigBlock->getParent();
296   BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
297   Function::iterator FI = OrigBlock;
298   F->getBasicBlockList().insert(++FI, NewLeaf);
299
300   // Emit comparison
301   ICmpInst* Comp = nullptr;
302   if (Leaf.Low == Leaf.High) {
303     // Make the seteq instruction...
304     Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
305                         Leaf.Low, "SwitchLeaf");
306   } else {
307     // Make range comparison
308     if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
309       // Val >= Min && Val <= Hi --> Val <= Hi
310       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
311                           "SwitchLeaf");
312     } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
313       // Val >= 0 && Val <= Hi --> Val <=u Hi
314       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
315                           "SwitchLeaf");      
316     } else {
317       // Emit V-Lo <=u Hi-Lo
318       Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
319       Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
320                                                    Val->getName()+".off",
321                                                    NewLeaf);
322       Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
323       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
324                           "SwitchLeaf");
325     }
326   }
327
328   // Make the conditional branch...
329   BasicBlock* Succ = Leaf.BB;
330   BranchInst::Create(Succ, Default, Comp, NewLeaf);
331
332   // If there were any PHI nodes in this successor, rewrite one entry
333   // from OrigBlock to come from NewLeaf.
334   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
335     PHINode* PN = cast<PHINode>(I);
336     // Remove all but one incoming entries from the cluster
337     uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
338                      cast<ConstantInt>(Leaf.Low)->getSExtValue();    
339     for (uint64_t j = 0; j < Range; ++j) {
340       PN->removeIncomingValue(OrigBlock);
341     }
342     
343     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
344     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
345     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
346   }
347
348   return NewLeaf;
349 }
350
351 // Clusterify - Transform simple list of Cases into list of CaseRange's
352 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
353   unsigned numCmps = 0;
354
355   // Start with "simple" cases
356   for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
357     Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
358                               i.getCaseSuccessor()));
359   
360   std::sort(Cases.begin(), Cases.end(), CaseCmp());
361
362   // Merge case into clusters
363   if (Cases.size()>=2)
364     for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
365          J != Cases.end();) {
366       int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
367       int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
368       BasicBlock* nextBB = J->BB;
369       BasicBlock* currentBB = I->BB;
370
371       // If the two neighboring cases go to the same destination, merge them
372       // into a single case.
373       if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
374         I->High = J->High;
375         J = Cases.erase(J);
376       } else {
377         I = J++;
378       }
379     }
380
381   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
382     if (I->Low != I->High)
383       // A range counts double, since it requires two compares.
384       ++numCmps;
385   }
386
387   return numCmps;
388 }
389
390 // processSwitchInst - Replace the specified switch instruction with a sequence
391 // of chained if-then insts in a balanced binary search.
392 //
393 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
394   BasicBlock *CurBlock = SI->getParent();
395   BasicBlock *OrigBlock = CurBlock;
396   Function *F = CurBlock->getParent();
397   Value *Val = SI->getCondition();  // The value we are switching on...
398   BasicBlock* Default = SI->getDefaultDest();
399
400   // If there is only the default destination, just branch.
401   if (!SI->getNumCases()) {
402     BranchInst::Create(Default, CurBlock);
403     SI->eraseFromParent();
404     return;
405   }
406
407   // Prepare cases vector.
408   CaseVector Cases;
409   unsigned numCmps = Clusterify(Cases, SI);
410   DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
411                << ". Total compares: " << numCmps << "\n");
412   DEBUG(dbgs() << "Cases: " << Cases << "\n");
413   (void)numCmps;
414
415   ConstantInt *LowerBound = nullptr;
416   ConstantInt *UpperBound = nullptr;
417   std::vector<IntRange> UnreachableRanges;
418
419   if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
420     // Make the bounds tightly fitted around the case value range, becase we
421     // know that the value passed to the switch must be exactly one of the case
422     // values.
423     assert(!Cases.empty());
424     LowerBound = cast<ConstantInt>(Cases.front().Low);
425     UpperBound = cast<ConstantInt>(Cases.back().High);
426
427     DenseMap<BasicBlock *, unsigned> Popularity;
428     unsigned MaxPop = 0;
429     BasicBlock *PopSucc = nullptr;
430
431     IntRange R = { INT64_MIN, INT64_MAX };
432     UnreachableRanges.push_back(R);
433     for (const auto &I : Cases) {
434       int64_t Low = cast<ConstantInt>(I.Low)->getSExtValue();
435       int64_t High = cast<ConstantInt>(I.High)->getSExtValue();
436
437       IntRange &LastRange = UnreachableRanges.back();
438       if (LastRange.Low == Low) {
439         // There is nothing left of the previous range.
440         UnreachableRanges.pop_back();
441       } else {
442         // Terminate the previous range.
443         assert(Low > LastRange.Low);
444         LastRange.High = Low - 1;
445       }
446       if (High != INT64_MAX) {
447         IntRange R = { High + 1, INT64_MAX };
448         UnreachableRanges.push_back(R);
449       }
450
451       // Count popularity.
452       int64_t N = High - Low + 1;
453       unsigned &Pop = Popularity[I.BB];
454       if ((Pop += N) > MaxPop) {
455         MaxPop = Pop;
456         PopSucc = I.BB;
457       }
458     }
459 #ifndef NDEBUG
460     /* UnreachableRanges should be sorted and the ranges non-adjacent. */
461     for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
462          I != E; ++I) {
463       assert(I->Low <= I->High);
464       auto Next = I + 1;
465       if (Next != E) {
466         assert(Next->Low > I->High);
467       }
468     }
469 #endif
470
471     // Use the most popular block as the new default, reducing the number of
472     // cases.
473     assert(MaxPop > 0 && PopSucc);
474     Default = PopSucc;
475     for (CaseItr I = Cases.begin(); I != Cases.end();) {
476       if (I->BB == PopSucc)
477         I = Cases.erase(I);
478       else
479         ++I;
480     }
481
482     // If there are no cases left, just branch.
483     if (Cases.empty()) {
484       BranchInst::Create(Default, CurBlock);
485       SI->eraseFromParent();
486       return;
487     }
488   }
489
490   // Create a new, empty default block so that the new hierarchy of
491   // if-then statements go to this and the PHI nodes are happy.
492   BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
493   F->getBasicBlockList().insert(Default, NewDefault);
494   BranchInst::Create(Default, NewDefault);
495
496   // If there is an entry in any PHI nodes for the default edge, make sure
497   // to update them as well.
498   for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
499     PHINode *PN = cast<PHINode>(I);
500     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
501     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
502     PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
503   }
504
505   BasicBlock *SwitchBlock =
506       switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
507                     OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
508
509   // Branch to our shiny new if-then stuff...
510   BranchInst::Create(SwitchBlock, OrigBlock);
511
512   // We are now done with the switch instruction, delete it.
513   BasicBlock *OldDefault = SI->getDefaultDest();
514   CurBlock->getInstList().erase(SI);
515
516   // If the Default block has no more predecessors just remove it.
517   if (pred_begin(OldDefault) == pred_end(OldDefault))
518     DeleteDeadBlock(OldDefault);
519 }