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