blob: d75880f585c3b3e7941a52e73518f52d09b93372 [file] [log] [blame]
Chris Lattner14383482003-04-23 16:23:59 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner14383482003-04-23 16:23:59 +00009//
Gordon Henriksenc86b6772007-11-04 16:15:04 +000010// The LowerSwitch transformation rewrites switch instructions with a sequence
11// of branches, which allows targets to get away with not implementing the
12// switch instruction until it is convenient.
Chris Lattner14383482003-04-23 16:23:59 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/Scalar.h"
Chris Lattner8d89e7b2006-05-09 04:13:41 +000017#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
Chris Lattnerebbc1a52003-10-07 18:46:23 +000018#include "llvm/Constants.h"
Chris Lattner14383482003-04-23 16:23:59 +000019#include "llvm/Function.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000020#include "llvm/Instructions.h"
Chris Lattner14383482003-04-23 16:23:59 +000021#include "llvm/Pass.h"
Dan Gohmanb61f2f02007-11-02 22:22:02 +000022#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000024#include "llvm/Support/Compiler.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000025#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner14383482003-04-23 16:23:59 +000028namespace {
Chris Lattner14383482003-04-23 16:23:59 +000029 /// 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 Lattnerf4b54612006-06-28 22:08:15 +000032 class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000033 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000034 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000035 LowerSwitch() : FunctionPass((intptr_t) &ID) {}
36
Chris Lattner8d89e7b2006-05-09 04:13:41 +000037 virtual bool runOnFunction(Function &F);
Chris Lattnered96fe82006-05-17 21:05:27 +000038
Chris Lattner8d89e7b2006-05-09 04:13:41 +000039 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Anton Korobeynikovbed29462007-04-16 18:10:23 +000040 // This is a cluster of orthogonal Transforms
Chris Lattner8d89e7b2006-05-09 04:13:41 +000041 AU.addPreserved<UnifyFunctionExitNodes>();
42 AU.addPreservedID(PromoteMemoryToRegisterID);
Chris Lattnered96fe82006-05-17 21:05:27 +000043 AU.addPreservedID(LowerInvokePassID);
44 AU.addPreservedID(LowerAllocationsID);
Chris Lattner8d89e7b2006-05-09 04:13:41 +000045 }
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000046
47 struct CaseRange {
48 Constant* Low;
49 Constant* High;
50 BasicBlock* BB;
51
Jeff Cohenc4558fd2007-03-12 17:56:27 +000052 CaseRange() : Low(0), High(0), BB(0) { }
53 CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
54 Low(low), High(high), BB(bb) { }
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000055 };
56
57 typedef std::vector<CaseRange> CaseVector;
58 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnerebbc1a52003-10-07 18:46:23 +000059 private:
Chris Lattner14383482003-04-23 16:23:59 +000060 void processSwitchInst(SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000061
62 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
63 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000064 BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnerebbc1a52003-10-07 18:46:23 +000065 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000066 unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000067 };
68
69 /// The comparison function for sorting the switch case values in the vector.
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000070 /// WARNING: Case ranges should be disjoint!
Chris Lattnerebbc1a52003-10-07 18:46:23 +000071 struct CaseCmp {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000072 bool operator () (const LowerSwitch::CaseRange& C1,
73 const LowerSwitch::CaseRange& C2) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000074
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000075 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
76 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
77 return CI1->getValue().slt(CI2->getValue());
Chris Lattnerebbc1a52003-10-07 18:46:23 +000078 }
Chris Lattner14383482003-04-23 16:23:59 +000079 };
80
Devang Patel19974732007-05-03 01:11:54 +000081 char LowerSwitch::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000082 RegisterPass<LowerSwitch>
Chris Lattner14383482003-04-23 16:23:59 +000083 X("lowerswitch", "Lower SwitchInst's to branches");
84}
85
Chris Lattnerb3674e42006-05-02 04:24:36 +000086// Publically exposed interface to pass...
87const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
Chris Lattner14383482003-04-23 16:23:59 +000088// createLowerSwitchPass - Interface to this file...
Chris Lattnerd7456022004-01-09 06:02:20 +000089FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner14383482003-04-23 16:23:59 +000090 return new LowerSwitch();
91}
92
93bool LowerSwitch::runOnFunction(Function &F) {
94 bool Changed = false;
95
96 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
97 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
98
99 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
100 Changed = true;
101 processSwitchInst(SI);
102 }
103 }
104
105 return Changed;
106}
107
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000108// operator<< - Used for debugging purposes.
109//
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000110static std::ostream& operator<<(std::ostream &O,
111 const LowerSwitch::CaseVector &C) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000112 O << "[";
113
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000114 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattnerd7456022004-01-09 06:02:20 +0000115 E = C.end(); B != E; ) {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000116 O << *B->Low << " -" << *B->High;
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000117 if (++B != E) O << ", ";
118 }
119
120 return O << "]";
121}
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000122
123static OStream& operator<<(OStream &O, const LowerSwitch::CaseVector &C) {
Bill Wendling5c7e3262006-12-17 05:15:13 +0000124 if (O.stream()) *O.stream() << C;
125 return O;
126}
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000127
128// switchConvert - Convert the switch statement into a binary lookup of
129// the case values. The function recursively builds this tree.
130//
131BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
132 Value* Val, BasicBlock* OrigBlock,
133 BasicBlock* Default)
134{
135 unsigned Size = End - Begin;
136
137 if (Size == 1)
138 return newLeafBlock(*Begin, Val, OrigBlock, Default);
139
140 unsigned Mid = Size / 2;
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000141 std::vector<CaseRange> LHS(Begin, Begin + Mid);
Bill Wendling0d45a092006-11-26 10:17:54 +0000142 DOUT << "LHS: " << LHS << "\n";
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000143 std::vector<CaseRange> RHS(Begin + Mid, End);
Bill Wendling0d45a092006-11-26 10:17:54 +0000144 DOUT << "RHS: " << RHS << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000145
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000146 CaseRange& Pivot = *(Begin + Mid);
Reid Spencere8391e02007-03-02 23:15:21 +0000147 DEBUG( DOUT << "Pivot ==> "
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000148 << cast<ConstantInt>(Pivot.Low)->getValue().toStringSigned(10)
149 << " -"
150 << cast<ConstantInt>(Pivot.High)->getValue().toStringSigned(10)
Reid Spencere8391e02007-03-02 23:15:21 +0000151 << "\n");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000152
153 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
154 OrigBlock, Default);
155 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
156 OrigBlock, Default);
157
158 // Create a new node that checks if the value is < pivot. Go to the
159 // left branch if it is and right branch if not.
160 Function* F = OrigBlock->getParent();
Gabor Greif051a9502008-04-06 20:25:17 +0000161 BasicBlock* NewNode = BasicBlock::Create("NodeBlock");
Chris Lattner261cdfb2007-04-17 18:09:47 +0000162 Function::iterator FI = OrigBlock;
163 F->getBasicBlockList().insert(++FI, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000164
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000165 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT, Val, Pivot.Low, "Pivot");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000166 NewNode->getInstList().push_back(Comp);
Gabor Greif051a9502008-04-06 20:25:17 +0000167 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000168 return NewNode;
169}
170
171// newLeafBlock - Create a new leaf block for the binary lookup tree. It
172// checks if the switch's value == the case's value. If not, then it
173// jumps to the default branch. At this point in the tree, the value
174// can't be another valid case value, so the jump to the "default" branch
175// is warranted.
176//
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000177BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000178 BasicBlock* OrigBlock,
179 BasicBlock* Default)
180{
181 Function* F = OrigBlock->getParent();
Gabor Greif051a9502008-04-06 20:25:17 +0000182 BasicBlock* NewLeaf = BasicBlock::Create("LeafBlock");
Chris Lattner261cdfb2007-04-17 18:09:47 +0000183 Function::iterator FI = OrigBlock;
184 F->getBasicBlockList().insert(++FI, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000185
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000186 // Emit comparison
187 ICmpInst* Comp = NULL;
188 if (Leaf.Low == Leaf.High) {
189 // Make the seteq instruction...
190 Comp = new ICmpInst(ICmpInst::ICMP_EQ, Val, Leaf.Low,
191 "SwitchLeaf", NewLeaf);
192 } else {
193 // Make range comparison
194 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
195 // Val >= Min && Val <= Hi --> Val <= Hi
196 Comp = new ICmpInst(ICmpInst::ICMP_SLE, Val, Leaf.High,
197 "SwitchLeaf", NewLeaf);
198 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
199 // Val >= 0 && Val <= Hi --> Val <=u Hi
200 Comp = new ICmpInst(ICmpInst::ICMP_ULE, Val, Leaf.High,
201 "SwitchLeaf", NewLeaf);
202 } else {
203 // Emit V-Lo <=u Hi-Lo
204 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
205 Instruction* Add = BinaryOperator::createAdd(Val, NegLo,
206 Val->getName()+".off",
207 NewLeaf);
208 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
209 Comp = new ICmpInst(ICmpInst::ICMP_ULE, Add, UpperBound,
210 "SwitchLeaf", NewLeaf);
211 }
212 }
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000213
214 // Make the conditional branch...
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000215 BasicBlock* Succ = Leaf.BB;
Gabor Greif051a9502008-04-06 20:25:17 +0000216 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000217
218 // If there were any PHI nodes in this successor, rewrite one entry
219 // from OrigBlock to come from NewLeaf.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000220 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
221 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000222 // Remove all but one incoming entries from the cluster
223 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
224 cast<ConstantInt>(Leaf.Low)->getSExtValue();
225 for (uint64_t j = 0; j < Range; ++j) {
226 PN->removeIncomingValue(OrigBlock);
227 }
228
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000229 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
230 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
231 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
232 }
233
234 return NewLeaf;
235}
236
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000237// Clusterify - Transform simple list of Cases into list of CaseRange's
238unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
239 unsigned numCmps = 0;
240
241 // Start with "simple" cases
242 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
243 Cases.push_back(CaseRange(SI->getSuccessorValue(i),
244 SI->getSuccessorValue(i),
245 SI->getSuccessor(i)));
Dan Gohman111c4f82007-11-02 22:24:01 +0000246 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000247
248 // Merge case into clusters
249 if (Cases.size()>=2)
David Greene9dfb11d2007-12-17 17:42:03 +0000250 for (CaseItr I=Cases.begin(), J=next(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000251 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
252 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
253 BasicBlock* nextBB = J->BB;
254 BasicBlock* currentBB = I->BB;
255
256 // If the two neighboring cases go to the same destination, merge them
257 // into a single case.
258 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
259 I->High = J->High;
260 J = Cases.erase(J);
261 } else {
262 I = J++;
263 }
264 }
265
266 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
267 if (I->Low != I->High)
268 // A range counts double, since it requires two compares.
269 ++numCmps;
270 }
271
272 return numCmps;
273}
274
Chris Lattner14383482003-04-23 16:23:59 +0000275// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000276// of chained if-then insts in a balanced binary search.
Chris Lattner14383482003-04-23 16:23:59 +0000277//
278void LowerSwitch::processSwitchInst(SwitchInst *SI) {
279 BasicBlock *CurBlock = SI->getParent();
280 BasicBlock *OrigBlock = CurBlock;
281 Function *F = CurBlock->getParent();
282 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000283 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner14383482003-04-23 16:23:59 +0000284
Chris Lattner44bb5412003-08-23 22:54:34 +0000285 // If there is only the default destination, don't bother with the code below.
286 if (SI->getNumOperands() == 2) {
Gabor Greif051a9502008-04-06 20:25:17 +0000287 BranchInst::Create(SI->getDefaultDest(), CurBlock);
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000288 CurBlock->getInstList().erase(SI);
Chris Lattner44bb5412003-08-23 22:54:34 +0000289 return;
290 }
291
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000292 // Create a new, empty default block so that the new hierarchy of
293 // if-then statements go to this and the PHI nodes are happy.
Gabor Greif051a9502008-04-06 20:25:17 +0000294 BasicBlock* NewDefault = BasicBlock::Create("NewDefault");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000295 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000296
Gabor Greif051a9502008-04-06 20:25:17 +0000297 BranchInst::Create(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000298
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000299 // If there is an entry in any PHI nodes for the default edge, make sure
300 // to update them as well.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000301 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
302 PHINode *PN = cast<PHINode>(I);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000303 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
304 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
305 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000306 }
307
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000308 // Prepare cases vector.
309 CaseVector Cases;
310 unsigned numCmps = Clusterify(Cases, SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000311
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000312 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
313 << ". Total compares: " << numCmps << "\n";
Bill Wendling0d45a092006-11-26 10:17:54 +0000314 DOUT << "Cases: " << Cases << "\n";
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000315
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000316 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
317 OrigBlock, NewDefault);
318
319 // Branch to our shiny new if-then stuff...
Gabor Greif051a9502008-04-06 20:25:17 +0000320 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000321
Chris Lattner14383482003-04-23 16:23:59 +0000322 // We are now done with the switch instruction, delete it.
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000323 CurBlock->getInstList().erase(SI);
Chris Lattner14383482003-04-23 16:23:59 +0000324}