blob: d6e5bb626805e9df2df83da8aa181e9d129a78af [file] [log] [blame]
Chris Lattner1b094a02003-04-23 16:23:59 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner1b094a02003-04-23 16:23:59 +00009//
Gordon Henriksend5687672007-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 Lattner1b094a02003-04-23 16:23:59 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/Scalar.h"
Jim Grosbachfff56632014-06-16 16:55:20 +000017#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/LLVMContext.h"
Jim Grosbachfff56632014-06-16 16:55:20 +000023#include "llvm/IR/CFG.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000024#include "llvm/Pass.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000025#include "llvm/Support/Compiler.h"
Nick Lewycky974e12b2009-10-25 06:57:41 +000026#include "llvm/Support/Debug.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000027#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000029#include <algorithm>
Chris Lattner49525f82004-01-09 06:02:20 +000030using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000031
Chandler Carruthe96dd892014-04-21 22:55:11 +000032#define DEBUG_TYPE "lower-switch"
33
Chris Lattner1b094a02003-04-23 16:23:59 +000034namespace {
Chris Lattner1b094a02003-04-23 16:23:59 +000035 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
Chris Lattnerb45de952010-08-18 02:41:56 +000036 /// instructions.
Nick Lewycky02d5f772009-10-25 06:33:48 +000037 class LowerSwitch : public FunctionPass {
Chris Lattnered922162003-10-07 18:46:23 +000038 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000039 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000040 LowerSwitch() : FunctionPass(ID) {
41 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
42 }
Devang Patel09f162c2007-05-01 21:15:47 +000043
Craig Topper3e4c6972014-03-05 09:10:37 +000044 bool runOnFunction(Function &F) override;
45
46 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anton Korobeynikovfb801512007-04-16 18:10:23 +000047 // This is a cluster of orthogonal Transforms
Chris Lattner4fe87d62006-05-09 04:13:41 +000048 AU.addPreserved<UnifyFunctionExitNodes>();
Dan Gohman0f7892b2010-08-06 21:48:06 +000049 AU.addPreserved("mem2reg");
Chris Lattnere4cb4762006-05-17 21:05:27 +000050 AU.addPreservedID(LowerInvokePassID);
Chris Lattner4fe87d62006-05-09 04:13:41 +000051 }
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000052
53 struct CaseRange {
54 Constant* Low;
55 Constant* High;
56 BasicBlock* BB;
57
Craig Topperf40110f2014-04-25 05:29:35 +000058 CaseRange(Constant *low = nullptr, Constant *high = nullptr,
59 BasicBlock *bb = nullptr) :
Jeff Cohen00227412007-03-12 17:56:27 +000060 Low(low), High(high), BB(bb) { }
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000061 };
62
Jim Grosbachfff56632014-06-16 16:55:20 +000063 typedef std::vector<CaseRange> CaseVector;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000064 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnered922162003-10-07 18:46:23 +000065 private:
Chris Lattner1b094a02003-04-23 16:23:59 +000066 void processSwitchInst(SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000067
Jim Grosbachfff56632014-06-16 16:55:20 +000068 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
69 ConstantInt *LowerBound, ConstantInt *UpperBound,
Marcello Maggioni78035b12014-07-11 10:34:36 +000070 Value *Val, BasicBlock *Predecessor,
71 BasicBlock *OrigBlock, BasicBlock *Default);
Jim Grosbachfff56632014-06-16 16:55:20 +000072 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
73 BasicBlock *Default);
74 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000075 };
Bob Wilsone4077362013-09-09 19:14:35 +000076
77 /// The comparison function for sorting the switch case values in the vector.
78 /// WARNING: Case ranges should be disjoint!
79 struct CaseCmp {
80 bool operator () (const LowerSwitch::CaseRange& C1,
81 const LowerSwitch::CaseRange& C2) {
82
83 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
84 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
85 return CI1->getValue().slt(CI2->getValue());
86 }
87 };
Chris Lattner1b094a02003-04-23 16:23:59 +000088}
89
Dan Gohmand78c4002008-05-13 00:00:25 +000090char LowerSwitch::ID = 0;
Owen Andersond31d82d2010-08-23 17:52:01 +000091INITIALIZE_PASS(LowerSwitch, "lowerswitch",
Owen Andersondf7a4f22010-10-07 22:25:06 +000092 "Lower SwitchInst's to branches", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000093
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000094// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +000095char &llvm::LowerSwitchID = LowerSwitch::ID;
Chris Lattner1b094a02003-04-23 16:23:59 +000096// createLowerSwitchPass - Interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +000097FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +000098 return new LowerSwitch();
99}
100
101bool LowerSwitch::runOnFunction(Function &F) {
102 bool Changed = false;
103
104 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
105 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
106
107 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
108 Changed = true;
109 processSwitchInst(SI);
110 }
111 }
112
113 return Changed;
114}
115
Chris Lattnered922162003-10-07 18:46:23 +0000116// operator<< - Used for debugging purposes.
117//
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000118static raw_ostream& operator<<(raw_ostream &O,
Chandler Carruth88c54b82010-10-23 08:10:43 +0000119 const LowerSwitch::CaseVector &C)
120 LLVM_ATTRIBUTE_USED;
Mike Stump47987632009-07-27 23:33:34 +0000121static raw_ostream& operator<<(raw_ostream &O,
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000122 const LowerSwitch::CaseVector &C) {
Chris Lattnered922162003-10-07 18:46:23 +0000123 O << "[";
124
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000125 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattner49525f82004-01-09 06:02:20 +0000126 E = C.end(); B != E; ) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000127 O << *B->Low << " -" << *B->High;
Chris Lattnered922162003-10-07 18:46:23 +0000128 if (++B != E) O << ", ";
129 }
130
131 return O << "]";
132}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000133
Marcello Maggioni78035b12014-07-11 10:34:36 +0000134static void fixPhis(BasicBlock *Succ,
135 BasicBlock *OrigBlock,
136 BasicBlock *NewNode) {
137 for (BasicBlock::iterator I = Succ->begin(),
138 E = Succ->getFirstNonPHI();
139 I != E; ++I) {
140 PHINode *PN = cast<PHINode>(I);
141
142 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
143 if (PN->getIncomingBlock(I) == OrigBlock)
144 PN->setIncomingBlock(I, NewNode);
145 }
146 }
147}
148
Chris Lattnered922162003-10-07 18:46:23 +0000149// switchConvert - Convert the switch statement into a binary lookup of
150// the case values. The function recursively builds this tree.
Jim Grosbachfff56632014-06-16 16:55:20 +0000151// LowerBound and UpperBound are used to keep track of the bounds for Val
152// that have already been checked by a block emitted by one of the previous
153// calls to switchConvert in the call stack.
154BasicBlock *LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
155 ConstantInt *LowerBound,
156 ConstantInt *UpperBound, Value *Val,
Marcello Maggioni78035b12014-07-11 10:34:36 +0000157 BasicBlock *Predecessor,
Jim Grosbachfff56632014-06-16 16:55:20 +0000158 BasicBlock *OrigBlock,
159 BasicBlock *Default) {
Chris Lattnered922162003-10-07 18:46:23 +0000160 unsigned Size = End - Begin;
161
Jim Grosbachfff56632014-06-16 16:55:20 +0000162 if (Size == 1) {
163 // Check if the Case Range is perfectly squeezed in between
164 // already checked Upper and Lower bounds. If it is then we can avoid
165 // emitting the code that checks if the value actually falls in the range
166 // because the bounds already tell us so.
167 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
Marcello Maggioni78035b12014-07-11 10:34:36 +0000168 fixPhis(Begin->BB, OrigBlock, Predecessor);
Jim Grosbachfff56632014-06-16 16:55:20 +0000169 return Begin->BB;
170 }
Chris Lattnered922162003-10-07 18:46:23 +0000171 return newLeafBlock(*Begin, Val, OrigBlock, Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000172 }
Chris Lattnered922162003-10-07 18:46:23 +0000173
174 unsigned Mid = Size / 2;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000175 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greene50c54232010-01-05 01:26:45 +0000176 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000177 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greene50c54232010-01-05 01:26:45 +0000178 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000179
Jim Grosbachfff56632014-06-16 16:55:20 +0000180 CaseRange &Pivot = *(Begin + Mid);
181 DEBUG(dbgs() << "Pivot ==> "
182 << cast<ConstantInt>(Pivot.Low)->getValue()
183 << " -" << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000184
Jim Grosbachfff56632014-06-16 16:55:20 +0000185 // NewLowerBound here should never be the integer minimal value.
186 // This is because it is computed from a case range that is never
187 // the smallest, so there is always a case range that has at least
188 // a smaller value.
189 ConstantInt *NewLowerBound = cast<ConstantInt>(Pivot.Low);
190 ConstantInt *NewUpperBound;
191
192 // If we don't have a Default block then it means that we can never
193 // have a value outside of a case range, so set the UpperBound to the highest
194 // value in the LHS part of the case ranges.
195 if (Default != nullptr) {
196 // Because NewLowerBound is never the smallest representable integer
197 // it is safe here to subtract one.
198 NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
199 NewLowerBound->getValue() - 1);
200 } else {
201 CaseItr LastLHS = LHS.begin() + LHS.size() - 1;
202 NewUpperBound = cast<ConstantInt>(LastLHS->High);
203 }
204
205 DEBUG(dbgs() << "LHS Bounds ==> ";
206 if (LowerBound) {
207 dbgs() << cast<ConstantInt>(LowerBound)->getSExtValue();
208 } else {
209 dbgs() << "NONE";
210 }
211 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
212 dbgs() << "RHS Bounds ==> ";
213 dbgs() << NewLowerBound->getSExtValue() << " - ";
214 if (UpperBound) {
215 dbgs() << cast<ConstantInt>(UpperBound)->getSExtValue() << "\n";
216 } else {
217 dbgs() << "NONE\n";
218 });
219
Chris Lattnered922162003-10-07 18:46:23 +0000220 // Create a new node that checks if the value is < pivot. Go to the
221 // left branch if it is and right branch if not.
222 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000223 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattnered922162003-10-07 18:46:23 +0000224
Bob Wilsone4077362013-09-09 19:14:35 +0000225 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000226 Val, Pivot.Low, "Pivot");
Marcello Maggioni78035b12014-07-11 10:34:36 +0000227
228 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
229 NewUpperBound, Val, NewNode, OrigBlock,
230 Default);
231 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
232 UpperBound, Val, NewNode, OrigBlock,
233 Default);
234
235 Function::iterator FI = OrigBlock;
236 F->getBasicBlockList().insert(++FI, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000237 NewNode->getInstList().push_back(Comp);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000238
Gabor Greife9ecc682008-04-06 20:25:17 +0000239 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000240 return NewNode;
241}
242
243// newLeafBlock - Create a new leaf block for the binary lookup tree. It
244// checks if the switch's value == the case's value. If not, then it
245// jumps to the default branch. At this point in the tree, the value
246// can't be another valid case value, so the jump to the "default" branch
247// is warranted.
248//
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000249BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnered922162003-10-07 18:46:23 +0000250 BasicBlock* OrigBlock,
251 BasicBlock* Default)
252{
253 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000254 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Chris Lattner233f97a2007-04-17 18:09:47 +0000255 Function::iterator FI = OrigBlock;
256 F->getBasicBlockList().insert(++FI, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000257
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000258 // Emit comparison
Craig Topperf40110f2014-04-25 05:29:35 +0000259 ICmpInst* Comp = nullptr;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000260 if (Leaf.Low == Leaf.High) {
261 // Make the seteq instruction...
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000262 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
263 Leaf.Low, "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000264 } else {
265 // Make range comparison
266 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
267 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000268 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
269 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000270 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
271 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000272 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
273 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000274 } else {
275 // Emit V-Lo <=u Hi-Lo
Owen Anderson487375e2009-07-29 18:55:55 +0000276 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000277 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000278 Val->getName()+".off",
279 NewLeaf);
Owen Anderson487375e2009-07-29 18:55:55 +0000280 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000281 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
282 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000283 }
284 }
Chris Lattnered922162003-10-07 18:46:23 +0000285
286 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000287 BasicBlock* Succ = Leaf.BB;
Gabor Greife9ecc682008-04-06 20:25:17 +0000288 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000289
290 // If there were any PHI nodes in this successor, rewrite one entry
291 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000292 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
293 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000294 // Remove all but one incoming entries from the cluster
295 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
296 cast<ConstantInt>(Leaf.Low)->getSExtValue();
297 for (uint64_t j = 0; j < Range; ++j) {
298 PN->removeIncomingValue(OrigBlock);
299 }
300
Chris Lattnered922162003-10-07 18:46:23 +0000301 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
302 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
303 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
304 }
305
306 return NewLeaf;
307}
308
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000309// Clusterify - Transform simple list of Cases into list of CaseRange's
310unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Bob Wilsone4077362013-09-09 19:14:35 +0000311 unsigned numCmps = 0;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000312
313 // Start with "simple" cases
Bob Wilsone4077362013-09-09 19:14:35 +0000314 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
315 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
316 i.getCaseSuccessor()));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000317
Bob Wilsone4077362013-09-09 19:14:35 +0000318 std::sort(Cases.begin(), Cases.end(), CaseCmp());
319
320 // Merge case into clusters
321 if (Cases.size()>=2)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000322 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
323 J != Cases.end();) {
Bob Wilsone4077362013-09-09 19:14:35 +0000324 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
325 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
326 BasicBlock* nextBB = J->BB;
327 BasicBlock* currentBB = I->BB;
328
329 // If the two neighboring cases go to the same destination, merge them
330 // into a single case.
331 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
332 I->High = J->High;
333 J = Cases.erase(J);
334 } else {
335 I = J++;
336 }
337 }
338
339 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
340 if (I->Low != I->High)
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000341 // A range counts double, since it requires two compares.
342 ++numCmps;
343 }
344
Bob Wilsone4077362013-09-09 19:14:35 +0000345 return numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000346}
347
Chris Lattner1b094a02003-04-23 16:23:59 +0000348// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnered922162003-10-07 18:46:23 +0000349// of chained if-then insts in a balanced binary search.
Chris Lattner1b094a02003-04-23 16:23:59 +0000350//
351void LowerSwitch::processSwitchInst(SwitchInst *SI) {
352 BasicBlock *CurBlock = SI->getParent();
353 BasicBlock *OrigBlock = CurBlock;
354 Function *F = CurBlock->getParent();
Eli Friedman95031ed2011-09-29 20:21:17 +0000355 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000356 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000357
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000358 // If there is only the default destination, don't bother with the code below.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000359 if (!SI->getNumCases()) {
Gabor Greife9ecc682008-04-06 20:25:17 +0000360 BranchInst::Create(SI->getDefaultDest(), CurBlock);
Chris Lattnerb6865952004-03-14 04:14:31 +0000361 CurBlock->getInstList().erase(SI);
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000362 return;
363 }
364
Jim Grosbachfff56632014-06-16 16:55:20 +0000365 const bool DefaultIsUnreachable =
366 Default->size() == 1 && isa<UnreachableInst>(Default->getTerminator());
Chris Lattnered922162003-10-07 18:46:23 +0000367 // Create a new, empty default block so that the new hierarchy of
368 // if-then statements go to this and the PHI nodes are happy.
Jim Grosbachfff56632014-06-16 16:55:20 +0000369 // if the default block is set as an unreachable we avoid creating one
370 // because will never be a valid target.
371 BasicBlock *NewDefault = nullptr;
372 if (!DefaultIsUnreachable) {
373 NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
374 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000375
Jim Grosbachfff56632014-06-16 16:55:20 +0000376 BranchInst::Create(Default, NewDefault);
377 }
Chris Lattnered922162003-10-07 18:46:23 +0000378 // If there is an entry in any PHI nodes for the default edge, make sure
379 // to update them as well.
Reid Spencer66149462004-09-15 17:06:42 +0000380 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
381 PHINode *PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000382 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
383 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
384 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000385 }
386
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000387 // Prepare cases vector.
388 CaseVector Cases;
389 unsigned numCmps = Clusterify(Cases, SI);
Chris Lattnered922162003-10-07 18:46:23 +0000390
David Greene50c54232010-01-05 01:26:45 +0000391 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Dan Gohman29f2baf2009-07-25 01:13:51 +0000392 << ". Total compares: " << numCmps << "\n");
David Greene50c54232010-01-05 01:26:45 +0000393 DEBUG(dbgs() << "Cases: " << Cases << "\n");
Mike Stumpd934cc02009-07-27 23:14:11 +0000394 (void)numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000395
Jim Grosbachfff56632014-06-16 16:55:20 +0000396 ConstantInt *UpperBound = nullptr;
397 ConstantInt *LowerBound = nullptr;
398
399 // Optimize the condition where Default is an unreachable block. In this case
400 // we can make the bounds tightly fitted around the case value ranges,
401 // because we know that the value passed to the switch should always be
402 // exactly one of the case values.
403 if (DefaultIsUnreachable) {
404 CaseItr LastCase = Cases.begin() + Cases.size() - 1;
405 UpperBound = cast<ConstantInt>(LastCase->High);
406 LowerBound = cast<ConstantInt>(Cases.begin()->Low);
407 }
408 BasicBlock *SwitchBlock =
409 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
Marcello Maggioni78035b12014-07-11 10:34:36 +0000410 OrigBlock, OrigBlock, NewDefault);
Chris Lattnered922162003-10-07 18:46:23 +0000411
412 // Branch to our shiny new if-then stuff...
Gabor Greife9ecc682008-04-06 20:25:17 +0000413 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000414
Chris Lattner1b094a02003-04-23 16:23:59 +0000415 // We are now done with the switch instruction, delete it.
Chris Lattnerb6865952004-03-14 04:14:31 +0000416 CurBlock->getInstList().erase(SI);
Jim Grosbachfff56632014-06-16 16:55:20 +0000417
418 pred_iterator PI = pred_begin(Default), E = pred_end(Default);
419 // If the Default block has no more predecessors just remove it
420 if (PI == E) {
421 DeleteDeadBlock(Default);
422 }
Chris Lattner1b094a02003-04-23 16:23:59 +0000423}