blob: a45192bb0cf52d67aaaca340a0d46646749df7ad [file] [log] [blame]
Chris Lattner1b094a02003-04-23 16:23:59 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattner1b094a02003-04-23 16:23:59 +00009//
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"
Chris Lattnered922162003-10-07 18:46:23 +000017#include "llvm/Constants.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000018#include "llvm/Function.h"
19#include "llvm/iTerminators.h"
20#include "llvm/iOperators.h"
21#include "llvm/iPHINode.h"
22#include "llvm/Pass.h"
Chris Lattnered922162003-10-07 18:46:23 +000023#include "Support/Debug.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000024#include "Support/Statistic.h"
25
26namespace {
27 Statistic<> NumLowered("lowerswitch", "Number of SwitchInst's replaced");
28
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!
Chris Lattnered922162003-10-07 18:46:23 +000032 class LowerSwitch : public FunctionPass {
33 public:
Chris Lattner1b094a02003-04-23 16:23:59 +000034 bool runOnFunction(Function &F);
Chris Lattnered922162003-10-07 18:46:23 +000035 typedef std::pair<Constant*, BasicBlock*> Case;
36 typedef std::vector<Case>::iterator CaseItr;
37 private:
Chris Lattner1b094a02003-04-23 16:23:59 +000038 void processSwitchInst(SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000039
40 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
41 BasicBlock* OrigBlock, BasicBlock* Default);
42 BasicBlock* newLeafBlock(Case& Leaf, Value* Val,
43 BasicBlock* OrigBlock, BasicBlock* Default);
44 };
45
46 /// The comparison function for sorting the switch case values in the vector.
47 struct CaseCmp {
48 bool operator () (const LowerSwitch::Case& C1,
49 const LowerSwitch::Case& C2) {
50 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
51 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
52
53 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
54 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
55 }
Chris Lattner1b094a02003-04-23 16:23:59 +000056 };
57
58 RegisterOpt<LowerSwitch>
59 X("lowerswitch", "Lower SwitchInst's to branches");
60}
61
62// createLowerSwitchPass - Interface to this file...
Brian Gaeke89207942003-08-13 18:18:15 +000063FunctionPass *createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +000064 return new LowerSwitch();
65}
66
67bool LowerSwitch::runOnFunction(Function &F) {
68 bool Changed = false;
69
70 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
71 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
72
73 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
74 Changed = true;
75 processSwitchInst(SI);
76 }
77 }
78
79 return Changed;
80}
81
Chris Lattnered922162003-10-07 18:46:23 +000082// operator<< - Used for debugging purposes.
83//
84std::ostream& operator << (std::ostream& O, std::vector<LowerSwitch::Case>& C)
85{
86 O << "[";
87
88 for (std::vector<LowerSwitch::Case>::iterator B = C.begin(), E = C.end();
89 B != E; ) {
90 O << *B->first;
91 if (++B != E) O << ", ";
92 }
93
94 return O << "]";
95}
96
97// switchConvert - Convert the switch statement into a binary lookup of
98// the case values. The function recursively builds this tree.
99//
100BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
101 Value* Val, BasicBlock* OrigBlock,
102 BasicBlock* Default)
103{
104 unsigned Size = End - Begin;
105
106 if (Size == 1)
107 return newLeafBlock(*Begin, Val, OrigBlock, Default);
108
109 unsigned Mid = Size / 2;
110 std::vector<Case> LHS(Begin, Begin + Mid);
111 DEBUG(std::cerr << "LHS: " << LHS << "\n");
112 std::vector<Case> RHS(Begin + Mid, End);
113 DEBUG(std::cerr << "RHS: " << RHS << "\n");
114
115 Case& Pivot = *(Begin + Mid);
116 DEBUG(std::cerr << "Pivot ==> "
117 << cast<ConstantUInt>(Pivot.first)->getValue() << "\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 BranchInst* Br = new BranchInst(LBranch, RBranch, Comp);
134 NewNode->getInstList().push_back(Br);
135 return NewNode;
136}
137
138// newLeafBlock - Create a new leaf block for the binary lookup tree. It
139// checks if the switch's value == the case's value. If not, then it
140// jumps to the default branch. At this point in the tree, the value
141// can't be another valid case value, so the jump to the "default" branch
142// is warranted.
143//
144BasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,
145 BasicBlock* OrigBlock,
146 BasicBlock* Default)
147{
148 Function* F = OrigBlock->getParent();
149 BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
150 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
151
152 // Make the seteq instruction...
153 SetCondInst* Comp = new SetCondInst(Instruction::SetEQ, Val,
154 Leaf.first, "SwitchLeaf");
155 NewLeaf->getInstList().push_back(Comp);
156
157 // Make the conditional branch...
158 BasicBlock* Succ = Leaf.second;
159 Instruction* Br = new BranchInst(Succ, Default, Comp);
160 NewLeaf->getInstList().push_back(Br);
161
162 // If there were any PHI nodes in this successor, rewrite one entry
163 // from OrigBlock to come from NewLeaf.
164 for (BasicBlock::iterator I = Succ->begin();
165 PHINode* PN = dyn_cast<PHINode>(I); ++I) {
166 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
167 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
168 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
169 }
170
171 return NewLeaf;
172}
173
Chris Lattner1b094a02003-04-23 16:23:59 +0000174// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnered922162003-10-07 18:46:23 +0000175// of chained if-then insts in a balanced binary search.
Chris Lattner1b094a02003-04-23 16:23:59 +0000176//
177void LowerSwitch::processSwitchInst(SwitchInst *SI) {
178 BasicBlock *CurBlock = SI->getParent();
179 BasicBlock *OrigBlock = CurBlock;
180 Function *F = CurBlock->getParent();
181 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000182 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000183
184 // Unlink the switch instruction from it's block.
185 CurBlock->getInstList().remove(SI);
186
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000187 // If there is only the default destination, don't bother with the code below.
188 if (SI->getNumOperands() == 2) {
189 CurBlock->getInstList().push_back(new BranchInst(SI->getDefaultDest()));
190 delete SI;
191 return;
192 }
193
Chris Lattnered922162003-10-07 18:46:23 +0000194 // Create a new, empty default block so that the new hierarchy of
195 // if-then statements go to this and the PHI nodes are happy.
196 BasicBlock* NewDefault = new BasicBlock("NewDefault");
197 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000198
Chris Lattnered922162003-10-07 18:46:23 +0000199 NewDefault->getInstList().push_back(new BranchInst(Default));
Chris Lattner1b094a02003-04-23 16:23:59 +0000200
Chris Lattnered922162003-10-07 18:46:23 +0000201 // If there is an entry in any PHI nodes for the default edge, make sure
202 // to update them as well.
203 for (BasicBlock::iterator I = Default->begin();
204 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
205 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
206 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
207 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000208 }
209
Chris Lattnered922162003-10-07 18:46:23 +0000210 std::vector<Case> Cases;
211
212 // Expand comparisons for all of the non-default cases...
213 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
214 Cases.push_back(Case(SI->getSuccessorValue(i), SI->getSuccessor(i)));
215
216 std::sort(Cases.begin(), Cases.end(), CaseCmp());
217 DEBUG(std::cerr << "Cases: " << Cases << "\n");
218 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
219 OrigBlock, NewDefault);
220
221 // Branch to our shiny new if-then stuff...
222 OrigBlock->getInstList().push_back(new BranchInst(SwitchBlock));
223
Chris Lattner1b094a02003-04-23 16:23:59 +0000224 // We are now done with the switch instruction, delete it.
225 delete SI;
226}