s|llvm/Support/Visibility.h|llvm/Support/Compiler.h|
[oota-llvm.git] / lib / Transforms / Utils / LowerSwitch.cpp
1 //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The LowerSwitch transformation rewrites switch statements with a sequence of
11 // branches, which allows targets to get away with not implementing the switch
12 // statement 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/Support/Debug.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/ADT/Statistic.h"
25 #include <algorithm>
26 #include <iostream>
27 using namespace llvm;
28
29 namespace {
30   Statistic<> NumLowered("lowerswitch", "Number of SwitchInst's replaced");
31
32   /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
33   /// instructions.  Note that this cannot be a BasicBlock pass because it
34   /// modifies the CFG!
35   class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
36   public:
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(LowerSelectID);
44       AU.addPreservedID(LowerInvokePassID);
45       AU.addPreservedID(LowerAllocationsID);
46     }
47         
48     typedef std::pair<Constant*, BasicBlock*> Case;
49     typedef std::vector<Case>::iterator       CaseItr;
50   private:
51     void processSwitchInst(SwitchInst *SI);
52
53     BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
54                               BasicBlock* OrigBlock, BasicBlock* Default);
55     BasicBlock* newLeafBlock(Case& Leaf, Value* Val,
56                              BasicBlock* OrigBlock, BasicBlock* Default);
57   };
58
59   /// The comparison function for sorting the switch case values in the vector.
60   struct CaseCmp {
61     bool operator () (const LowerSwitch::Case& C1,
62                       const LowerSwitch::Case& C2) {
63       if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
64         return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
65
66       const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
67       return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
68     }
69   };
70
71   RegisterOpt<LowerSwitch>
72   X("lowerswitch", "Lower SwitchInst's to branches");
73 }
74
75 // Publically exposed interface to pass...
76 const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
77 // createLowerSwitchPass - Interface to this file...
78 FunctionPass *llvm::createLowerSwitchPass() {
79   return new LowerSwitch();
80 }
81
82 bool LowerSwitch::runOnFunction(Function &F) {
83   bool Changed = false;
84
85   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
86     BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
87
88     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
89       Changed = true;
90       processSwitchInst(SI);
91     }
92   }
93
94   return Changed;
95 }
96
97 // operator<< - Used for debugging purposes.
98 //
99 std::ostream& operator<<(std::ostream &O,
100                          const std::vector<LowerSwitch::Case> &C) {
101   O << "[";
102
103   for (std::vector<LowerSwitch::Case>::const_iterator B = C.begin(),
104          E = C.end(); B != E; ) {
105     O << *B->first;
106     if (++B != E) O << ", ";
107   }
108
109   return O << "]";
110 }
111
112 // switchConvert - Convert the switch statement into a binary lookup of
113 // the case values. The function recursively builds this tree.
114 //
115 BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
116                                        Value* Val, BasicBlock* OrigBlock,
117                                        BasicBlock* Default)
118 {
119   unsigned Size = End - Begin;
120
121   if (Size == 1)
122     return newLeafBlock(*Begin, Val, OrigBlock, Default);
123
124   unsigned Mid = Size / 2;
125   std::vector<Case> LHS(Begin, Begin + Mid);
126   DEBUG(std::cerr << "LHS: " << LHS << "\n");
127   std::vector<Case> RHS(Begin + Mid, End);
128   DEBUG(std::cerr << "RHS: " << RHS << "\n");
129
130   Case& Pivot = *(Begin + Mid);
131   DEBUG(std::cerr << "Pivot ==> "
132                   << (int64_t)cast<ConstantInt>(Pivot.first)->getRawValue()
133                   << "\n");
134
135   BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
136                                       OrigBlock, Default);
137   BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
138                                       OrigBlock, Default);
139
140   // Create a new node that checks if the value is < pivot. Go to the
141   // left branch if it is and right branch if not.
142   Function* F = OrigBlock->getParent();
143   BasicBlock* NewNode = new BasicBlock("NodeBlock");
144   F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
145
146   SetCondInst* Comp = new SetCondInst(Instruction::SetLT, Val, Pivot.first,
147                                       "Pivot");
148   NewNode->getInstList().push_back(Comp);
149   new BranchInst(LBranch, RBranch, Comp, NewNode);
150   return NewNode;
151 }
152
153 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
154 // checks if the switch's value == the case's value. If not, then it
155 // jumps to the default branch. At this point in the tree, the value
156 // can't be another valid case value, so the jump to the "default" branch
157 // is warranted.
158 //
159 BasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,
160                                       BasicBlock* OrigBlock,
161                                       BasicBlock* Default)
162 {
163   Function* F = OrigBlock->getParent();
164   BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
165   F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
166
167   // Make the seteq instruction...
168   SetCondInst* Comp = new SetCondInst(Instruction::SetEQ, Val,
169                                       Leaf.first, "SwitchLeaf");
170   NewLeaf->getInstList().push_back(Comp);
171
172   // Make the conditional branch...
173   BasicBlock* Succ = Leaf.second;
174   new BranchInst(Succ, Default, Comp, NewLeaf);
175
176   // If there were any PHI nodes in this successor, rewrite one entry
177   // from OrigBlock to come from NewLeaf.
178   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
179     PHINode* PN = cast<PHINode>(I);
180     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
181     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
182     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
183   }
184
185   return NewLeaf;
186 }
187
188 // processSwitchInst - Replace the specified switch instruction with a sequence
189 // of chained if-then insts in a balanced binary search.
190 //
191 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
192   BasicBlock *CurBlock = SI->getParent();
193   BasicBlock *OrigBlock = CurBlock;
194   Function *F = CurBlock->getParent();
195   Value *Val = SI->getOperand(0);  // The value we are switching on...
196   BasicBlock* Default = SI->getDefaultDest();
197
198   // If there is only the default destination, don't bother with the code below.
199   if (SI->getNumOperands() == 2) {
200     new BranchInst(SI->getDefaultDest(), CurBlock);
201     CurBlock->getInstList().erase(SI);
202     return;
203   }
204
205   // Create a new, empty default block so that the new hierarchy of
206   // if-then statements go to this and the PHI nodes are happy.
207   BasicBlock* NewDefault = new BasicBlock("NewDefault");
208   F->getBasicBlockList().insert(Default, NewDefault);
209
210   new BranchInst(Default, NewDefault);
211
212   // If there is an entry in any PHI nodes for the default edge, make sure
213   // to update them as well.
214   for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
215     PHINode *PN = cast<PHINode>(I);
216     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
217     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
218     PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
219   }
220
221   std::vector<Case> Cases;
222
223   // Expand comparisons for all of the non-default cases...
224   for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
225     Cases.push_back(Case(SI->getSuccessorValue(i), SI->getSuccessor(i)));
226
227   std::sort(Cases.begin(), Cases.end(), CaseCmp());
228   DEBUG(std::cerr << "Cases: " << Cases << "\n");
229   BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
230                                           OrigBlock, NewDefault);
231
232   // Branch to our shiny new if-then stuff...
233   new BranchInst(SwitchBlock, OrigBlock);
234
235   // We are now done with the switch instruction, delete it.
236   CurBlock->getInstList().erase(SI);
237 }