blob: 1da59360fc2beee10b06f6d6dfb8c1193f463f06 [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"
Chris Lattner944fac72008-08-23 22:23:09 +000025#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000026#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000027using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000028
Chris Lattner14383482003-04-23 16:23:59 +000029namespace {
Chris Lattner14383482003-04-23 16:23:59 +000030 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
31 /// instructions. Note that this cannot be a BasicBlock pass because it
32 /// modifies the CFG!
Chris Lattnerf4b54612006-06-28 22:08:15 +000033 class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000034 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000035 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000036 LowerSwitch() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000037
Chris Lattner8d89e7b2006-05-09 04:13:41 +000038 virtual bool runOnFunction(Function &F);
Chris Lattnered96fe82006-05-17 21:05:27 +000039
Chris Lattner8d89e7b2006-05-09 04:13:41 +000040 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Anton Korobeynikovbed29462007-04-16 18:10:23 +000041 // This is a cluster of orthogonal Transforms
Chris Lattner8d89e7b2006-05-09 04:13:41 +000042 AU.addPreserved<UnifyFunctionExitNodes>();
43 AU.addPreservedID(PromoteMemoryToRegisterID);
Chris Lattnered96fe82006-05-17 21:05:27 +000044 AU.addPreservedID(LowerInvokePassID);
45 AU.addPreservedID(LowerAllocationsID);
Chris Lattner8d89e7b2006-05-09 04:13:41 +000046 }
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000047
48 struct CaseRange {
49 Constant* Low;
50 Constant* High;
51 BasicBlock* BB;
52
Jeff Cohenc4558fd2007-03-12 17:56:27 +000053 CaseRange() : Low(0), High(0), BB(0) { }
54 CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
55 Low(low), High(high), BB(bb) { }
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000056 };
57
58 typedef std::vector<CaseRange> CaseVector;
59 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnerebbc1a52003-10-07 18:46:23 +000060 private:
Chris Lattner14383482003-04-23 16:23:59 +000061 void processSwitchInst(SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000062
63 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
64 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000065 BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnerebbc1a52003-10-07 18:46:23 +000066 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000067 unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000068 };
69
70 /// The comparison function for sorting the switch case values in the vector.
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000071 /// WARNING: Case ranges should be disjoint!
Chris Lattnerebbc1a52003-10-07 18:46:23 +000072 struct CaseCmp {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000073 bool operator () (const LowerSwitch::CaseRange& C1,
74 const LowerSwitch::CaseRange& C2) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000075
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000076 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
77 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
78 return CI1->getValue().slt(CI2->getValue());
Chris Lattnerebbc1a52003-10-07 18:46:23 +000079 }
Chris Lattner14383482003-04-23 16:23:59 +000080 };
Chris Lattner14383482003-04-23 16:23:59 +000081}
82
Dan Gohman844731a2008-05-13 00:00:25 +000083char LowerSwitch::ID = 0;
84static RegisterPass<LowerSwitch>
85X("lowerswitch", "Lower SwitchInst's to branches");
86
Chris Lattnerb3674e42006-05-02 04:24:36 +000087// Publically exposed interface to pass...
Dan Gohman6ddba2b2008-05-13 02:05:11 +000088const PassInfo *const llvm::LowerSwitchID = &X;
Chris Lattner14383482003-04-23 16:23:59 +000089// createLowerSwitchPass - Interface to this file...
Chris Lattnerd7456022004-01-09 06:02:20 +000090FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner14383482003-04-23 16:23:59 +000091 return new LowerSwitch();
92}
93
94bool LowerSwitch::runOnFunction(Function &F) {
95 bool Changed = false;
96
97 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
98 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
99
100 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
101 Changed = true;
102 processSwitchInst(SI);
103 }
104 }
105
106 return Changed;
107}
108
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000109// operator<< - Used for debugging purposes.
110//
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000111static std::ostream& operator<<(std::ostream &O,
112 const LowerSwitch::CaseVector &C) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000113 O << "[";
114
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000115 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattnerd7456022004-01-09 06:02:20 +0000116 E = C.end(); B != E; ) {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000117 O << *B->Low << " -" << *B->High;
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000118 if (++B != E) O << ", ";
119 }
120
121 return O << "]";
122}
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000123
124static OStream& operator<<(OStream &O, const LowerSwitch::CaseVector &C) {
Bill Wendling5c7e3262006-12-17 05:15:13 +0000125 if (O.stream()) *O.stream() << C;
126 return O;
127}
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000128
129// switchConvert - Convert the switch statement into a binary lookup of
130// the case values. The function recursively builds this tree.
131//
132BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
133 Value* Val, BasicBlock* OrigBlock,
134 BasicBlock* Default)
135{
136 unsigned Size = End - Begin;
137
138 if (Size == 1)
139 return newLeafBlock(*Begin, Val, OrigBlock, Default);
140
141 unsigned Mid = Size / 2;
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000142 std::vector<CaseRange> LHS(Begin, Begin + Mid);
Bill Wendling0d45a092006-11-26 10:17:54 +0000143 DOUT << "LHS: " << LHS << "\n";
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000144 std::vector<CaseRange> RHS(Begin + Mid, End);
Bill Wendling0d45a092006-11-26 10:17:54 +0000145 DOUT << "RHS: " << RHS << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000146
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000147 CaseRange& Pivot = *(Begin + Mid);
Chris Lattner944fac72008-08-23 22:23:09 +0000148 DEBUG(errs() << "Pivot ==> "
149 << cast<ConstantInt>(Pivot.Low)->getValue() << " -"
Dan Gohmanf871ccb2009-03-23 15:57:19 +0000150 << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000151
152 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
153 OrigBlock, Default);
154 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
155 OrigBlock, Default);
156
157 // Create a new node that checks if the value is < pivot. Go to the
158 // left branch if it is and right branch if not.
159 Function* F = OrigBlock->getParent();
Gabor Greif051a9502008-04-06 20:25:17 +0000160 BasicBlock* NewNode = BasicBlock::Create("NodeBlock");
Chris Lattner261cdfb2007-04-17 18:09:47 +0000161 Function::iterator FI = OrigBlock;
162 F->getBasicBlockList().insert(++FI, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000163
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000164 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT, Val, Pivot.Low, "Pivot");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000165 NewNode->getInstList().push_back(Comp);
Gabor Greif051a9502008-04-06 20:25:17 +0000166 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000167 return NewNode;
168}
169
170// newLeafBlock - Create a new leaf block for the binary lookup tree. It
171// checks if the switch's value == the case's value. If not, then it
172// jumps to the default branch. At this point in the tree, the value
173// can't be another valid case value, so the jump to the "default" branch
174// is warranted.
175//
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000176BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000177 BasicBlock* OrigBlock,
178 BasicBlock* Default)
179{
180 Function* F = OrigBlock->getParent();
Gabor Greif051a9502008-04-06 20:25:17 +0000181 BasicBlock* NewLeaf = BasicBlock::Create("LeafBlock");
Chris Lattner261cdfb2007-04-17 18:09:47 +0000182 Function::iterator FI = OrigBlock;
183 F->getBasicBlockList().insert(++FI, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000184
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000185 // Emit comparison
186 ICmpInst* Comp = NULL;
187 if (Leaf.Low == Leaf.High) {
188 // Make the seteq instruction...
189 Comp = new ICmpInst(ICmpInst::ICMP_EQ, Val, Leaf.Low,
190 "SwitchLeaf", NewLeaf);
191 } else {
192 // Make range comparison
193 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
194 // Val >= Min && Val <= Hi --> Val <= Hi
195 Comp = new ICmpInst(ICmpInst::ICMP_SLE, Val, Leaf.High,
196 "SwitchLeaf", NewLeaf);
197 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
198 // Val >= 0 && Val <= Hi --> Val <=u Hi
199 Comp = new ICmpInst(ICmpInst::ICMP_ULE, Val, Leaf.High,
200 "SwitchLeaf", NewLeaf);
201 } else {
202 // Emit V-Lo <=u Hi-Lo
203 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000204 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000205 Val->getName()+".off",
206 NewLeaf);
207 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
208 Comp = new ICmpInst(ICmpInst::ICMP_ULE, Add, UpperBound,
209 "SwitchLeaf", NewLeaf);
210 }
211 }
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000212
213 // Make the conditional branch...
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000214 BasicBlock* Succ = Leaf.BB;
Gabor Greif051a9502008-04-06 20:25:17 +0000215 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000216
217 // If there were any PHI nodes in this successor, rewrite one entry
218 // from OrigBlock to come from NewLeaf.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000219 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
220 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000221 // Remove all but one incoming entries from the cluster
222 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
223 cast<ConstantInt>(Leaf.Low)->getSExtValue();
224 for (uint64_t j = 0; j < Range; ++j) {
225 PN->removeIncomingValue(OrigBlock);
226 }
227
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000228 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
229 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
230 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
231 }
232
233 return NewLeaf;
234}
235
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000236// Clusterify - Transform simple list of Cases into list of CaseRange's
237unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
238 unsigned numCmps = 0;
239
240 // Start with "simple" cases
241 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
242 Cases.push_back(CaseRange(SI->getSuccessorValue(i),
243 SI->getSuccessorValue(i),
244 SI->getSuccessor(i)));
Dan Gohman111c4f82007-11-02 22:24:01 +0000245 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000246
247 // Merge case into clusters
248 if (Cases.size()>=2)
David Greene9dfb11d2007-12-17 17:42:03 +0000249 for (CaseItr I=Cases.begin(), J=next(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000250 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
251 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
252 BasicBlock* nextBB = J->BB;
253 BasicBlock* currentBB = I->BB;
254
255 // If the two neighboring cases go to the same destination, merge them
256 // into a single case.
257 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
258 I->High = J->High;
259 J = Cases.erase(J);
260 } else {
261 I = J++;
262 }
263 }
264
265 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
266 if (I->Low != I->High)
267 // A range counts double, since it requires two compares.
268 ++numCmps;
269 }
270
271 return numCmps;
272}
273
Chris Lattner14383482003-04-23 16:23:59 +0000274// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000275// of chained if-then insts in a balanced binary search.
Chris Lattner14383482003-04-23 16:23:59 +0000276//
277void LowerSwitch::processSwitchInst(SwitchInst *SI) {
278 BasicBlock *CurBlock = SI->getParent();
279 BasicBlock *OrigBlock = CurBlock;
280 Function *F = CurBlock->getParent();
281 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000282 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner14383482003-04-23 16:23:59 +0000283
Chris Lattner44bb5412003-08-23 22:54:34 +0000284 // If there is only the default destination, don't bother with the code below.
285 if (SI->getNumOperands() == 2) {
Gabor Greif051a9502008-04-06 20:25:17 +0000286 BranchInst::Create(SI->getDefaultDest(), CurBlock);
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000287 CurBlock->getInstList().erase(SI);
Chris Lattner44bb5412003-08-23 22:54:34 +0000288 return;
289 }
290
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000291 // Create a new, empty default block so that the new hierarchy of
292 // if-then statements go to this and the PHI nodes are happy.
Gabor Greif051a9502008-04-06 20:25:17 +0000293 BasicBlock* NewDefault = BasicBlock::Create("NewDefault");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000294 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000295
Gabor Greif051a9502008-04-06 20:25:17 +0000296 BranchInst::Create(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000297
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000298 // If there is an entry in any PHI nodes for the default edge, make sure
299 // to update them as well.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000300 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
301 PHINode *PN = cast<PHINode>(I);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000302 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
303 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
304 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000305 }
306
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000307 // Prepare cases vector.
308 CaseVector Cases;
309 unsigned numCmps = Clusterify(Cases, SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000310
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000311 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
312 << ". Total compares: " << numCmps << "\n";
Bill Wendling0d45a092006-11-26 10:17:54 +0000313 DOUT << "Cases: " << Cases << "\n";
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000314
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000315 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
316 OrigBlock, NewDefault);
317
318 // Branch to our shiny new if-then stuff...
Gabor Greif051a9502008-04-06 20:25:17 +0000319 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000320
Chris Lattner14383482003-04-23 16:23:59 +0000321 // We are now done with the switch instruction, delete it.
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000322 CurBlock->getInstList().erase(SI);
Chris Lattner14383482003-04-23 16:23:59 +0000323}