blob: dce57f517bcbc343f9461f8e32b806d0360df112 [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"
Owen Anderson0a205a42009-07-05 22:41:43 +000021#include "llvm/LLVMContext.h"
Chris Lattner14383482003-04-23 16:23:59 +000022#include "llvm/Pass.h"
Dan Gohmanb61f2f02007-11-02 22:22:02 +000023#include "llvm/ADT/STLExtras.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000024#include "llvm/Support/Compiler.h"
Nick Lewyckyf5a86f42009-10-25 06:57:41 +000025#include "llvm/Support/Debug.h"
Chris Lattner944fac72008-08-23 22:23:09 +000026#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000027#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattner14383482003-04-23 16:23:59 +000030namespace {
Chris Lattner14383482003-04-23 16:23:59 +000031 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
Chris Lattner473fc962010-08-18 02:41:56 +000032 /// instructions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000033 class 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
Owen Anderson90c579d2010-08-06 18:33:48 +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>();
Dan Gohman60493c32010-08-06 21:48:06 +000043 AU.addPreserved("mem2reg");
Chris Lattnered96fe82006-05-17 21:05:27 +000044 AU.addPreservedID(LowerInvokePassID);
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
Chris Lattner473fc962010-08-18 02:41:56 +000052 CaseRange(Constant *low = 0, Constant *high = 0, BasicBlock *bb = 0) :
Jeff Cohenc4558fd2007-03-12 17:56:27 +000053 Low(low), High(high), BB(bb) { }
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000054 };
55
56 typedef std::vector<CaseRange> CaseVector;
57 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnerebbc1a52003-10-07 18:46:23 +000058 private:
Chris Lattner14383482003-04-23 16:23:59 +000059 void processSwitchInst(SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000060
61 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
62 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000063 BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnerebbc1a52003-10-07 18:46:23 +000064 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000065 unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000066 };
67
68 /// The comparison function for sorting the switch case values in the vector.
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000069 /// WARNING: Case ranges should be disjoint!
Chris Lattnerebbc1a52003-10-07 18:46:23 +000070 struct CaseCmp {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000071 bool operator () (const LowerSwitch::CaseRange& C1,
72 const LowerSwitch::CaseRange& C2) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000073
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000074 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
75 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
76 return CI1->getValue().slt(CI2->getValue());
Chris Lattnerebbc1a52003-10-07 18:46:23 +000077 }
Chris Lattner14383482003-04-23 16:23:59 +000078 };
Chris Lattner14383482003-04-23 16:23:59 +000079}
80
Dan Gohman844731a2008-05-13 00:00:25 +000081char LowerSwitch::ID = 0;
Owen Anderson02dd53e2010-08-23 17:52:01 +000082INITIALIZE_PASS(LowerSwitch, "lowerswitch",
Owen Andersonce665bd2010-10-07 22:25:06 +000083 "Lower SwitchInst's to branches", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000084
Chris Lattnerb3674e42006-05-02 04:24:36 +000085// Publically exposed interface to pass...
Owen Anderson90c579d2010-08-06 18:33:48 +000086char &llvm::LowerSwitchID = LowerSwitch::ID;
Chris Lattner14383482003-04-23 16:23:59 +000087// createLowerSwitchPass - Interface to this file...
Chris Lattnerd7456022004-01-09 06:02:20 +000088FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner14383482003-04-23 16:23:59 +000089 return new LowerSwitch();
90}
91
92bool LowerSwitch::runOnFunction(Function &F) {
93 bool Changed = false;
94
95 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
96 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
97
98 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
99 Changed = true;
100 processSwitchInst(SI);
101 }
102 }
103
104 return Changed;
105}
106
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000107// operator<< - Used for debugging purposes.
108//
Daniel Dunbar1cd1d982009-07-24 10:36:58 +0000109static raw_ostream& operator<<(raw_ostream &O,
Mike Stumpeb045ec2009-07-28 01:35:34 +0000110 const LowerSwitch::CaseVector &C) ATTRIBUTE_USED;
Mike Stump66ad89c2009-07-27 23:33:34 +0000111static raw_ostream& operator<<(raw_ostream &O,
Daniel Dunbar1cd1d982009-07-24 10:36:58 +0000112 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
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000124// switchConvert - Convert the switch statement into a binary lookup of
125// the case values. The function recursively builds this tree.
126//
127BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
128 Value* Val, BasicBlock* OrigBlock,
129 BasicBlock* Default)
130{
131 unsigned Size = End - Begin;
132
133 if (Size == 1)
134 return newLeafBlock(*Begin, Val, OrigBlock, Default);
135
136 unsigned Mid = Size / 2;
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000137 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greene0f4c9882010-01-05 01:26:45 +0000138 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000139 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greene0f4c9882010-01-05 01:26:45 +0000140 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000141
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000142 CaseRange& Pivot = *(Begin + Mid);
David Greene0f4c9882010-01-05 01:26:45 +0000143 DEBUG(dbgs() << "Pivot ==> "
Chris Lattner944fac72008-08-23 22:23:09 +0000144 << cast<ConstantInt>(Pivot.Low)->getValue() << " -"
Dan Gohmanf871ccb2009-03-23 15:57:19 +0000145 << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000146
147 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
148 OrigBlock, Default);
149 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
150 OrigBlock, Default);
151
152 // Create a new node that checks if the value is < pivot. Go to the
153 // left branch if it is and right branch if not.
154 Function* F = OrigBlock->getParent();
Owen Anderson1d0be152009-08-13 21:58:54 +0000155 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattner261cdfb2007-04-17 18:09:47 +0000156 Function::iterator FI = OrigBlock;
157 F->getBasicBlockList().insert(++FI, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000158
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000159 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson333c4002009-07-09 23:48:35 +0000160 Val, Pivot.Low, "Pivot");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000161 NewNode->getInstList().push_back(Comp);
Gabor Greif051a9502008-04-06 20:25:17 +0000162 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000163 return NewNode;
164}
165
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
170// is warranted.
171//
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000172BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000173 BasicBlock* OrigBlock,
174 BasicBlock* Default)
175{
176 Function* F = OrigBlock->getParent();
Owen Anderson1d0be152009-08-13 21:58:54 +0000177 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Chris Lattner261cdfb2007-04-17 18:09:47 +0000178 Function::iterator FI = OrigBlock;
179 F->getBasicBlockList().insert(++FI, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000180
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000181 // Emit comparison
182 ICmpInst* Comp = NULL;
183 if (Leaf.Low == Leaf.High) {
184 // Make the seteq instruction...
Owen Anderson333c4002009-07-09 23:48:35 +0000185 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
186 Leaf.Low, "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000187 } else {
188 // Make range comparison
189 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
190 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson333c4002009-07-09 23:48:35 +0000191 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
192 "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000193 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
194 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson333c4002009-07-09 23:48:35 +0000195 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
196 "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000197 } else {
198 // Emit V-Lo <=u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +0000199 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000200 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000201 Val->getName()+".off",
202 NewLeaf);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000203 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson333c4002009-07-09 23:48:35 +0000204 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
205 "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000206 }
207 }
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000208
209 // Make the conditional branch...
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000210 BasicBlock* Succ = Leaf.BB;
Gabor Greif051a9502008-04-06 20:25:17 +0000211 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000212
213 // If there were any PHI nodes in this successor, rewrite one entry
214 // from OrigBlock to come from NewLeaf.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000215 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
216 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000217 // Remove all but one incoming entries from the cluster
218 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
219 cast<ConstantInt>(Leaf.Low)->getSExtValue();
220 for (uint64_t j = 0; j < Range; ++j) {
221 PN->removeIncomingValue(OrigBlock);
222 }
223
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000224 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
225 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
226 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
227 }
228
229 return NewLeaf;
230}
231
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000232// Clusterify - Transform simple list of Cases into list of CaseRange's
233unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
234 unsigned numCmps = 0;
235
236 // Start with "simple" cases
237 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
238 Cases.push_back(CaseRange(SI->getSuccessorValue(i),
239 SI->getSuccessorValue(i),
240 SI->getSuccessor(i)));
Dan Gohman111c4f82007-11-02 22:24:01 +0000241 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000242
243 // Merge case into clusters
244 if (Cases.size()>=2)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000245 for (CaseItr I=Cases.begin(), J=llvm::next(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000246 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
247 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
248 BasicBlock* nextBB = J->BB;
249 BasicBlock* currentBB = I->BB;
250
251 // If the two neighboring cases go to the same destination, merge them
252 // into a single case.
253 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
254 I->High = J->High;
255 J = Cases.erase(J);
256 } else {
257 I = J++;
258 }
259 }
260
261 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
262 if (I->Low != I->High)
263 // A range counts double, since it requires two compares.
264 ++numCmps;
265 }
266
267 return numCmps;
268}
269
Chris Lattner14383482003-04-23 16:23:59 +0000270// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000271// of chained if-then insts in a balanced binary search.
Chris Lattner14383482003-04-23 16:23:59 +0000272//
273void LowerSwitch::processSwitchInst(SwitchInst *SI) {
274 BasicBlock *CurBlock = SI->getParent();
275 BasicBlock *OrigBlock = CurBlock;
276 Function *F = CurBlock->getParent();
277 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000278 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner14383482003-04-23 16:23:59 +0000279
Chris Lattner44bb5412003-08-23 22:54:34 +0000280 // If there is only the default destination, don't bother with the code below.
281 if (SI->getNumOperands() == 2) {
Gabor Greif051a9502008-04-06 20:25:17 +0000282 BranchInst::Create(SI->getDefaultDest(), CurBlock);
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000283 CurBlock->getInstList().erase(SI);
Chris Lattner44bb5412003-08-23 22:54:34 +0000284 return;
285 }
286
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000287 // Create a new, empty default block so that the new hierarchy of
288 // if-then statements go to this and the PHI nodes are happy.
Owen Anderson1d0be152009-08-13 21:58:54 +0000289 BasicBlock* NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000290 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000291
Gabor Greif051a9502008-04-06 20:25:17 +0000292 BranchInst::Create(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000293
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000294 // If there is an entry in any PHI nodes for the default edge, make sure
295 // to update them as well.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000296 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
297 PHINode *PN = cast<PHINode>(I);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000298 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
299 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
300 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000301 }
302
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000303 // Prepare cases vector.
304 CaseVector Cases;
305 unsigned numCmps = Clusterify(Cases, SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000306
David Greene0f4c9882010-01-05 01:26:45 +0000307 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Dan Gohman6c1980b2009-07-25 01:13:51 +0000308 << ". Total compares: " << numCmps << "\n");
David Greene0f4c9882010-01-05 01:26:45 +0000309 DEBUG(dbgs() << "Cases: " << Cases << "\n");
Mike Stump02efa782009-07-27 23:14:11 +0000310 (void)numCmps;
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000311
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000312 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
313 OrigBlock, NewDefault);
314
315 // Branch to our shiny new if-then stuff...
Gabor Greif051a9502008-04-06 20:25:17 +0000316 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000317
Chris Lattner14383482003-04-23 16:23:59 +0000318 // We are now done with the switch instruction, delete it.
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000319 CurBlock->getInstList().erase(SI);
Chris Lattner14383482003-04-23 16:23:59 +0000320}