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"
28 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
29 /// instructions. Note that this cannot be a BasicBlock pass because it
31 class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
33 virtual bool runOnFunction(Function &F);
35 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
36 // This is a cluster of orthogonal Transforms
37 AU.addPreserved<UnifyFunctionExitNodes>();
38 AU.addPreservedID(PromoteMemoryToRegisterID);
39 AU.addPreservedID(LowerSelectID);
40 AU.addPreservedID(LowerInvokePassID);
41 AU.addPreservedID(LowerAllocationsID);
49 CaseRange(Constant* _Low = NULL, Constant* _High = NULL,
50 BasicBlock* _BB = NULL):
51 Low(_Low), High(_High), BB(_BB) { }
54 typedef std::vector<CaseRange> CaseVector;
55 typedef std::vector<CaseRange>::iterator CaseItr;
57 void processSwitchInst(SwitchInst *SI);
59 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
60 BasicBlock* OrigBlock, BasicBlock* Default);
61 BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
62 BasicBlock* OrigBlock, BasicBlock* Default);
63 unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
66 /// The comparison function for sorting the switch case values in the vector.
67 /// WARNING: Case ranges should be disjoint!
69 bool operator () (const LowerSwitch::CaseRange& C1,
70 const LowerSwitch::CaseRange& C2) {
72 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
73 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
74 return CI1->getValue().slt(CI2->getValue());
78 RegisterPass<LowerSwitch>
79 X("lowerswitch", "Lower SwitchInst's to branches");
82 // Publically exposed interface to pass...
83 const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
84 // createLowerSwitchPass - Interface to this file...
85 FunctionPass *llvm::createLowerSwitchPass() {
86 return new LowerSwitch();
89 bool LowerSwitch::runOnFunction(Function &F) {
92 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
93 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
95 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
97 processSwitchInst(SI);
104 // operator<< - Used for debugging purposes.
106 static std::ostream& operator<<(std::ostream &O,
107 const LowerSwitch::CaseVector &C) {
110 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
111 E = C.end(); B != E; ) {
112 O << *B->Low << " -" << *B->High;
113 if (++B != E) O << ", ";
119 static OStream& operator<<(OStream &O, const LowerSwitch::CaseVector &C) {
120 if (O.stream()) *O.stream() << C;
124 // switchConvert - Convert the switch statement into a binary lookup of
125 // the case values. The function recursively builds this tree.
127 BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
128 Value* Val, BasicBlock* OrigBlock,
131 unsigned Size = End - Begin;
134 return newLeafBlock(*Begin, Val, OrigBlock, Default);
136 unsigned Mid = Size / 2;
137 std::vector<CaseRange> LHS(Begin, Begin + Mid);
138 DOUT << "LHS: " << LHS << "\n";
139 std::vector<CaseRange> RHS(Begin + Mid, End);
140 DOUT << "RHS: " << RHS << "\n";
142 CaseRange& Pivot = *(Begin + Mid);
143 DEBUG( DOUT << "Pivot ==> "
144 << cast<ConstantInt>(Pivot.Low)->getValue().toStringSigned(10)
146 << cast<ConstantInt>(Pivot.High)->getValue().toStringSigned(10)
149 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
151 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
154 // Create a new node that checks if the value is < pivot. Go to the
155 // left branch if it is and right branch if not.
156 Function* F = OrigBlock->getParent();
157 BasicBlock* NewNode = new BasicBlock("NodeBlock");
158 F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
160 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT, Val, Pivot.Low, "Pivot");
161 NewNode->getInstList().push_back(Comp);
162 new BranchInst(LBranch, RBranch, Comp, NewNode);
166 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
167 // checks if the switch's value == the case's value. If not, then it
168 // jumps to the default branch. At this point in the tree, the value
169 // can't be another valid case value, so the jump to the "default" branch
172 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
173 BasicBlock* OrigBlock,
176 Function* F = OrigBlock->getParent();
177 BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
178 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
181 ICmpInst* Comp = NULL;
182 if (Leaf.Low == Leaf.High) {
183 // Make the seteq instruction...
184 Comp = new ICmpInst(ICmpInst::ICMP_EQ, Val, Leaf.Low,
185 "SwitchLeaf", NewLeaf);
187 // Make range comparison
188 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
189 // Val >= Min && Val <= Hi --> Val <= Hi
190 Comp = new ICmpInst(ICmpInst::ICMP_SLE, Val, Leaf.High,
191 "SwitchLeaf", NewLeaf);
192 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
193 // Val >= 0 && Val <= Hi --> Val <=u Hi
194 Comp = new ICmpInst(ICmpInst::ICMP_ULE, Val, Leaf.High,
195 "SwitchLeaf", NewLeaf);
197 // Emit V-Lo <=u Hi-Lo
198 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
199 Instruction* Add = BinaryOperator::createAdd(Val, NegLo,
200 Val->getName()+".off",
202 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
203 Comp = new ICmpInst(ICmpInst::ICMP_ULE, Add, UpperBound,
204 "SwitchLeaf", NewLeaf);
208 // Make the conditional branch...
209 BasicBlock* Succ = Leaf.BB;
210 new BranchInst(Succ, Default, Comp, NewLeaf);
212 // If there were any PHI nodes in this successor, rewrite one entry
213 // from OrigBlock to come from NewLeaf.
214 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
215 PHINode* PN = cast<PHINode>(I);
216 // Remove all but one incoming entries from the cluster
217 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
218 cast<ConstantInt>(Leaf.Low)->getSExtValue();
219 for (uint64_t j = 0; j < Range; ++j) {
220 PN->removeIncomingValue(OrigBlock);
223 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
224 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
225 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
231 // Clusterify - Transform simple list of Cases into list of CaseRange's
232 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
233 unsigned numCmps = 0;
235 // Start with "simple" cases
236 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
237 Cases.push_back(CaseRange(SI->getSuccessorValue(i),
238 SI->getSuccessorValue(i),
239 SI->getSuccessor(i)));
240 sort(Cases.begin(), Cases.end(), CaseCmp());
242 // Merge case into clusters
244 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
245 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
246 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
247 BasicBlock* nextBB = J->BB;
248 BasicBlock* currentBB = I->BB;
250 // If the two neighboring cases go to the same destination, merge them
251 // into a single case.
252 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
260 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
261 if (I->Low != I->High)
262 // A range counts double, since it requires two compares.
269 // processSwitchInst - Replace the specified switch instruction with a sequence
270 // of chained if-then insts in a balanced binary search.
272 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
273 BasicBlock *CurBlock = SI->getParent();
274 BasicBlock *OrigBlock = CurBlock;
275 Function *F = CurBlock->getParent();
276 Value *Val = SI->getOperand(0); // The value we are switching on...
277 BasicBlock* Default = SI->getDefaultDest();
279 // If there is only the default destination, don't bother with the code below.
280 if (SI->getNumOperands() == 2) {
281 new BranchInst(SI->getDefaultDest(), CurBlock);
282 CurBlock->getInstList().erase(SI);
286 // Create a new, empty default block so that the new hierarchy of
287 // if-then statements go to this and the PHI nodes are happy.
288 BasicBlock* NewDefault = new BasicBlock("NewDefault");
289 F->getBasicBlockList().insert(Default, NewDefault);
291 new BranchInst(Default, NewDefault);
293 // If there is an entry in any PHI nodes for the default edge, make sure
294 // to update them as well.
295 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
296 PHINode *PN = cast<PHINode>(I);
297 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
298 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
299 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
302 // Prepare cases vector.
304 unsigned numCmps = Clusterify(Cases, SI);
306 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
307 << ". Total compares: " << numCmps << "\n";
308 DOUT << "Cases: " << Cases << "\n";
310 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
311 OrigBlock, NewDefault);
313 // Branch to our shiny new if-then stuff...
314 new BranchInst(SwitchBlock, OrigBlock);
316 // We are now done with the switch instruction, delete it.
317 CurBlock->getInstList().erase(SI);