blob: 8141049a8179fb4bb7e223637a2ff30ecec9ff91 [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 {
Hans Wennborgae9c9712015-01-23 20:43:51 +000035 struct IntRange {
36 int64_t Low, High;
37 };
38 // Return true iff R is covered by Ranges.
39 static bool IsInRanges(const IntRange &R,
40 const std::vector<IntRange> &Ranges) {
41 // Note: Ranges must be sorted, non-overlapping and non-adjacent.
42
43 // Find the first range whose High field is >= R.High,
44 // then check if the Low field is <= R.Low. If so, we
45 // have a Range that covers R.
46 auto I = std::lower_bound(
47 Ranges.begin(), Ranges.end(), R,
48 [](const IntRange &A, const IntRange &B) { return A.High < B.High; });
49 return I != Ranges.end() && I->Low <= R.Low;
50 }
51
Chris Lattner1b094a02003-04-23 16:23:59 +000052 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
Chris Lattnerb45de952010-08-18 02:41:56 +000053 /// instructions.
Nick Lewycky02d5f772009-10-25 06:33:48 +000054 class LowerSwitch : public FunctionPass {
Chris Lattnered922162003-10-07 18:46:23 +000055 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000056 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000057 LowerSwitch() : FunctionPass(ID) {
58 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
59 }
Devang Patel09f162c2007-05-01 21:15:47 +000060
Craig Topper3e4c6972014-03-05 09:10:37 +000061 bool runOnFunction(Function &F) override;
62
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anton Korobeynikovfb801512007-04-16 18:10:23 +000064 // This is a cluster of orthogonal Transforms
Chris Lattner4fe87d62006-05-09 04:13:41 +000065 AU.addPreserved<UnifyFunctionExitNodes>();
Chris Lattnere4cb4762006-05-17 21:05:27 +000066 AU.addPreservedID(LowerInvokePassID);
Chris Lattner4fe87d62006-05-09 04:13:41 +000067 }
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000068
69 struct CaseRange {
70 Constant* Low;
71 Constant* High;
72 BasicBlock* BB;
73
Hans Wennborg8c82fbc2015-02-05 16:50:27 +000074 CaseRange(Constant *low, Constant *high, BasicBlock *bb)
75 : Low(low), High(high), BB(bb) {}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000076 };
77
Jim Grosbachfff56632014-06-16 16:55:20 +000078 typedef std::vector<CaseRange> CaseVector;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000079 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnered922162003-10-07 18:46:23 +000080 private:
Chris Lattner1b094a02003-04-23 16:23:59 +000081 void processSwitchInst(SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000082
Jim Grosbachfff56632014-06-16 16:55:20 +000083 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
84 ConstantInt *LowerBound, ConstantInt *UpperBound,
Marcello Maggioni78035b12014-07-11 10:34:36 +000085 Value *Val, BasicBlock *Predecessor,
Hans Wennborgae9c9712015-01-23 20:43:51 +000086 BasicBlock *OrigBlock, BasicBlock *Default,
87 const std::vector<IntRange> &UnreachableRanges);
Jim Grosbachfff56632014-06-16 16:55:20 +000088 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
89 BasicBlock *Default);
90 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000091 };
Bob Wilsone4077362013-09-09 19:14:35 +000092
93 /// The comparison function for sorting the switch case values in the vector.
94 /// WARNING: Case ranges should be disjoint!
95 struct CaseCmp {
96 bool operator () (const LowerSwitch::CaseRange& C1,
97 const LowerSwitch::CaseRange& C2) {
98
99 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
100 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
101 return CI1->getValue().slt(CI2->getValue());
102 }
103 };
Chris Lattner1b094a02003-04-23 16:23:59 +0000104}
105
Dan Gohmand78c4002008-05-13 00:00:25 +0000106char LowerSwitch::ID = 0;
Owen Andersond31d82d2010-08-23 17:52:01 +0000107INITIALIZE_PASS(LowerSwitch, "lowerswitch",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000108 "Lower SwitchInst's to branches", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000109
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000110// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +0000111char &llvm::LowerSwitchID = LowerSwitch::ID;
Chris Lattner1b094a02003-04-23 16:23:59 +0000112// createLowerSwitchPass - Interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +0000113FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +0000114 return new LowerSwitch();
115}
116
117bool LowerSwitch::runOnFunction(Function &F) {
118 bool Changed = false;
119
120 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
121 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
122
123 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
124 Changed = true;
125 processSwitchInst(SI);
126 }
127 }
128
129 return Changed;
130}
131
Chris Lattnered922162003-10-07 18:46:23 +0000132// operator<< - Used for debugging purposes.
133//
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000134static raw_ostream& operator<<(raw_ostream &O,
Chandler Carruth88c54b82010-10-23 08:10:43 +0000135 const LowerSwitch::CaseVector &C)
136 LLVM_ATTRIBUTE_USED;
Mike Stump47987632009-07-27 23:33:34 +0000137static raw_ostream& operator<<(raw_ostream &O,
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000138 const LowerSwitch::CaseVector &C) {
Chris Lattnered922162003-10-07 18:46:23 +0000139 O << "[";
140
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000141 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattner49525f82004-01-09 06:02:20 +0000142 E = C.end(); B != E; ) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000143 O << *B->Low << " -" << *B->High;
Chris Lattnered922162003-10-07 18:46:23 +0000144 if (++B != E) O << ", ";
145 }
146
147 return O << "]";
148}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000149
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000150// \brief Update the first occurrence of the "switch statement" BB in the PHI
151// node with the "new" BB. The other occurrences will:
152//
153// 1) Be updated by subsequent calls to this function. Switch statements may
154// have more than one outcoming edge into the same BB if they all have the same
155// value. When the switch statement is converted these incoming edges are now
156// coming from multiple BBs.
157// 2) Removed if subsequent incoming values now share the same case, i.e.,
158// multiple outcome edges are condensed into one. This is necessary to keep the
159// number of phi values equal to the number of branches to SuccBB.
160static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
161 unsigned NumMergedCases) {
162 for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
163 I != IE; ++I) {
Marcello Maggioni78035b12014-07-11 10:34:36 +0000164 PHINode *PN = cast<PHINode>(I);
165
Juergen Ributzkad4417252014-11-10 21:05:27 +0000166 // Only update the first occurence.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000167 unsigned Idx = 0, E = PN->getNumIncomingValues();
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000168 unsigned LocalNumMergedCases = NumMergedCases;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000169 for (; Idx != E; ++Idx) {
Juergen Ributzkad4417252014-11-10 21:05:27 +0000170 if (PN->getIncomingBlock(Idx) == OrigBB) {
171 PN->setIncomingBlock(Idx, NewBB);
172 break;
173 }
Marcello Maggioni78035b12014-07-11 10:34:36 +0000174 }
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000175
176 // Remove additional occurences coming from condensed cases and keep the
177 // number of incoming values equal to the number of branches to SuccBB.
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000178 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000179 if (PN->getIncomingBlock(Idx) == OrigBB) {
180 PN->removeIncomingValue(Idx);
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000181 LocalNumMergedCases--;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000182 }
Marcello Maggioni78035b12014-07-11 10:34:36 +0000183 }
184}
185
Chris Lattnered922162003-10-07 18:46:23 +0000186// switchConvert - Convert the switch statement into a binary lookup of
187// the case values. The function recursively builds this tree.
Jim Grosbachfff56632014-06-16 16:55:20 +0000188// LowerBound and UpperBound are used to keep track of the bounds for Val
189// that have already been checked by a block emitted by one of the previous
190// calls to switchConvert in the call stack.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000191BasicBlock *
192LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
193 ConstantInt *UpperBound, Value *Val,
194 BasicBlock *Predecessor, BasicBlock *OrigBlock,
195 BasicBlock *Default,
196 const std::vector<IntRange> &UnreachableRanges) {
Chris Lattnered922162003-10-07 18:46:23 +0000197 unsigned Size = End - Begin;
198
Jim Grosbachfff56632014-06-16 16:55:20 +0000199 if (Size == 1) {
200 // Check if the Case Range is perfectly squeezed in between
201 // already checked Upper and Lower bounds. If it is then we can avoid
202 // emitting the code that checks if the value actually falls in the range
203 // because the bounds already tell us so.
204 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000205 unsigned NumMergedCases = 0;
206 if (LowerBound && UpperBound)
207 NumMergedCases =
208 UpperBound->getSExtValue() - LowerBound->getSExtValue();
209 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
Jim Grosbachfff56632014-06-16 16:55:20 +0000210 return Begin->BB;
211 }
Chris Lattnered922162003-10-07 18:46:23 +0000212 return newLeafBlock(*Begin, Val, OrigBlock, Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000213 }
Chris Lattnered922162003-10-07 18:46:23 +0000214
215 unsigned Mid = Size / 2;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000216 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greene50c54232010-01-05 01:26:45 +0000217 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000218 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greene50c54232010-01-05 01:26:45 +0000219 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000220
Jim Grosbachfff56632014-06-16 16:55:20 +0000221 CaseRange &Pivot = *(Begin + Mid);
222 DEBUG(dbgs() << "Pivot ==> "
223 << cast<ConstantInt>(Pivot.Low)->getValue()
224 << " -" << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000225
Jim Grosbachfff56632014-06-16 16:55:20 +0000226 // NewLowerBound here should never be the integer minimal value.
227 // This is because it is computed from a case range that is never
228 // the smallest, so there is always a case range that has at least
229 // a smaller value.
230 ConstantInt *NewLowerBound = cast<ConstantInt>(Pivot.Low);
Jim Grosbachfff56632014-06-16 16:55:20 +0000231
Hans Wennborgae9c9712015-01-23 20:43:51 +0000232 // Because NewLowerBound is never the smallest representable integer
233 // it is safe here to subtract one.
234 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
235 NewLowerBound->getValue() - 1);
236
237 if (!UnreachableRanges.empty()) {
238 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
239 int64_t GapLow = cast<ConstantInt>(LHS.back().High)->getSExtValue() + 1;
240 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
241 IntRange Gap = { GapLow, GapHigh };
242 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
243 NewUpperBound = cast<ConstantInt>(LHS.back().High);
Jim Grosbachfff56632014-06-16 16:55:20 +0000244 }
245
246 DEBUG(dbgs() << "LHS Bounds ==> ";
247 if (LowerBound) {
248 dbgs() << cast<ConstantInt>(LowerBound)->getSExtValue();
249 } else {
250 dbgs() << "NONE";
251 }
252 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
253 dbgs() << "RHS Bounds ==> ";
254 dbgs() << NewLowerBound->getSExtValue() << " - ";
255 if (UpperBound) {
256 dbgs() << cast<ConstantInt>(UpperBound)->getSExtValue() << "\n";
257 } else {
258 dbgs() << "NONE\n";
259 });
260
Chris Lattnered922162003-10-07 18:46:23 +0000261 // Create a new node that checks if the value is < pivot. Go to the
262 // left branch if it is and right branch if not.
263 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000264 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattnered922162003-10-07 18:46:23 +0000265
Bob Wilsone4077362013-09-09 19:14:35 +0000266 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000267 Val, Pivot.Low, "Pivot");
Marcello Maggioni78035b12014-07-11 10:34:36 +0000268
269 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
270 NewUpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000271 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000272 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
273 UpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000274 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000275
276 Function::iterator FI = OrigBlock;
277 F->getBasicBlockList().insert(++FI, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000278 NewNode->getInstList().push_back(Comp);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000279
Gabor Greife9ecc682008-04-06 20:25:17 +0000280 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000281 return NewNode;
282}
283
284// newLeafBlock - Create a new leaf block for the binary lookup tree. It
285// checks if the switch's value == the case's value. If not, then it
286// jumps to the default branch. At this point in the tree, the value
287// can't be another valid case value, so the jump to the "default" branch
288// is warranted.
289//
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000290BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnered922162003-10-07 18:46:23 +0000291 BasicBlock* OrigBlock,
292 BasicBlock* Default)
293{
294 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000295 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Chris Lattner233f97a2007-04-17 18:09:47 +0000296 Function::iterator FI = OrigBlock;
297 F->getBasicBlockList().insert(++FI, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000298
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000299 // Emit comparison
Craig Topperf40110f2014-04-25 05:29:35 +0000300 ICmpInst* Comp = nullptr;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000301 if (Leaf.Low == Leaf.High) {
302 // Make the seteq instruction...
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000303 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
304 Leaf.Low, "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000305 } else {
306 // Make range comparison
307 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
308 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000309 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
310 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000311 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
312 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000313 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
314 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000315 } else {
316 // Emit V-Lo <=u Hi-Lo
Owen Anderson487375e2009-07-29 18:55:55 +0000317 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000318 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000319 Val->getName()+".off",
320 NewLeaf);
Owen Anderson487375e2009-07-29 18:55:55 +0000321 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000322 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
323 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000324 }
325 }
Chris Lattnered922162003-10-07 18:46:23 +0000326
327 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000328 BasicBlock* Succ = Leaf.BB;
Gabor Greife9ecc682008-04-06 20:25:17 +0000329 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000330
331 // If there were any PHI nodes in this successor, rewrite one entry
332 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000333 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
334 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000335 // Remove all but one incoming entries from the cluster
336 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
337 cast<ConstantInt>(Leaf.Low)->getSExtValue();
338 for (uint64_t j = 0; j < Range; ++j) {
339 PN->removeIncomingValue(OrigBlock);
340 }
341
Chris Lattnered922162003-10-07 18:46:23 +0000342 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
343 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
344 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
345 }
346
347 return NewLeaf;
348}
349
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000350// Clusterify - Transform simple list of Cases into list of CaseRange's
351unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Bob Wilsone4077362013-09-09 19:14:35 +0000352 unsigned numCmps = 0;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000353
354 // Start with "simple" cases
Bob Wilsone4077362013-09-09 19:14:35 +0000355 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
356 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
357 i.getCaseSuccessor()));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000358
Bob Wilsone4077362013-09-09 19:14:35 +0000359 std::sort(Cases.begin(), Cases.end(), CaseCmp());
360
361 // Merge case into clusters
362 if (Cases.size()>=2)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000363 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
364 J != Cases.end();) {
Bob Wilsone4077362013-09-09 19:14:35 +0000365 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
366 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
367 BasicBlock* nextBB = J->BB;
368 BasicBlock* currentBB = I->BB;
369
370 // If the two neighboring cases go to the same destination, merge them
371 // into a single case.
372 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
373 I->High = J->High;
374 J = Cases.erase(J);
375 } else {
376 I = J++;
377 }
378 }
379
380 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
381 if (I->Low != I->High)
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000382 // A range counts double, since it requires two compares.
383 ++numCmps;
384 }
385
Bob Wilsone4077362013-09-09 19:14:35 +0000386 return numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000387}
388
Chris Lattner1b094a02003-04-23 16:23:59 +0000389// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnered922162003-10-07 18:46:23 +0000390// of chained if-then insts in a balanced binary search.
Chris Lattner1b094a02003-04-23 16:23:59 +0000391//
392void LowerSwitch::processSwitchInst(SwitchInst *SI) {
393 BasicBlock *CurBlock = SI->getParent();
394 BasicBlock *OrigBlock = CurBlock;
395 Function *F = CurBlock->getParent();
Eli Friedman95031ed2011-09-29 20:21:17 +0000396 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000397 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000398
Hans Wennborgae9c9712015-01-23 20:43:51 +0000399 // If there is only the default destination, just branch.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000400 if (!SI->getNumCases()) {
Hans Wennborgae9c9712015-01-23 20:43:51 +0000401 BranchInst::Create(Default, CurBlock);
402 SI->eraseFromParent();
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000403 return;
404 }
405
Hans Wennborgae9c9712015-01-23 20:43:51 +0000406 // Prepare cases vector.
407 CaseVector Cases;
408 unsigned numCmps = Clusterify(Cases, SI);
409 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
410 << ". Total compares: " << numCmps << "\n");
411 DEBUG(dbgs() << "Cases: " << Cases << "\n");
412 (void)numCmps;
413
414 ConstantInt *LowerBound = nullptr;
415 ConstantInt *UpperBound = nullptr;
416 std::vector<IntRange> UnreachableRanges;
417
418 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
419 // Make the bounds tightly fitted around the case value range, becase we
420 // know that the value passed to the switch must be exactly one of the case
421 // values.
422 assert(!Cases.empty());
423 LowerBound = cast<ConstantInt>(Cases.front().Low);
424 UpperBound = cast<ConstantInt>(Cases.back().High);
425
426 DenseMap<BasicBlock *, unsigned> Popularity;
427 unsigned MaxPop = 0;
428 BasicBlock *PopSucc = nullptr;
429
430 IntRange R = { INT64_MIN, INT64_MAX };
431 UnreachableRanges.push_back(R);
432 for (const auto &I : Cases) {
433 int64_t Low = cast<ConstantInt>(I.Low)->getSExtValue();
434 int64_t High = cast<ConstantInt>(I.High)->getSExtValue();
435
436 IntRange &LastRange = UnreachableRanges.back();
437 if (LastRange.Low == Low) {
438 // There is nothing left of the previous range.
439 UnreachableRanges.pop_back();
440 } else {
441 // Terminate the previous range.
442 assert(Low > LastRange.Low);
443 LastRange.High = Low - 1;
444 }
445 if (High != INT64_MAX) {
446 IntRange R = { High + 1, INT64_MAX };
447 UnreachableRanges.push_back(R);
448 }
449
450 // Count popularity.
451 int64_t N = High - Low + 1;
452 unsigned &Pop = Popularity[I.BB];
453 if ((Pop += N) > MaxPop) {
454 MaxPop = Pop;
455 PopSucc = I.BB;
456 }
457 }
458#ifndef NDEBUG
459 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
460 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
461 I != E; ++I) {
462 assert(I->Low <= I->High);
463 auto Next = I + 1;
464 if (Next != E) {
465 assert(Next->Low > I->High);
466 }
467 }
468#endif
469
470 // Use the most popular block as the new default, reducing the number of
471 // cases.
472 assert(MaxPop > 0 && PopSucc);
473 Default = PopSucc;
474 for (CaseItr I = Cases.begin(); I != Cases.end();) {
475 if (I->BB == PopSucc)
476 I = Cases.erase(I);
477 else
478 ++I;
479 }
480
481 // If there are no cases left, just branch.
482 if (Cases.empty()) {
483 BranchInst::Create(Default, CurBlock);
484 SI->eraseFromParent();
485 return;
486 }
487 }
488
Chris Lattnered922162003-10-07 18:46:23 +0000489 // Create a new, empty default block so that the new hierarchy of
490 // if-then statements go to this and the PHI nodes are happy.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000491 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
492 F->getBasicBlockList().insert(Default, NewDefault);
493 BranchInst::Create(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000494
Chris Lattnered922162003-10-07 18:46:23 +0000495 // If there is an entry in any PHI nodes for the default edge, make sure
496 // to update them as well.
Reid Spencer66149462004-09-15 17:06:42 +0000497 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
498 PHINode *PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000499 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
500 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
501 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000502 }
503
Jim Grosbachfff56632014-06-16 16:55:20 +0000504 BasicBlock *SwitchBlock =
505 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000506 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
Chris Lattnered922162003-10-07 18:46:23 +0000507
508 // Branch to our shiny new if-then stuff...
Gabor Greife9ecc682008-04-06 20:25:17 +0000509 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000510
Chris Lattner1b094a02003-04-23 16:23:59 +0000511 // We are now done with the switch instruction, delete it.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000512 BasicBlock *OldDefault = SI->getDefaultDest();
Chris Lattnerb6865952004-03-14 04:14:31 +0000513 CurBlock->getInstList().erase(SI);
Jim Grosbachfff56632014-06-16 16:55:20 +0000514
Hans Wennborgae9c9712015-01-23 20:43:51 +0000515 // If the Default block has no more predecessors just remove it.
516 if (pred_begin(OldDefault) == pred_end(OldDefault))
517 DeleteDeadBlock(OldDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000518}