Rework the routines that convert AP[S]Int into a string. Now, instead of
[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/UnifyFunctionExitNodes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Compiler.h"
25 #include <algorithm>
26 using namespace llvm;
27
28 namespace {
29   /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
30   /// instructions.  Note that this cannot be a BasicBlock pass because it
31   /// modifies the CFG!
32   class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
33   public:
34     static char ID; // Pass identification, replacement for typeid
35     LowerSwitch() : FunctionPass((intptr_t) &ID) {} 
36
37     virtual bool runOnFunction(Function &F);
38     
39     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40       // This is a cluster of orthogonal Transforms
41       AU.addPreserved<UnifyFunctionExitNodes>();
42       AU.addPreservedID(PromoteMemoryToRegisterID);
43       AU.addPreservedID(LowerInvokePassID);
44       AU.addPreservedID(LowerAllocationsID);
45     }
46
47     struct CaseRange {
48       Constant* Low;
49       Constant* High;
50       BasicBlock* BB;
51
52       CaseRange() : Low(0), High(0), BB(0) { }
53       CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
54         Low(low), High(high), BB(bb) { }
55     };
56
57     typedef std::vector<CaseRange>           CaseVector;
58     typedef std::vector<CaseRange>::iterator CaseItr;
59   private:
60     void processSwitchInst(SwitchInst *SI);
61
62     BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
63                               BasicBlock* OrigBlock, BasicBlock* Default);
64     BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
65                              BasicBlock* OrigBlock, BasicBlock* Default);
66     unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
67   };
68
69   /// The comparison function for sorting the switch case values in the vector.
70   /// WARNING: Case ranges should be disjoint!
71   struct CaseCmp {
72     bool operator () (const LowerSwitch::CaseRange& C1,
73                       const LowerSwitch::CaseRange& C2) {
74
75       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
76       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
77       return CI1->getValue().slt(CI2->getValue());
78     }
79   };
80 }
81
82 char LowerSwitch::ID = 0;
83 static RegisterPass<LowerSwitch>
84 X("lowerswitch", "Lower SwitchInst's to branches");
85
86 // Publically exposed interface to pass...
87 const PassInfo *const llvm::LowerSwitchID = &X;
88 // createLowerSwitchPass - Interface to this file...
89 FunctionPass *llvm::createLowerSwitchPass() {
90   return new LowerSwitch();
91 }
92
93 bool LowerSwitch::runOnFunction(Function &F) {
94   bool Changed = false;
95
96   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
97     BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
98
99     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
100       Changed = true;
101       processSwitchInst(SI);
102     }
103   }
104
105   return Changed;
106 }
107
108 // operator<< - Used for debugging purposes.
109 //
110 static std::ostream& operator<<(std::ostream &O,
111                                 const LowerSwitch::CaseVector &C) {
112   O << "[";
113
114   for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
115          E = C.end(); B != E; ) {
116     O << *B->Low << " -" << *B->High;
117     if (++B != E) O << ", ";
118   }
119
120   return O << "]";
121 }
122
123 static OStream& operator<<(OStream &O, const LowerSwitch::CaseVector &C) {
124   if (O.stream()) *O.stream() << C;
125   return O;
126 }
127
128 // switchConvert - Convert the switch statement into a binary lookup of
129 // the case values. The function recursively builds this tree.
130 //
131 BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
132                                        Value* Val, BasicBlock* OrigBlock,
133                                        BasicBlock* Default)
134 {
135   unsigned Size = End - Begin;
136
137   if (Size == 1)
138     return newLeafBlock(*Begin, Val, OrigBlock, Default);
139
140   unsigned Mid = Size / 2;
141   std::vector<CaseRange> LHS(Begin, Begin + Mid);
142   DOUT << "LHS: " << LHS << "\n";
143   std::vector<CaseRange> RHS(Begin + Mid, End);
144   DOUT << "RHS: " << RHS << "\n";
145
146   CaseRange& Pivot = *(Begin + Mid);
147   DEBUG(cerr << "Pivot ==> " 
148              << cast<ConstantInt>(Pivot.Low)->getValue() << " -"
149              << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
150
151   BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
152                                       OrigBlock, Default);
153   BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
154                                       OrigBlock, Default);
155
156   // Create a new node that checks if the value is < pivot. Go to the
157   // left branch if it is and right branch if not.
158   Function* F = OrigBlock->getParent();
159   BasicBlock* NewNode = BasicBlock::Create("NodeBlock");
160   Function::iterator FI = OrigBlock;
161   F->getBasicBlockList().insert(++FI, NewNode);
162
163   ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT, Val, Pivot.Low, "Pivot");
164   NewNode->getInstList().push_back(Comp);
165   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
166   return NewNode;
167 }
168
169 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
170 // checks if the switch's value == the case's value. If not, then it
171 // jumps to the default branch. At this point in the tree, the value
172 // can't be another valid case value, so the jump to the "default" branch
173 // is warranted.
174 //
175 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
176                                       BasicBlock* OrigBlock,
177                                       BasicBlock* Default)
178 {
179   Function* F = OrigBlock->getParent();
180   BasicBlock* NewLeaf = BasicBlock::Create("LeafBlock");
181   Function::iterator FI = OrigBlock;
182   F->getBasicBlockList().insert(++FI, NewLeaf);
183
184   // Emit comparison
185   ICmpInst* Comp = NULL;
186   if (Leaf.Low == Leaf.High) {
187     // Make the seteq instruction...
188     Comp = new ICmpInst(ICmpInst::ICMP_EQ, Val, Leaf.Low,
189                         "SwitchLeaf", NewLeaf);
190   } else {
191     // Make range comparison
192     if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
193       // Val >= Min && Val <= Hi --> Val <= Hi
194       Comp = new ICmpInst(ICmpInst::ICMP_SLE, Val, Leaf.High,
195                           "SwitchLeaf", NewLeaf);
196     } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
197       // Val >= 0 && Val <= Hi --> Val <=u Hi
198       Comp = new ICmpInst(ICmpInst::ICMP_ULE, Val, Leaf.High,
199                           "SwitchLeaf", NewLeaf);      
200     } else {
201       // Emit V-Lo <=u Hi-Lo
202       Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
203       Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
204                                                    Val->getName()+".off",
205                                                    NewLeaf);
206       Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
207       Comp = new ICmpInst(ICmpInst::ICMP_ULE, Add, UpperBound,
208                           "SwitchLeaf", NewLeaf);
209     }
210   }
211
212   // Make the conditional branch...
213   BasicBlock* Succ = Leaf.BB;
214   BranchInst::Create(Succ, Default, Comp, NewLeaf);
215
216   // If there were any PHI nodes in this successor, rewrite one entry
217   // from OrigBlock to come from NewLeaf.
218   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
219     PHINode* PN = cast<PHINode>(I);
220     // Remove all but one incoming entries from the cluster
221     uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
222                      cast<ConstantInt>(Leaf.Low)->getSExtValue();    
223     for (uint64_t j = 0; j < Range; ++j) {
224       PN->removeIncomingValue(OrigBlock);
225     }
226     
227     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
228     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
229     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
230   }
231
232   return NewLeaf;
233 }
234
235 // Clusterify - Transform simple list of Cases into list of CaseRange's
236 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
237   unsigned numCmps = 0;
238
239   // Start with "simple" cases
240   for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
241     Cases.push_back(CaseRange(SI->getSuccessorValue(i),
242                               SI->getSuccessorValue(i),
243                               SI->getSuccessor(i)));
244   std::sort(Cases.begin(), Cases.end(), CaseCmp());
245
246   // Merge case into clusters
247   if (Cases.size()>=2)
248     for (CaseItr I=Cases.begin(), J=next(Cases.begin()); J!=Cases.end(); ) {
249       int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
250       int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
251       BasicBlock* nextBB = J->BB;
252       BasicBlock* currentBB = I->BB;
253
254       // If the two neighboring cases go to the same destination, merge them
255       // into a single case.
256       if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
257         I->High = J->High;
258         J = Cases.erase(J);
259       } else {
260         I = J++;
261       }
262     }
263
264   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
265     if (I->Low != I->High)
266       // A range counts double, since it requires two compares.
267       ++numCmps;
268   }
269
270   return numCmps;
271 }
272
273 // processSwitchInst - Replace the specified switch instruction with a sequence
274 // of chained if-then insts in a balanced binary search.
275 //
276 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
277   BasicBlock *CurBlock = SI->getParent();
278   BasicBlock *OrigBlock = CurBlock;
279   Function *F = CurBlock->getParent();
280   Value *Val = SI->getOperand(0);  // The value we are switching on...
281   BasicBlock* Default = SI->getDefaultDest();
282
283   // If there is only the default destination, don't bother with the code below.
284   if (SI->getNumOperands() == 2) {
285     BranchInst::Create(SI->getDefaultDest(), CurBlock);
286     CurBlock->getInstList().erase(SI);
287     return;
288   }
289
290   // Create a new, empty default block so that the new hierarchy of
291   // if-then statements go to this and the PHI nodes are happy.
292   BasicBlock* NewDefault = BasicBlock::Create("NewDefault");
293   F->getBasicBlockList().insert(Default, NewDefault);
294
295   BranchInst::Create(Default, NewDefault);
296
297   // If there is an entry in any PHI nodes for the default edge, make sure
298   // to update them as well.
299   for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
300     PHINode *PN = cast<PHINode>(I);
301     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
302     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
303     PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
304   }
305
306   // Prepare cases vector.
307   CaseVector Cases;
308   unsigned numCmps = Clusterify(Cases, SI);
309
310   DOUT << "Clusterify finished. Total clusters: " << Cases.size()
311        << ". Total compares: " << numCmps << "\n";
312   DOUT << "Cases: " << Cases << "\n";
313   
314   BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
315                                           OrigBlock, NewDefault);
316
317   // Branch to our shiny new if-then stuff...
318   BranchInst::Create(SwitchBlock, OrigBlock);
319
320   // We are now done with the switch instruction, delete it.
321   CurBlock->getInstList().erase(SI);
322 }