blob: 3b447098af118c4460d3e86ed32eec36fc098ab8 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000018#include "llvm/IR/CFG.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"
Chris Lattner1b094a02003-04-23 16:23:59 +000023#include "llvm/Pass.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000024#include "llvm/Support/Compiler.h"
Nick Lewycky974e12b2009-10-25 06:57:41 +000025#include "llvm/Support/Debug.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000026#include "llvm/Support/raw_ostream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.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 {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000070 ConstantInt* Low;
71 ConstantInt* High;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000072 BasicBlock* BB;
73
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000074 CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
Hans Wennborg8c82fbc2015-02-05 16:50:27 +000075 : 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 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000104}
Chris Lattner1b094a02003-04-23 16:23:59 +0000105
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
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000166 // Only update the first occurrence.
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
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000176 // Remove additional occurrences coming from condensed cases and keep the
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000177 // number of incoming values equal to the number of branches to SuccBB.
Michael Liao24fcae82015-03-17 18:03:10 +0000178 SmallVector<unsigned, 8> Indices;
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000179 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000180 if (PN->getIncomingBlock(Idx) == OrigBB) {
Michael Liao24fcae82015-03-17 18:03:10 +0000181 Indices.push_back(Idx);
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000182 LocalNumMergedCases--;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000183 }
Michael Liao24fcae82015-03-17 18:03:10 +0000184 // Remove incoming values in the reverse order to prevent invalidating
185 // *successive* index.
186 for (auto III = Indices.rbegin(), IIE = Indices.rend(); III != IIE; ++III)
187 PN->removeIncomingValue(*III);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000188 }
189}
190
Chris Lattnered922162003-10-07 18:46:23 +0000191// switchConvert - Convert the switch statement into a binary lookup of
192// the case values. The function recursively builds this tree.
Jim Grosbachfff56632014-06-16 16:55:20 +0000193// LowerBound and UpperBound are used to keep track of the bounds for Val
194// that have already been checked by a block emitted by one of the previous
195// calls to switchConvert in the call stack.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000196BasicBlock *
197LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
198 ConstantInt *UpperBound, Value *Val,
199 BasicBlock *Predecessor, BasicBlock *OrigBlock,
200 BasicBlock *Default,
201 const std::vector<IntRange> &UnreachableRanges) {
Chris Lattnered922162003-10-07 18:46:23 +0000202 unsigned Size = End - Begin;
203
Jim Grosbachfff56632014-06-16 16:55:20 +0000204 if (Size == 1) {
205 // Check if the Case Range is perfectly squeezed in between
206 // already checked Upper and Lower bounds. If it is then we can avoid
207 // emitting the code that checks if the value actually falls in the range
208 // because the bounds already tell us so.
209 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000210 unsigned NumMergedCases = 0;
211 if (LowerBound && UpperBound)
212 NumMergedCases =
213 UpperBound->getSExtValue() - LowerBound->getSExtValue();
214 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
Jim Grosbachfff56632014-06-16 16:55:20 +0000215 return Begin->BB;
216 }
Chris Lattnered922162003-10-07 18:46:23 +0000217 return newLeafBlock(*Begin, Val, OrigBlock, Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000218 }
Chris Lattnered922162003-10-07 18:46:23 +0000219
220 unsigned Mid = Size / 2;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000221 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greene50c54232010-01-05 01:26:45 +0000222 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000223 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greene50c54232010-01-05 01:26:45 +0000224 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000225
Jim Grosbachfff56632014-06-16 16:55:20 +0000226 CaseRange &Pivot = *(Begin + Mid);
227 DEBUG(dbgs() << "Pivot ==> "
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000228 << Pivot.Low->getValue()
229 << " -" << Pivot.High->getValue() << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000230
Jim Grosbachfff56632014-06-16 16:55:20 +0000231 // NewLowerBound here should never be the integer minimal value.
232 // This is because it is computed from a case range that is never
233 // the smallest, so there is always a case range that has at least
234 // a smaller value.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000235 ConstantInt *NewLowerBound = Pivot.Low;
Jim Grosbachfff56632014-06-16 16:55:20 +0000236
Hans Wennborgae9c9712015-01-23 20:43:51 +0000237 // Because NewLowerBound is never the smallest representable integer
238 // it is safe here to subtract one.
239 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
240 NewLowerBound->getValue() - 1);
241
242 if (!UnreachableRanges.empty()) {
243 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000244 int64_t GapLow = LHS.back().High->getSExtValue() + 1;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000245 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
246 IntRange Gap = { GapLow, GapHigh };
247 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000248 NewUpperBound = LHS.back().High;
Jim Grosbachfff56632014-06-16 16:55:20 +0000249 }
250
251 DEBUG(dbgs() << "LHS Bounds ==> ";
252 if (LowerBound) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000253 dbgs() << LowerBound->getSExtValue();
Jim Grosbachfff56632014-06-16 16:55:20 +0000254 } else {
255 dbgs() << "NONE";
256 }
257 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
258 dbgs() << "RHS Bounds ==> ";
259 dbgs() << NewLowerBound->getSExtValue() << " - ";
260 if (UpperBound) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000261 dbgs() << UpperBound->getSExtValue() << "\n";
Jim Grosbachfff56632014-06-16 16:55:20 +0000262 } else {
263 dbgs() << "NONE\n";
264 });
265
Chris Lattnered922162003-10-07 18:46:23 +0000266 // Create a new node that checks if the value is < pivot. Go to the
267 // left branch if it is and right branch if not.
268 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000269 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattnered922162003-10-07 18:46:23 +0000270
Bob Wilsone4077362013-09-09 19:14:35 +0000271 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000272 Val, Pivot.Low, "Pivot");
Marcello Maggioni78035b12014-07-11 10:34:36 +0000273
274 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
275 NewUpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000276 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000277 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
278 UpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000279 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000280
281 Function::iterator FI = OrigBlock;
282 F->getBasicBlockList().insert(++FI, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000283 NewNode->getInstList().push_back(Comp);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000284
Gabor Greife9ecc682008-04-06 20:25:17 +0000285 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000286 return NewNode;
287}
288
289// newLeafBlock - Create a new leaf block for the binary lookup tree. It
290// checks if the switch's value == the case's value. If not, then it
291// jumps to the default branch. At this point in the tree, the value
292// can't be another valid case value, so the jump to the "default" branch
293// is warranted.
294//
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000295BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnered922162003-10-07 18:46:23 +0000296 BasicBlock* OrigBlock,
297 BasicBlock* Default)
298{
299 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000300 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Chris Lattner233f97a2007-04-17 18:09:47 +0000301 Function::iterator FI = OrigBlock;
302 F->getBasicBlockList().insert(++FI, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000303
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000304 // Emit comparison
Craig Topperf40110f2014-04-25 05:29:35 +0000305 ICmpInst* Comp = nullptr;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000306 if (Leaf.Low == Leaf.High) {
307 // Make the seteq instruction...
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000308 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
309 Leaf.Low, "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000310 } else {
311 // Make range comparison
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000312 if (Leaf.Low->isMinValue(true /*isSigned*/)) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000313 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000314 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
315 "SwitchLeaf");
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000316 } else if (Leaf.Low->isZero()) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000317 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000318 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
319 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000320 } else {
321 // Emit V-Lo <=u Hi-Lo
Owen Anderson487375e2009-07-29 18:55:55 +0000322 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000323 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000324 Val->getName()+".off",
325 NewLeaf);
Owen Anderson487375e2009-07-29 18:55:55 +0000326 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000327 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
328 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000329 }
330 }
Chris Lattnered922162003-10-07 18:46:23 +0000331
332 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000333 BasicBlock* Succ = Leaf.BB;
Gabor Greife9ecc682008-04-06 20:25:17 +0000334 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000335
336 // If there were any PHI nodes in this successor, rewrite one entry
337 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000338 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
339 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000340 // Remove all but one incoming entries from the cluster
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000341 uint64_t Range = Leaf.High->getSExtValue() -
342 Leaf.Low->getSExtValue();
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000343 for (uint64_t j = 0; j < Range; ++j) {
344 PN->removeIncomingValue(OrigBlock);
345 }
346
Chris Lattnered922162003-10-07 18:46:23 +0000347 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
348 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
349 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
350 }
351
352 return NewLeaf;
353}
354
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000355// Clusterify - Transform simple list of Cases into list of CaseRange's
356unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Bob Wilsone4077362013-09-09 19:14:35 +0000357 unsigned numCmps = 0;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000358
359 // Start with "simple" cases
Bob Wilsone4077362013-09-09 19:14:35 +0000360 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
361 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
362 i.getCaseSuccessor()));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000363
Bob Wilsone4077362013-09-09 19:14:35 +0000364 std::sort(Cases.begin(), Cases.end(), CaseCmp());
365
366 // Merge case into clusters
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000367 if (Cases.size() >= 2) {
368 CaseItr I = Cases.begin();
369 for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000370 int64_t nextValue = J->Low->getSExtValue();
371 int64_t currentValue = I->High->getSExtValue();
Bob Wilsone4077362013-09-09 19:14:35 +0000372 BasicBlock* nextBB = J->BB;
373 BasicBlock* currentBB = I->BB;
374
375 // If the two neighboring cases go to the same destination, merge them
376 // into a single case.
Justin Bognere46d3792015-06-20 00:28:25 +0000377 assert(nextValue > currentValue && "Cases should be strictly ascending");
378 if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
Bob Wilsone4077362013-09-09 19:14:35 +0000379 I->High = J->High;
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000380 // FIXME: Combine branch weights.
381 } else if (++I != J) {
382 *I = *J;
Bob Wilsone4077362013-09-09 19:14:35 +0000383 }
384 }
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000385 Cases.erase(std::next(I), Cases.end());
386 }
Bob Wilsone4077362013-09-09 19:14:35 +0000387
388 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
389 if (I->Low != I->High)
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000390 // A range counts double, since it requires two compares.
391 ++numCmps;
392 }
393
Bob Wilsone4077362013-09-09 19:14:35 +0000394 return numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000395}
396
Chris Lattner1b094a02003-04-23 16:23:59 +0000397// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnered922162003-10-07 18:46:23 +0000398// of chained if-then insts in a balanced binary search.
Chris Lattner1b094a02003-04-23 16:23:59 +0000399//
400void LowerSwitch::processSwitchInst(SwitchInst *SI) {
401 BasicBlock *CurBlock = SI->getParent();
402 BasicBlock *OrigBlock = CurBlock;
403 Function *F = CurBlock->getParent();
Eli Friedman95031ed2011-09-29 20:21:17 +0000404 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000405 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000406
Hans Wennborgae9c9712015-01-23 20:43:51 +0000407 // If there is only the default destination, just branch.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000408 if (!SI->getNumCases()) {
Hans Wennborgae9c9712015-01-23 20:43:51 +0000409 BranchInst::Create(Default, CurBlock);
410 SI->eraseFromParent();
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000411 return;
412 }
413
Hans Wennborgae9c9712015-01-23 20:43:51 +0000414 // Prepare cases vector.
415 CaseVector Cases;
416 unsigned numCmps = Clusterify(Cases, SI);
417 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
418 << ". Total compares: " << numCmps << "\n");
419 DEBUG(dbgs() << "Cases: " << Cases << "\n");
420 (void)numCmps;
421
422 ConstantInt *LowerBound = nullptr;
423 ConstantInt *UpperBound = nullptr;
424 std::vector<IntRange> UnreachableRanges;
425
426 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000427 // Make the bounds tightly fitted around the case value range, because we
Hans Wennborgae9c9712015-01-23 20:43:51 +0000428 // know that the value passed to the switch must be exactly one of the case
429 // values.
430 assert(!Cases.empty());
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000431 LowerBound = Cases.front().Low;
432 UpperBound = Cases.back().High;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000433
434 DenseMap<BasicBlock *, unsigned> Popularity;
435 unsigned MaxPop = 0;
436 BasicBlock *PopSucc = nullptr;
437
438 IntRange R = { INT64_MIN, INT64_MAX };
439 UnreachableRanges.push_back(R);
440 for (const auto &I : Cases) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000441 int64_t Low = I.Low->getSExtValue();
442 int64_t High = I.High->getSExtValue();
Hans Wennborgae9c9712015-01-23 20:43:51 +0000443
444 IntRange &LastRange = UnreachableRanges.back();
445 if (LastRange.Low == Low) {
446 // There is nothing left of the previous range.
447 UnreachableRanges.pop_back();
448 } else {
449 // Terminate the previous range.
450 assert(Low > LastRange.Low);
451 LastRange.High = Low - 1;
452 }
453 if (High != INT64_MAX) {
454 IntRange R = { High + 1, INT64_MAX };
455 UnreachableRanges.push_back(R);
456 }
457
458 // Count popularity.
459 int64_t N = High - Low + 1;
460 unsigned &Pop = Popularity[I.BB];
461 if ((Pop += N) > MaxPop) {
462 MaxPop = Pop;
463 PopSucc = I.BB;
464 }
465 }
466#ifndef NDEBUG
467 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
468 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
469 I != E; ++I) {
470 assert(I->Low <= I->High);
471 auto Next = I + 1;
472 if (Next != E) {
473 assert(Next->Low > I->High);
474 }
475 }
476#endif
477
478 // Use the most popular block as the new default, reducing the number of
479 // cases.
480 assert(MaxPop > 0 && PopSucc);
481 Default = PopSucc;
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000482 Cases.erase(std::remove_if(
483 Cases.begin(), Cases.end(),
484 [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
485 Cases.end());
Hans Wennborgae9c9712015-01-23 20:43:51 +0000486
487 // If there are no cases left, just branch.
488 if (Cases.empty()) {
489 BranchInst::Create(Default, CurBlock);
490 SI->eraseFromParent();
491 return;
492 }
493 }
494
Chris Lattnered922162003-10-07 18:46:23 +0000495 // Create a new, empty default block so that the new hierarchy of
496 // if-then statements go to this and the PHI nodes are happy.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000497 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
498 F->getBasicBlockList().insert(Default, NewDefault);
499 BranchInst::Create(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000500
Chris Lattnered922162003-10-07 18:46:23 +0000501 // If there is an entry in any PHI nodes for the default edge, make sure
502 // to update them as well.
Reid Spencer66149462004-09-15 17:06:42 +0000503 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
504 PHINode *PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000505 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
506 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
507 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000508 }
509
Jim Grosbachfff56632014-06-16 16:55:20 +0000510 BasicBlock *SwitchBlock =
511 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000512 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
Chris Lattnered922162003-10-07 18:46:23 +0000513
514 // Branch to our shiny new if-then stuff...
Gabor Greife9ecc682008-04-06 20:25:17 +0000515 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000516
Chris Lattner1b094a02003-04-23 16:23:59 +0000517 // We are now done with the switch instruction, delete it.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000518 BasicBlock *OldDefault = SI->getDefaultDest();
Chris Lattnerb6865952004-03-14 04:14:31 +0000519 CurBlock->getInstList().erase(SI);
Jim Grosbachfff56632014-06-16 16:55:20 +0000520
Hans Wennborgae9c9712015-01-23 20:43:51 +0000521 // If the Default block has no more predecessors just remove it.
522 if (pred_begin(OldDefault) == pred_end(OldDefault))
523 DeleteDeadBlock(OldDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000524}