Introduce llvm::SplitAllCriticalEdges
[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   /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
36   /// instructions.
37   class LowerSwitch : public FunctionPass {
38   public:
39     static char ID; // Pass identification, replacement for typeid
40     LowerSwitch() : FunctionPass(ID) {
41       initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
42     } 
43
44     bool runOnFunction(Function &F) override;
45
46     void getAnalysisUsage(AnalysisUsage &AU) const override {
47       // This is a cluster of orthogonal Transforms
48       AU.addPreserved<UnifyFunctionExitNodes>();
49       AU.addPreserved("mem2reg");
50       AU.addPreservedID(LowerInvokePassID);
51     }
52
53     struct CaseRange {
54       Constant* Low;
55       Constant* High;
56       BasicBlock* BB;
57
58       CaseRange(Constant *low = nullptr, Constant *high = nullptr,
59                 BasicBlock *bb = nullptr) :
60         Low(low), High(high), BB(bb) { }
61     };
62
63     typedef std::vector<CaseRange> CaseVector;
64     typedef std::vector<CaseRange>::iterator CaseItr;
65   private:
66     void processSwitchInst(SwitchInst *SI);
67
68     BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
69                               ConstantInt *LowerBound, ConstantInt *UpperBound,
70                               Value *Val, BasicBlock *Predecessor,
71                               BasicBlock *OrigBlock, BasicBlock *Default);
72     BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
73                              BasicBlock *Default);
74     unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
75   };
76
77   /// The comparison function for sorting the switch case values in the vector.
78   /// WARNING: Case ranges should be disjoint!
79   struct CaseCmp {
80     bool operator () (const LowerSwitch::CaseRange& C1,
81                       const LowerSwitch::CaseRange& C2) {
82
83       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
84       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
85       return CI1->getValue().slt(CI2->getValue());
86     }
87   };
88 }
89
90 char LowerSwitch::ID = 0;
91 INITIALIZE_PASS(LowerSwitch, "lowerswitch",
92                 "Lower SwitchInst's to branches", false, false)
93
94 // Publicly exposed interface to pass...
95 char &llvm::LowerSwitchID = LowerSwitch::ID;
96 // createLowerSwitchPass - Interface to this file...
97 FunctionPass *llvm::createLowerSwitchPass() {
98   return new LowerSwitch();
99 }
100
101 bool LowerSwitch::runOnFunction(Function &F) {
102   bool Changed = false;
103
104   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
105     BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
106
107     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
108       Changed = true;
109       processSwitchInst(SI);
110     }
111   }
112
113   return Changed;
114 }
115
116 // operator<< - Used for debugging purposes.
117 //
118 static raw_ostream& operator<<(raw_ostream &O,
119                                const LowerSwitch::CaseVector &C)
120     LLVM_ATTRIBUTE_USED;
121 static raw_ostream& operator<<(raw_ostream &O,
122                                const LowerSwitch::CaseVector &C) {
123   O << "[";
124
125   for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
126          E = C.end(); B != E; ) {
127     O << *B->Low << " -" << *B->High;
128     if (++B != E) O << ", ";
129   }
130
131   return O << "]";
132 }
133
134 /// \brief Update the first occurrence of the "switch statement" BB in the PHI
135 /// node with the "new" BB. The other occurrences will be updated by subsequent
136 /// calls to this function.
137 ///
138 /// Switch statements may have more than one incoming edge into the same BB if
139 /// they all have the same value. When the switch statement is converted these
140 /// incoming edges are now coming from multiple BBs.
141 static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB) {
142   for (BasicBlock::iterator I = SuccBB->begin(), E = SuccBB->getFirstNonPHI();
143        I != E; ++I) {
144     PHINode *PN = cast<PHINode>(I);
145
146     // Only update the first occurence.
147     for (unsigned Idx = 0, E = PN->getNumIncomingValues(); Idx != E; ++Idx) {
148       if (PN->getIncomingBlock(Idx) == OrigBB) {
149         PN->setIncomingBlock(Idx, NewBB);
150         break;
151       }
152     }
153   }
154 }
155
156 // switchConvert - Convert the switch statement into a binary lookup of
157 // the case values. The function recursively builds this tree.
158 // LowerBound and UpperBound are used to keep track of the bounds for Val
159 // that have already been checked by a block emitted by one of the previous
160 // calls to switchConvert in the call stack.
161 BasicBlock *LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
162                                        ConstantInt *LowerBound,
163                                        ConstantInt *UpperBound, Value *Val,
164                                        BasicBlock *Predecessor,
165                                        BasicBlock *OrigBlock,
166                                        BasicBlock *Default) {
167   unsigned Size = End - Begin;
168
169   if (Size == 1) {
170     // Check if the Case Range is perfectly squeezed in between
171     // already checked Upper and Lower bounds. If it is then we can avoid
172     // emitting the code that checks if the value actually falls in the range
173     // because the bounds already tell us so.
174     if (Begin->Low == LowerBound && Begin->High == UpperBound) {
175       fixPhis(Begin->BB, OrigBlock, Predecessor);
176       return Begin->BB;
177     }
178     return newLeafBlock(*Begin, Val, OrigBlock, Default);
179   }
180
181   unsigned Mid = Size / 2;
182   std::vector<CaseRange> LHS(Begin, Begin + Mid);
183   DEBUG(dbgs() << "LHS: " << LHS << "\n");
184   std::vector<CaseRange> RHS(Begin + Mid, End);
185   DEBUG(dbgs() << "RHS: " << RHS << "\n");
186
187   CaseRange &Pivot = *(Begin + Mid);
188   DEBUG(dbgs() << "Pivot ==> "
189                << cast<ConstantInt>(Pivot.Low)->getValue()
190                << " -" << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
191
192   // NewLowerBound here should never be the integer minimal value.
193   // This is because it is computed from a case range that is never
194   // the smallest, so there is always a case range that has at least
195   // a smaller value.
196   ConstantInt *NewLowerBound = cast<ConstantInt>(Pivot.Low);
197   ConstantInt *NewUpperBound;
198
199   // If we don't have a Default block then it means that we can never
200   // have a value outside of a case range, so set the UpperBound to the highest
201   // value in the LHS part of the case ranges.
202   if (Default != nullptr) {
203     // Because NewLowerBound is never the smallest representable integer
204     // it is safe here to subtract one.
205     NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
206                                      NewLowerBound->getValue() - 1);
207   } else {
208     CaseItr LastLHS = LHS.begin() + LHS.size() - 1;
209     NewUpperBound = cast<ConstantInt>(LastLHS->High);
210   }
211
212   DEBUG(dbgs() << "LHS Bounds ==> ";
213         if (LowerBound) {
214           dbgs() << cast<ConstantInt>(LowerBound)->getSExtValue();
215         } else {
216           dbgs() << "NONE";
217         }
218         dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
219         dbgs() << "RHS Bounds ==> ";
220         dbgs() << NewLowerBound->getSExtValue() << " - ";
221         if (UpperBound) {
222           dbgs() << cast<ConstantInt>(UpperBound)->getSExtValue() << "\n";
223         } else {
224           dbgs() << "NONE\n";
225         });
226
227   // Create a new node that checks if the value is < pivot. Go to the
228   // left branch if it is and right branch if not.
229   Function* F = OrigBlock->getParent();
230   BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
231
232   ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
233                                 Val, Pivot.Low, "Pivot");
234
235   BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
236                                       NewUpperBound, Val, NewNode, OrigBlock,
237                                       Default);
238   BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
239                                       UpperBound, Val, NewNode, OrigBlock,
240                                       Default);
241
242   Function::iterator FI = OrigBlock;
243   F->getBasicBlockList().insert(++FI, NewNode);
244   NewNode->getInstList().push_back(Comp);
245
246   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
247   return NewNode;
248 }
249
250 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
251 // checks if the switch's value == the case's value. If not, then it
252 // jumps to the default branch. At this point in the tree, the value
253 // can't be another valid case value, so the jump to the "default" branch
254 // is warranted.
255 //
256 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
257                                       BasicBlock* OrigBlock,
258                                       BasicBlock* Default)
259 {
260   Function* F = OrigBlock->getParent();
261   BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
262   Function::iterator FI = OrigBlock;
263   F->getBasicBlockList().insert(++FI, NewLeaf);
264
265   // Emit comparison
266   ICmpInst* Comp = nullptr;
267   if (Leaf.Low == Leaf.High) {
268     // Make the seteq instruction...
269     Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
270                         Leaf.Low, "SwitchLeaf");
271   } else {
272     // Make range comparison
273     if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
274       // Val >= Min && Val <= Hi --> Val <= Hi
275       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
276                           "SwitchLeaf");
277     } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
278       // Val >= 0 && Val <= Hi --> Val <=u Hi
279       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
280                           "SwitchLeaf");      
281     } else {
282       // Emit V-Lo <=u Hi-Lo
283       Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
284       Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
285                                                    Val->getName()+".off",
286                                                    NewLeaf);
287       Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
288       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
289                           "SwitchLeaf");
290     }
291   }
292
293   // Make the conditional branch...
294   BasicBlock* Succ = Leaf.BB;
295   BranchInst::Create(Succ, Default, Comp, NewLeaf);
296
297   // If there were any PHI nodes in this successor, rewrite one entry
298   // from OrigBlock to come from NewLeaf.
299   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
300     PHINode* PN = cast<PHINode>(I);
301     // Remove all but one incoming entries from the cluster
302     uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
303                      cast<ConstantInt>(Leaf.Low)->getSExtValue();    
304     for (uint64_t j = 0; j < Range; ++j) {
305       PN->removeIncomingValue(OrigBlock);
306     }
307     
308     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
309     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
310     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
311   }
312
313   return NewLeaf;
314 }
315
316 // Clusterify - Transform simple list of Cases into list of CaseRange's
317 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
318   unsigned numCmps = 0;
319
320   // Start with "simple" cases
321   for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
322     Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
323                               i.getCaseSuccessor()));
324   
325   std::sort(Cases.begin(), Cases.end(), CaseCmp());
326
327   // Merge case into clusters
328   if (Cases.size()>=2)
329     for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
330          J != Cases.end();) {
331       int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
332       int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
333       BasicBlock* nextBB = J->BB;
334       BasicBlock* currentBB = I->BB;
335
336       // If the two neighboring cases go to the same destination, merge them
337       // into a single case.
338       if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
339         I->High = J->High;
340         J = Cases.erase(J);
341       } else {
342         I = J++;
343       }
344     }
345
346   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
347     if (I->Low != I->High)
348       // A range counts double, since it requires two compares.
349       ++numCmps;
350   }
351
352   return numCmps;
353 }
354
355 // processSwitchInst - Replace the specified switch instruction with a sequence
356 // of chained if-then insts in a balanced binary search.
357 //
358 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
359   BasicBlock *CurBlock = SI->getParent();
360   BasicBlock *OrigBlock = CurBlock;
361   Function *F = CurBlock->getParent();
362   Value *Val = SI->getCondition();  // The value we are switching on...
363   BasicBlock* Default = SI->getDefaultDest();
364
365   // If there is only the default destination, don't bother with the code below.
366   if (!SI->getNumCases()) {
367     BranchInst::Create(SI->getDefaultDest(), CurBlock);
368     CurBlock->getInstList().erase(SI);
369     return;
370   }
371
372   const bool DefaultIsUnreachable =
373       Default->size() == 1 && isa<UnreachableInst>(Default->getTerminator());
374   // Create a new, empty default block so that the new hierarchy of
375   // if-then statements go to this and the PHI nodes are happy.
376   // if the default block is set as an unreachable we avoid creating one
377   // because will never be a valid target.
378   BasicBlock *NewDefault = nullptr;
379   if (!DefaultIsUnreachable) {
380     NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
381     F->getBasicBlockList().insert(Default, NewDefault);
382
383     BranchInst::Create(Default, NewDefault);
384   }
385   // If there is an entry in any PHI nodes for the default edge, make sure
386   // to update them as well.
387   for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
388     PHINode *PN = cast<PHINode>(I);
389     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
390     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
391     PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
392   }
393
394   // Prepare cases vector.
395   CaseVector Cases;
396   unsigned numCmps = Clusterify(Cases, SI);
397
398   DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
399                << ". Total compares: " << numCmps << "\n");
400   DEBUG(dbgs() << "Cases: " << Cases << "\n");
401   (void)numCmps;
402   
403   ConstantInt *UpperBound = nullptr;
404   ConstantInt *LowerBound = nullptr;
405
406   // Optimize the condition where Default is an unreachable block. In this case
407   // we can make the bounds tightly fitted around the case value ranges,
408   // because we know that the value passed to the switch should always be
409   // exactly one of the case values.
410   if (DefaultIsUnreachable) {
411     CaseItr LastCase = Cases.begin() + Cases.size() - 1;
412     UpperBound = cast<ConstantInt>(LastCase->High);
413     LowerBound = cast<ConstantInt>(Cases.begin()->Low);
414   }
415   BasicBlock *SwitchBlock =
416       switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
417                     OrigBlock, OrigBlock, NewDefault);
418
419   // Branch to our shiny new if-then stuff...
420   BranchInst::Create(SwitchBlock, OrigBlock);
421
422   // We are now done with the switch instruction, delete it.
423   CurBlock->getInstList().erase(SI);
424
425   pred_iterator PI = pred_begin(Default), E = pred_end(Default);
426   // If the Default block has no more predecessors just remove it
427   if (PI == E) {
428     DeleteDeadBlock(Default);
429   }
430 }