blob: b375d51005d574319b19996d4175634a7f92a189 [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
Sanjay Patel815adac2015-09-16 16:21:08 +000052 /// Replace all SwitchInst instructions with chained branch instructions.
Nick Lewycky02d5f772009-10-25 06:33:48 +000053 class LowerSwitch : public FunctionPass {
Chris Lattnered922162003-10-07 18:46:23 +000054 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000055 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000056 LowerSwitch() : FunctionPass(ID) {
57 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
58 }
Devang Patel09f162c2007-05-01 21:15:47 +000059
Craig Topper3e4c6972014-03-05 09:10:37 +000060 bool runOnFunction(Function &F) override;
61
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000062 struct CaseRange {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000063 ConstantInt* Low;
64 ConstantInt* High;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000065 BasicBlock* BB;
66
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000067 CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
Hans Wennborg8c82fbc2015-02-05 16:50:27 +000068 : Low(low), High(high), BB(bb) {}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000069 };
70
Jim Grosbachfff56632014-06-16 16:55:20 +000071 typedef std::vector<CaseRange> CaseVector;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000072 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnered922162003-10-07 18:46:23 +000073 private:
Chen Li0786bc92015-08-11 20:16:17 +000074 void processSwitchInst(SwitchInst *SI, SmallPtrSetImpl<BasicBlock*> &DeleteList);
Chris Lattnered922162003-10-07 18:46:23 +000075
Jim Grosbachfff56632014-06-16 16:55:20 +000076 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
77 ConstantInt *LowerBound, ConstantInt *UpperBound,
Marcello Maggioni78035b12014-07-11 10:34:36 +000078 Value *Val, BasicBlock *Predecessor,
Hans Wennborgae9c9712015-01-23 20:43:51 +000079 BasicBlock *OrigBlock, BasicBlock *Default,
80 const std::vector<IntRange> &UnreachableRanges);
Jim Grosbachfff56632014-06-16 16:55:20 +000081 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
82 BasicBlock *Default);
83 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000084 };
Bob Wilsone4077362013-09-09 19:14:35 +000085
86 /// The comparison function for sorting the switch case values in the vector.
87 /// WARNING: Case ranges should be disjoint!
88 struct CaseCmp {
89 bool operator () (const LowerSwitch::CaseRange& C1,
90 const LowerSwitch::CaseRange& C2) {
91
92 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
93 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
94 return CI1->getValue().slt(CI2->getValue());
95 }
96 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000097}
Chris Lattner1b094a02003-04-23 16:23:59 +000098
Dan Gohmand78c4002008-05-13 00:00:25 +000099char LowerSwitch::ID = 0;
Owen Andersond31d82d2010-08-23 17:52:01 +0000100INITIALIZE_PASS(LowerSwitch, "lowerswitch",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000101 "Lower SwitchInst's to branches", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000102
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000103// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +0000104char &llvm::LowerSwitchID = LowerSwitch::ID;
Chris Lattner1b094a02003-04-23 16:23:59 +0000105// createLowerSwitchPass - Interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +0000106FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +0000107 return new LowerSwitch();
108}
109
110bool LowerSwitch::runOnFunction(Function &F) {
111 bool Changed = false;
Chen Li0786bc92015-08-11 20:16:17 +0000112 SmallPtrSet<BasicBlock*, 8> DeleteList;
Chris Lattner1b094a02003-04-23 16:23:59 +0000113
114 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000115 BasicBlock *Cur = &*I++; // Advance over block so we don't traverse new blocks
Chris Lattner1b094a02003-04-23 16:23:59 +0000116
Chen Li0786bc92015-08-11 20:16:17 +0000117 // If the block is a dead Default block that will be deleted later, don't
118 // waste time processing it.
119 if (DeleteList.count(Cur))
120 continue;
121
Chris Lattner1b094a02003-04-23 16:23:59 +0000122 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
123 Changed = true;
Chen Li10f01bd2015-08-11 18:12:26 +0000124 processSwitchInst(SI, DeleteList);
Chris Lattner1b094a02003-04-23 16:23:59 +0000125 }
126 }
127
Chen Li10f01bd2015-08-11 18:12:26 +0000128 for (BasicBlock* BB: DeleteList) {
129 DeleteDeadBlock(BB);
130 }
131
Chris Lattner1b094a02003-04-23 16:23:59 +0000132 return Changed;
133}
134
Sanjay Patel815adac2015-09-16 16:21:08 +0000135/// Used for debugging purposes.
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000136static raw_ostream& operator<<(raw_ostream &O,
Chandler Carruth88c54b82010-10-23 08:10:43 +0000137 const LowerSwitch::CaseVector &C)
138 LLVM_ATTRIBUTE_USED;
Mike Stump47987632009-07-27 23:33:34 +0000139static raw_ostream& operator<<(raw_ostream &O,
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000140 const LowerSwitch::CaseVector &C) {
Chris Lattnered922162003-10-07 18:46:23 +0000141 O << "[";
142
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000143 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattner49525f82004-01-09 06:02:20 +0000144 E = C.end(); B != E; ) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000145 O << *B->Low << " -" << *B->High;
Chris Lattnered922162003-10-07 18:46:23 +0000146 if (++B != E) O << ", ";
147 }
148
149 return O << "]";
150}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000151
Sanjay Patel815adac2015-09-16 16:21:08 +0000152/// \brief Update the first occurrence of the "switch statement" BB in the PHI
153/// node with the "new" BB. The other occurrences will:
154///
155/// 1) Be updated by subsequent calls to this function. Switch statements may
156/// have more than one outcoming edge into the same BB if they all have the same
157/// value. When the switch statement is converted these incoming edges are now
158/// coming from multiple BBs.
159/// 2) Removed if subsequent incoming values now share the same case, i.e.,
160/// multiple outcome edges are condensed into one. This is necessary to keep the
161/// number of phi values equal to the number of branches to SuccBB.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000162static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
163 unsigned NumMergedCases) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000164 for (BasicBlock::iterator I = SuccBB->begin(),
165 IE = SuccBB->getFirstNonPHI()->getIterator();
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000166 I != IE; ++I) {
Marcello Maggioni78035b12014-07-11 10:34:36 +0000167 PHINode *PN = cast<PHINode>(I);
168
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000169 // Only update the first occurrence.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000170 unsigned Idx = 0, E = PN->getNumIncomingValues();
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000171 unsigned LocalNumMergedCases = NumMergedCases;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000172 for (; Idx != E; ++Idx) {
Juergen Ributzkad4417252014-11-10 21:05:27 +0000173 if (PN->getIncomingBlock(Idx) == OrigBB) {
174 PN->setIncomingBlock(Idx, NewBB);
175 break;
176 }
Marcello Maggioni78035b12014-07-11 10:34:36 +0000177 }
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000178
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000179 // Remove additional occurrences coming from condensed cases and keep the
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000180 // number of incoming values equal to the number of branches to SuccBB.
Michael Liao24fcae82015-03-17 18:03:10 +0000181 SmallVector<unsigned, 8> Indices;
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000182 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000183 if (PN->getIncomingBlock(Idx) == OrigBB) {
Michael Liao24fcae82015-03-17 18:03:10 +0000184 Indices.push_back(Idx);
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000185 LocalNumMergedCases--;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000186 }
Michael Liao24fcae82015-03-17 18:03:10 +0000187 // Remove incoming values in the reverse order to prevent invalidating
188 // *successive* index.
David Majnemerd7708772016-06-24 04:05:21 +0000189 for (unsigned III : reverse(Indices))
190 PN->removeIncomingValue(III);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000191 }
192}
193
Sanjay Patel815adac2015-09-16 16:21:08 +0000194/// Convert the switch statement into a binary lookup of the case values.
195/// The function recursively builds this tree. LowerBound and UpperBound are
196/// used to keep track of the bounds for Val that have already been checked by
197/// a block emitted by one of the previous calls to switchConvert in the call
198/// stack.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000199BasicBlock *
200LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
201 ConstantInt *UpperBound, Value *Val,
202 BasicBlock *Predecessor, BasicBlock *OrigBlock,
203 BasicBlock *Default,
204 const std::vector<IntRange> &UnreachableRanges) {
Chris Lattnered922162003-10-07 18:46:23 +0000205 unsigned Size = End - Begin;
206
Jim Grosbachfff56632014-06-16 16:55:20 +0000207 if (Size == 1) {
208 // Check if the Case Range is perfectly squeezed in between
209 // already checked Upper and Lower bounds. If it is then we can avoid
210 // emitting the code that checks if the value actually falls in the range
211 // because the bounds already tell us so.
212 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000213 unsigned NumMergedCases = 0;
214 if (LowerBound && UpperBound)
215 NumMergedCases =
216 UpperBound->getSExtValue() - LowerBound->getSExtValue();
217 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
Jim Grosbachfff56632014-06-16 16:55:20 +0000218 return Begin->BB;
219 }
Chris Lattnered922162003-10-07 18:46:23 +0000220 return newLeafBlock(*Begin, Val, OrigBlock, Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000221 }
Chris Lattnered922162003-10-07 18:46:23 +0000222
223 unsigned Mid = Size / 2;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000224 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greene50c54232010-01-05 01:26:45 +0000225 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000226 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greene50c54232010-01-05 01:26:45 +0000227 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000228
Jim Grosbachfff56632014-06-16 16:55:20 +0000229 CaseRange &Pivot = *(Begin + Mid);
230 DEBUG(dbgs() << "Pivot ==> "
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000231 << Pivot.Low->getValue()
232 << " -" << Pivot.High->getValue() << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000233
Jim Grosbachfff56632014-06-16 16:55:20 +0000234 // NewLowerBound here should never be the integer minimal value.
235 // This is because it is computed from a case range that is never
236 // the smallest, so there is always a case range that has at least
237 // a smaller value.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000238 ConstantInt *NewLowerBound = Pivot.Low;
Jim Grosbachfff56632014-06-16 16:55:20 +0000239
Hans Wennborgae9c9712015-01-23 20:43:51 +0000240 // Because NewLowerBound is never the smallest representable integer
241 // it is safe here to subtract one.
242 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
243 NewLowerBound->getValue() - 1);
244
245 if (!UnreachableRanges.empty()) {
246 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000247 int64_t GapLow = LHS.back().High->getSExtValue() + 1;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000248 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
249 IntRange Gap = { GapLow, GapHigh };
250 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000251 NewUpperBound = LHS.back().High;
Jim Grosbachfff56632014-06-16 16:55:20 +0000252 }
253
254 DEBUG(dbgs() << "LHS Bounds ==> ";
255 if (LowerBound) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000256 dbgs() << LowerBound->getSExtValue();
Jim Grosbachfff56632014-06-16 16:55:20 +0000257 } else {
258 dbgs() << "NONE";
259 }
260 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
261 dbgs() << "RHS Bounds ==> ";
262 dbgs() << NewLowerBound->getSExtValue() << " - ";
263 if (UpperBound) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000264 dbgs() << UpperBound->getSExtValue() << "\n";
Jim Grosbachfff56632014-06-16 16:55:20 +0000265 } else {
266 dbgs() << "NONE\n";
267 });
268
Chris Lattnered922162003-10-07 18:46:23 +0000269 // Create a new node that checks if the value is < pivot. Go to the
270 // left branch if it is and right branch if not.
271 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000272 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattnered922162003-10-07 18:46:23 +0000273
Bob Wilsone4077362013-09-09 19:14:35 +0000274 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000275 Val, Pivot.Low, "Pivot");
Marcello Maggioni78035b12014-07-11 10:34:36 +0000276
277 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
278 NewUpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000279 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000280 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
281 UpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000282 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000283
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000284 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000285 NewNode->getInstList().push_back(Comp);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000286
Gabor Greife9ecc682008-04-06 20:25:17 +0000287 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000288 return NewNode;
289}
290
Sanjay Patel815adac2015-09-16 16:21:08 +0000291/// Create a new leaf block for the binary lookup tree. It checks if the
292/// switch's value == the case's value. If not, then it jumps to the default
293/// branch. At this point in the tree, the value can't be another valid case
294/// value, so the jump to the "default" branch is warranted.
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");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000301 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000302
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000303 // Emit comparison
Craig Topperf40110f2014-04-25 05:29:35 +0000304 ICmpInst* Comp = nullptr;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000305 if (Leaf.Low == Leaf.High) {
306 // Make the seteq instruction...
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000307 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
308 Leaf.Low, "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000309 } else {
310 // Make range comparison
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000311 if (Leaf.Low->isMinValue(true /*isSigned*/)) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000312 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000313 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
314 "SwitchLeaf");
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000315 } else if (Leaf.Low->isZero()) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000316 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000317 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
318 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000319 } else {
320 // Emit V-Lo <=u Hi-Lo
Owen Anderson487375e2009-07-29 18:55:55 +0000321 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000322 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000323 Val->getName()+".off",
324 NewLeaf);
Owen Anderson487375e2009-07-29 18:55:55 +0000325 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000326 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
327 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000328 }
329 }
Chris Lattnered922162003-10-07 18:46:23 +0000330
331 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000332 BasicBlock* Succ = Leaf.BB;
Gabor Greife9ecc682008-04-06 20:25:17 +0000333 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000334
335 // If there were any PHI nodes in this successor, rewrite one entry
336 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000337 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
338 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000339 // Remove all but one incoming entries from the cluster
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000340 uint64_t Range = Leaf.High->getSExtValue() -
341 Leaf.Low->getSExtValue();
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000342 for (uint64_t j = 0; j < Range; ++j) {
343 PN->removeIncomingValue(OrigBlock);
344 }
345
Chris Lattnered922162003-10-07 18:46:23 +0000346 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
347 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
348 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
349 }
350
351 return NewLeaf;
352}
353
Sanjay Patel815adac2015-09-16 16:21:08 +0000354/// Transform simple list of Cases into list of CaseRange's.
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000355unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Bob Wilsone4077362013-09-09 19:14:35 +0000356 unsigned numCmps = 0;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000357
358 // Start with "simple" cases
Chandler Carruth927d8e62017-04-12 07:27:28 +0000359 for (auto Case : SI->cases())
360 Cases.push_back(CaseRange(Case.getCaseValue(), Case.getCaseValue(),
361 Case.getCaseSuccessor()));
362
Bob Wilsone4077362013-09-09 19:14:35 +0000363 std::sort(Cases.begin(), Cases.end(), CaseCmp());
364
365 // Merge case into clusters
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000366 if (Cases.size() >= 2) {
367 CaseItr I = Cases.begin();
368 for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000369 int64_t nextValue = J->Low->getSExtValue();
370 int64_t currentValue = I->High->getSExtValue();
Bob Wilsone4077362013-09-09 19:14:35 +0000371 BasicBlock* nextBB = J->BB;
372 BasicBlock* currentBB = I->BB;
373
374 // If the two neighboring cases go to the same destination, merge them
375 // into a single case.
Justin Bognere46d3792015-06-20 00:28:25 +0000376 assert(nextValue > currentValue && "Cases should be strictly ascending");
377 if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
Bob Wilsone4077362013-09-09 19:14:35 +0000378 I->High = J->High;
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000379 // FIXME: Combine branch weights.
380 } else if (++I != J) {
381 *I = *J;
Bob Wilsone4077362013-09-09 19:14:35 +0000382 }
383 }
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000384 Cases.erase(std::next(I), Cases.end());
385 }
Bob Wilsone4077362013-09-09 19:14:35 +0000386
387 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
388 if (I->Low != I->High)
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000389 // A range counts double, since it requires two compares.
390 ++numCmps;
391 }
392
Bob Wilsone4077362013-09-09 19:14:35 +0000393 return numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000394}
395
Sanjay Patel815adac2015-09-16 16:21:08 +0000396/// Replace the specified switch instruction with a sequence of chained if-then
397/// insts in a balanced binary search.
Chen Li0786bc92015-08-11 20:16:17 +0000398void LowerSwitch::processSwitchInst(SwitchInst *SI,
399 SmallPtrSetImpl<BasicBlock*> &DeleteList) {
Chris Lattner1b094a02003-04-23 16:23:59 +0000400 BasicBlock *CurBlock = SI->getParent();
401 BasicBlock *OrigBlock = CurBlock;
402 Function *F = CurBlock->getParent();
Eli Friedman95031ed2011-09-29 20:21:17 +0000403 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000404 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000405
Hans Wennborgae9c9712015-01-23 20:43:51 +0000406 // If there is only the default destination, just branch.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000407 if (!SI->getNumCases()) {
Hans Wennborgae9c9712015-01-23 20:43:51 +0000408 BranchInst::Create(Default, CurBlock);
409 SI->eraseFromParent();
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000410 return;
411 }
412
Hans Wennborgae9c9712015-01-23 20:43:51 +0000413 // Prepare cases vector.
414 CaseVector Cases;
415 unsigned numCmps = Clusterify(Cases, SI);
416 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
417 << ". Total compares: " << numCmps << "\n");
418 DEBUG(dbgs() << "Cases: " << Cases << "\n");
419 (void)numCmps;
420
421 ConstantInt *LowerBound = nullptr;
422 ConstantInt *UpperBound = nullptr;
423 std::vector<IntRange> UnreachableRanges;
424
425 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000426 // Make the bounds tightly fitted around the case value range, because we
Hans Wennborgae9c9712015-01-23 20:43:51 +0000427 // know that the value passed to the switch must be exactly one of the case
428 // values.
429 assert(!Cases.empty());
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000430 LowerBound = Cases.front().Low;
431 UpperBound = Cases.back().High;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000432
433 DenseMap<BasicBlock *, unsigned> Popularity;
434 unsigned MaxPop = 0;
435 BasicBlock *PopSucc = nullptr;
436
437 IntRange R = { INT64_MIN, INT64_MAX };
438 UnreachableRanges.push_back(R);
439 for (const auto &I : Cases) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000440 int64_t Low = I.Low->getSExtValue();
441 int64_t High = I.High->getSExtValue();
Hans Wennborgae9c9712015-01-23 20:43:51 +0000442
443 IntRange &LastRange = UnreachableRanges.back();
444 if (LastRange.Low == Low) {
445 // There is nothing left of the previous range.
446 UnreachableRanges.pop_back();
447 } else {
448 // Terminate the previous range.
449 assert(Low > LastRange.Low);
450 LastRange.High = Low - 1;
451 }
452 if (High != INT64_MAX) {
453 IntRange R = { High + 1, INT64_MAX };
454 UnreachableRanges.push_back(R);
455 }
456
457 // Count popularity.
458 int64_t N = High - Low + 1;
459 unsigned &Pop = Popularity[I.BB];
460 if ((Pop += N) > MaxPop) {
461 MaxPop = Pop;
462 PopSucc = I.BB;
463 }
464 }
465#ifndef NDEBUG
466 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
467 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
468 I != E; ++I) {
469 assert(I->Low <= I->High);
470 auto Next = I + 1;
471 if (Next != E) {
472 assert(Next->Low > I->High);
473 }
474 }
475#endif
476
477 // Use the most popular block as the new default, reducing the number of
478 // cases.
479 assert(MaxPop > 0 && PopSucc);
480 Default = PopSucc;
David Majnemerc7004902016-08-12 04:32:37 +0000481 Cases.erase(
482 remove_if(Cases,
483 [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
484 Cases.end());
Hans Wennborgae9c9712015-01-23 20:43:51 +0000485
486 // If there are no cases left, just branch.
487 if (Cases.empty()) {
488 BranchInst::Create(Default, CurBlock);
489 SI->eraseFromParent();
490 return;
491 }
492 }
493
Chris Lattnered922162003-10-07 18:46:23 +0000494 // Create a new, empty default block so that the new hierarchy of
495 // if-then statements go to this and the PHI nodes are happy.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000496 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000497 F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
Hans Wennborgae9c9712015-01-23 20:43:51 +0000498 BranchInst::Create(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000499
Chris Lattnered922162003-10-07 18:46:23 +0000500 // If there is an entry in any PHI nodes for the default edge, make sure
501 // to update them as well.
Reid Spencer66149462004-09-15 17:06:42 +0000502 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
503 PHINode *PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000504 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
505 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
506 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000507 }
508
Jim Grosbachfff56632014-06-16 16:55:20 +0000509 BasicBlock *SwitchBlock =
510 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000511 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
Chris Lattnered922162003-10-07 18:46:23 +0000512
513 // Branch to our shiny new if-then stuff...
Gabor Greife9ecc682008-04-06 20:25:17 +0000514 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000515
Chris Lattner1b094a02003-04-23 16:23:59 +0000516 // We are now done with the switch instruction, delete it.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000517 BasicBlock *OldDefault = SI->getDefaultDest();
Chris Lattnerb6865952004-03-14 04:14:31 +0000518 CurBlock->getInstList().erase(SI);
Jim Grosbachfff56632014-06-16 16:55:20 +0000519
Chen Li10f01bd2015-08-11 18:12:26 +0000520 // If the Default block has no more predecessors just add it to DeleteList.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000521 if (pred_begin(OldDefault) == pred_end(OldDefault))
Chen Li0786bc92015-08-11 20:16:17 +0000522 DeleteList.insert(OldDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000523}