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