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/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"
30 Statistic<> NumLowered("lowerswitch", "Number of SwitchInst's replaced");
32 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
33 /// instructions. Note that this cannot be a BasicBlock pass because it
35 class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
37 virtual bool runOnFunction(Function &F);
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);
48 typedef std::pair<Constant*, BasicBlock*> Case;
49 typedef std::vector<Case>::iterator CaseItr;
51 void processSwitchInst(SwitchInst *SI);
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);
59 /// The comparison function for sorting the switch case values in the vector.
61 bool operator () (const LowerSwitch::Case& C1,
62 const LowerSwitch::Case& C2) {
64 const ConstantInt* CI1 = cast<const ConstantInt>(C1.first);
65 const ConstantInt* CI2 = cast<const ConstantInt>(C2.first);
66 if (CI1->getType()->isUnsigned())
67 return CI1->getZExtValue() < CI2->getZExtValue();
68 return CI1->getSExtValue() < CI2->getSExtValue();
72 RegisterPass<LowerSwitch>
73 X("lowerswitch", "Lower SwitchInst's to branches");
76 // Publically exposed interface to pass...
77 const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
78 // createLowerSwitchPass - Interface to this file...
79 FunctionPass *llvm::createLowerSwitchPass() {
80 return new LowerSwitch();
83 bool LowerSwitch::runOnFunction(Function &F) {
86 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
87 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
89 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
91 processSwitchInst(SI);
98 // operator<< - Used for debugging purposes.
100 std::ostream& operator<<(std::ostream &O,
101 const std::vector<LowerSwitch::Case> &C) {
104 for (std::vector<LowerSwitch::Case>::const_iterator B = C.begin(),
105 E = C.end(); B != E; ) {
107 if (++B != E) O << ", ";
113 // switchConvert - Convert the switch statement into a binary lookup of
114 // the case values. The function recursively builds this tree.
116 BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
117 Value* Val, BasicBlock* OrigBlock,
120 unsigned Size = End - Begin;
123 return newLeafBlock(*Begin, Val, OrigBlock, Default);
125 unsigned Mid = Size / 2;
126 std::vector<Case> LHS(Begin, Begin + Mid);
127 DEBUG(std::cerr << "LHS: " << LHS << "\n");
128 std::vector<Case> RHS(Begin + Mid, End);
129 DEBUG(std::cerr << "RHS: " << RHS << "\n");
131 Case& Pivot = *(Begin + Mid);
132 DEBUG(std::cerr << "Pivot ==> "
133 << cast<ConstantInt>(Pivot.first)->getSExtValue()
136 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
138 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
141 // Create a new node that checks if the value is < pivot. Go to the
142 // left branch if it is and right branch if not.
143 Function* F = OrigBlock->getParent();
144 BasicBlock* NewNode = new BasicBlock("NodeBlock");
145 F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
147 SetCondInst* Comp = new SetCondInst(Instruction::SetLT, Val, Pivot.first,
149 NewNode->getInstList().push_back(Comp);
150 new BranchInst(LBranch, RBranch, Comp, NewNode);
154 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
155 // checks if the switch's value == the case's value. If not, then it
156 // jumps to the default branch. At this point in the tree, the value
157 // can't be another valid case value, so the jump to the "default" branch
160 BasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,
161 BasicBlock* OrigBlock,
164 Function* F = OrigBlock->getParent();
165 BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
166 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
168 // Make the seteq instruction...
169 SetCondInst* Comp = new SetCondInst(Instruction::SetEQ, Val,
170 Leaf.first, "SwitchLeaf");
171 NewLeaf->getInstList().push_back(Comp);
173 // Make the conditional branch...
174 BasicBlock* Succ = Leaf.second;
175 new BranchInst(Succ, Default, Comp, NewLeaf);
177 // If there were any PHI nodes in this successor, rewrite one entry
178 // from OrigBlock to come from NewLeaf.
179 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
180 PHINode* PN = cast<PHINode>(I);
181 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
182 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
183 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
189 // processSwitchInst - Replace the specified switch instruction with a sequence
190 // of chained if-then insts in a balanced binary search.
192 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
193 BasicBlock *CurBlock = SI->getParent();
194 BasicBlock *OrigBlock = CurBlock;
195 Function *F = CurBlock->getParent();
196 Value *Val = SI->getOperand(0); // The value we are switching on...
197 BasicBlock* Default = SI->getDefaultDest();
199 // If there is only the default destination, don't bother with the code below.
200 if (SI->getNumOperands() == 2) {
201 new BranchInst(SI->getDefaultDest(), CurBlock);
202 CurBlock->getInstList().erase(SI);
206 // Create a new, empty default block so that the new hierarchy of
207 // if-then statements go to this and the PHI nodes are happy.
208 BasicBlock* NewDefault = new BasicBlock("NewDefault");
209 F->getBasicBlockList().insert(Default, NewDefault);
211 new BranchInst(Default, NewDefault);
213 // If there is an entry in any PHI nodes for the default edge, make sure
214 // to update them as well.
215 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
216 PHINode *PN = cast<PHINode>(I);
217 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
218 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
219 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
222 std::vector<Case> Cases;
224 // Expand comparisons for all of the non-default cases...
225 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
226 Cases.push_back(Case(SI->getSuccessorValue(i), SI->getSuccessor(i)));
228 std::sort(Cases.begin(), Cases.end(), CaseCmp());
229 DEBUG(std::cerr << "Cases: " << Cases << "\n");
230 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
231 OrigBlock, NewDefault);
233 // Branch to our shiny new if-then stuff...
234 new BranchInst(SwitchBlock, OrigBlock);
236 // We are now done with the switch instruction, delete it.
237 CurBlock->getInstList().erase(SI);