1 //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
26 Statistic<> NumLowered("lowerswitch", "Number of SwitchInst's replaced");
28 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
29 /// instructions. Note that this cannot be a BasicBlock pass because it
31 class LowerSwitch : public FunctionPass {
33 bool runOnFunction(Function &F);
34 typedef std::pair<Constant*, BasicBlock*> Case;
35 typedef std::vector<Case>::iterator CaseItr;
37 void processSwitchInst(SwitchInst *SI);
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);
45 /// The comparison function for sorting the switch case values in the vector.
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();
52 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
53 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
57 RegisterOpt<LowerSwitch>
58 X("lowerswitch", "Lower SwitchInst's to branches");
61 // createLowerSwitchPass - Interface to this file...
62 FunctionPass *llvm::createLowerSwitchPass() {
63 return new LowerSwitch();
66 bool LowerSwitch::runOnFunction(Function &F) {
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
72 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
74 processSwitchInst(SI);
81 // operator<< - Used for debugging purposes.
83 std::ostream& operator<<(std::ostream &O,
84 const std::vector<LowerSwitch::Case> &C) {
87 for (std::vector<LowerSwitch::Case>::const_iterator B = C.begin(),
88 E = C.end(); B != E; ) {
90 if (++B != E) O << ", ";
96 // switchConvert - Convert the switch statement into a binary lookup of
97 // the case values. The function recursively builds this tree.
99 BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
100 Value* Val, BasicBlock* OrigBlock,
103 unsigned Size = End - Begin;
106 return newLeafBlock(*Begin, Val, OrigBlock, Default);
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");
114 Case& Pivot = *(Begin + Mid);
115 DEBUG(std::cerr << "Pivot ==> "
116 << (int64_t)cast<ConstantInt>(Pivot.first)->getRawValue()
119 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
121 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
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);
130 SetCondInst* Comp = new SetCondInst(Instruction::SetLT, Val, Pivot.first,
132 NewNode->getInstList().push_back(Comp);
133 new BranchInst(LBranch, RBranch, Comp, NewNode);
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
143 BasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,
144 BasicBlock* OrigBlock,
147 Function* F = OrigBlock->getParent();
148 BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
149 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
151 // Make the seteq instruction...
152 SetCondInst* Comp = new SetCondInst(Instruction::SetEQ, Val,
153 Leaf.first, "SwitchLeaf");
154 NewLeaf->getInstList().push_back(Comp);
156 // Make the conditional branch...
157 BasicBlock* Succ = Leaf.second;
158 new BranchInst(Succ, Default, Comp, NewLeaf);
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);
172 // processSwitchInst - Replace the specified switch instruction with a sequence
173 // of chained if-then insts in a balanced binary search.
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();
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);
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);
194 new BranchInst(Default, NewDefault);
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);
205 std::vector<Case> Cases;
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)));
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);
216 // Branch to our shiny new if-then stuff...
217 new BranchInst(SwitchBlock, OrigBlock);
219 // We are now done with the switch instruction, delete it.
220 CurBlock->getInstList().erase(SI);