blob: fec13c8c160b0c8f922eaddd1f67241034f1ff87 [file] [log] [blame]
Chris Lattner1b094a02003-04-23 16:23:59 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattner1b094a02003-04-23 16:23:59 +00008//
Gordon Henriksend5687672007-11-04 16:15:04 +00009// The LowerSwitch transformation rewrites switch instructions with a sequence
10// of branches, which allows targets to get away with not implementing the
11// switch instruction until it is convenient.
Chris Lattner1b094a02003-04-23 16:23:59 +000012//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenkofce43572017-10-21 00:57:46 +000015#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/STLExtras.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000017#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/IR/BasicBlock.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000020#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/Function.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000023#include "llvm/IR/InstrTypes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Instructions.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000025#include "llvm/IR/Value.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000026#include "llvm/Pass.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000027#include "llvm/Support/Casting.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000028#include "llvm/Support/Compiler.h"
Nick Lewycky974e12b2009-10-25 06:57:41 +000029#include "llvm/Support/Debug.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000030#include "llvm/Support/raw_ostream.h"
David Blaikiea373d182018-03-28 17:44:36 +000031#include "llvm/Transforms/Utils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000033#include <algorithm>
Eugene Zelenkofce43572017-10-21 00:57:46 +000034#include <cassert>
35#include <cstdint>
36#include <iterator>
37#include <limits>
38#include <vector>
39
Chris Lattner49525f82004-01-09 06:02:20 +000040using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000041
Chandler Carruthe96dd892014-04-21 22:55:11 +000042#define DEBUG_TYPE "lower-switch"
43
Chris Lattner1b094a02003-04-23 16:23:59 +000044namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +000045
Hans Wennborgae9c9712015-01-23 20:43:51 +000046 struct IntRange {
47 int64_t Low, High;
48 };
Hans Wennborgae9c9712015-01-23 20:43:51 +000049
Eugene Zelenkofce43572017-10-21 00:57:46 +000050} // end anonymous namespace
51
52// Return true iff R is covered by Ranges.
53static bool IsInRanges(const IntRange &R,
54 const std::vector<IntRange> &Ranges) {
55 // Note: Ranges must be sorted, non-overlapping and non-adjacent.
56
57 // Find the first range whose High field is >= R.High,
58 // then check if the Low field is <= R.Low. If so, we
59 // have a Range that covers R.
60 auto I = std::lower_bound(
61 Ranges.begin(), Ranges.end(), R,
62 [](const IntRange &A, const IntRange &B) { return A.High < B.High; });
63 return I != Ranges.end() && I->Low <= R.Low;
64}
65
66namespace {
Hans Wennborgae9c9712015-01-23 20:43:51 +000067
Sanjay Patel815adac2015-09-16 16:21:08 +000068 /// Replace all SwitchInst instructions with chained branch instructions.
Nick Lewycky02d5f772009-10-25 06:33:48 +000069 class LowerSwitch : public FunctionPass {
Chris Lattnered922162003-10-07 18:46:23 +000070 public:
Eugene Zelenkofce43572017-10-21 00:57:46 +000071 // Pass identification, replacement for typeid
72 static char ID;
73
Owen Anderson6c18d1a2010-10-19 17:21:58 +000074 LowerSwitch() : FunctionPass(ID) {
75 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +000076 }
Devang Patel09f162c2007-05-01 21:15:47 +000077
Craig Topper3e4c6972014-03-05 09:10:37 +000078 bool runOnFunction(Function &F) override;
79
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000080 struct CaseRange {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000081 ConstantInt* Low;
82 ConstantInt* High;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000083 BasicBlock* BB;
84
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000085 CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
Hans Wennborg8c82fbc2015-02-05 16:50:27 +000086 : Low(low), High(high), BB(bb) {}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000087 };
88
Eugene Zelenkofce43572017-10-21 00:57:46 +000089 using CaseVector = std::vector<CaseRange>;
90 using CaseItr = std::vector<CaseRange>::iterator;
91
Chris Lattnered922162003-10-07 18:46:23 +000092 private:
Chen Li0786bc92015-08-11 20:16:17 +000093 void processSwitchInst(SwitchInst *SI, SmallPtrSetImpl<BasicBlock*> &DeleteList);
Chris Lattnered922162003-10-07 18:46:23 +000094
Jim Grosbachfff56632014-06-16 16:55:20 +000095 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
96 ConstantInt *LowerBound, ConstantInt *UpperBound,
Marcello Maggioni78035b12014-07-11 10:34:36 +000097 Value *Val, BasicBlock *Predecessor,
Hans Wennborgae9c9712015-01-23 20:43:51 +000098 BasicBlock *OrigBlock, BasicBlock *Default,
99 const std::vector<IntRange> &UnreachableRanges);
Jim Grosbachfff56632014-06-16 16:55:20 +0000100 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
101 BasicBlock *Default);
102 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +0000103 };
Bob Wilsone4077362013-09-09 19:14:35 +0000104
105 /// The comparison function for sorting the switch case values in the vector.
106 /// WARNING: Case ranges should be disjoint!
107 struct CaseCmp {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000108 bool operator()(const LowerSwitch::CaseRange& C1,
109 const LowerSwitch::CaseRange& C2) {
Bob Wilsone4077362013-09-09 19:14:35 +0000110 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
111 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
112 return CI1->getValue().slt(CI2->getValue());
113 }
114 };
Eugene Zelenkofce43572017-10-21 00:57:46 +0000115
116} // end anonymous namespace
Chris Lattner1b094a02003-04-23 16:23:59 +0000117
Dan Gohmand78c4002008-05-13 00:00:25 +0000118char LowerSwitch::ID = 0;
Dan Gohmand78c4002008-05-13 00:00:25 +0000119
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000120// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +0000121char &llvm::LowerSwitchID = LowerSwitch::ID;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000122
123INITIALIZE_PASS(LowerSwitch, "lowerswitch",
124 "Lower SwitchInst's to branches", false, false)
125
Chris Lattner1b094a02003-04-23 16:23:59 +0000126// createLowerSwitchPass - Interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +0000127FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +0000128 return new LowerSwitch();
129}
130
131bool LowerSwitch::runOnFunction(Function &F) {
132 bool Changed = false;
Chen Li0786bc92015-08-11 20:16:17 +0000133 SmallPtrSet<BasicBlock*, 8> DeleteList;
Chris Lattner1b094a02003-04-23 16:23:59 +0000134
135 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000136 BasicBlock *Cur = &*I++; // Advance over block so we don't traverse new blocks
Chris Lattner1b094a02003-04-23 16:23:59 +0000137
Chen Li0786bc92015-08-11 20:16:17 +0000138 // If the block is a dead Default block that will be deleted later, don't
139 // waste time processing it.
140 if (DeleteList.count(Cur))
141 continue;
142
Chris Lattner1b094a02003-04-23 16:23:59 +0000143 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
144 Changed = true;
Chen Li10f01bd2015-08-11 18:12:26 +0000145 processSwitchInst(SI, DeleteList);
Chris Lattner1b094a02003-04-23 16:23:59 +0000146 }
147 }
148
Chen Li10f01bd2015-08-11 18:12:26 +0000149 for (BasicBlock* BB: DeleteList) {
150 DeleteDeadBlock(BB);
151 }
152
Chris Lattner1b094a02003-04-23 16:23:59 +0000153 return Changed;
154}
155
Sanjay Patel815adac2015-09-16 16:21:08 +0000156/// Used for debugging purposes.
Fangrui Song862eebb2018-05-05 20:14:38 +0000157LLVM_ATTRIBUTE_USED
158static raw_ostream &operator<<(raw_ostream &O,
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000159 const LowerSwitch::CaseVector &C) {
Chris Lattnered922162003-10-07 18:46:23 +0000160 O << "[";
161
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000162 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattner49525f82004-01-09 06:02:20 +0000163 E = C.end(); B != E; ) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000164 O << *B->Low << " -" << *B->High;
Chris Lattnered922162003-10-07 18:46:23 +0000165 if (++B != E) O << ", ";
166 }
167
168 return O << "]";
169}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000170
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000171/// Update the first occurrence of the "switch statement" BB in the PHI
Sanjay Patel815adac2015-09-16 16:21:08 +0000172/// node with the "new" BB. The other occurrences will:
173///
174/// 1) Be updated by subsequent calls to this function. Switch statements may
175/// have more than one outcoming edge into the same BB if they all have the same
176/// value. When the switch statement is converted these incoming edges are now
177/// coming from multiple BBs.
178/// 2) Removed if subsequent incoming values now share the same case, i.e.,
179/// multiple outcome edges are condensed into one. This is necessary to keep the
180/// number of phi values equal to the number of branches to SuccBB.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000181static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
182 unsigned NumMergedCases) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000183 for (BasicBlock::iterator I = SuccBB->begin(),
184 IE = SuccBB->getFirstNonPHI()->getIterator();
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000185 I != IE; ++I) {
Marcello Maggioni78035b12014-07-11 10:34:36 +0000186 PHINode *PN = cast<PHINode>(I);
187
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000188 // Only update the first occurrence.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000189 unsigned Idx = 0, E = PN->getNumIncomingValues();
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000190 unsigned LocalNumMergedCases = NumMergedCases;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000191 for (; Idx != E; ++Idx) {
Juergen Ributzkad4417252014-11-10 21:05:27 +0000192 if (PN->getIncomingBlock(Idx) == OrigBB) {
193 PN->setIncomingBlock(Idx, NewBB);
194 break;
195 }
Marcello Maggioni78035b12014-07-11 10:34:36 +0000196 }
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000197
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000198 // Remove additional occurrences coming from condensed cases and keep the
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000199 // number of incoming values equal to the number of branches to SuccBB.
Michael Liao24fcae82015-03-17 18:03:10 +0000200 SmallVector<unsigned, 8> Indices;
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000201 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000202 if (PN->getIncomingBlock(Idx) == OrigBB) {
Michael Liao24fcae82015-03-17 18:03:10 +0000203 Indices.push_back(Idx);
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000204 LocalNumMergedCases--;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000205 }
Michael Liao24fcae82015-03-17 18:03:10 +0000206 // Remove incoming values in the reverse order to prevent invalidating
207 // *successive* index.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000208 for (unsigned III : llvm::reverse(Indices))
David Majnemerd7708772016-06-24 04:05:21 +0000209 PN->removeIncomingValue(III);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000210 }
211}
212
Sanjay Patel815adac2015-09-16 16:21:08 +0000213/// Convert the switch statement into a binary lookup of the case values.
214/// The function recursively builds this tree. LowerBound and UpperBound are
215/// used to keep track of the bounds for Val that have already been checked by
216/// a block emitted by one of the previous calls to switchConvert in the call
217/// stack.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000218BasicBlock *
219LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
220 ConstantInt *UpperBound, Value *Val,
221 BasicBlock *Predecessor, BasicBlock *OrigBlock,
222 BasicBlock *Default,
223 const std::vector<IntRange> &UnreachableRanges) {
Chris Lattnered922162003-10-07 18:46:23 +0000224 unsigned Size = End - Begin;
225
Jim Grosbachfff56632014-06-16 16:55:20 +0000226 if (Size == 1) {
227 // Check if the Case Range is perfectly squeezed in between
228 // already checked Upper and Lower bounds. If it is then we can avoid
229 // emitting the code that checks if the value actually falls in the range
230 // because the bounds already tell us so.
231 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000232 unsigned NumMergedCases = 0;
233 if (LowerBound && UpperBound)
234 NumMergedCases =
235 UpperBound->getSExtValue() - LowerBound->getSExtValue();
236 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
Jim Grosbachfff56632014-06-16 16:55:20 +0000237 return Begin->BB;
238 }
Chris Lattnered922162003-10-07 18:46:23 +0000239 return newLeafBlock(*Begin, Val, OrigBlock, Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000240 }
Chris Lattnered922162003-10-07 18:46:23 +0000241
242 unsigned Mid = Size / 2;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000243 std::vector<CaseRange> LHS(Begin, Begin + Mid);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000244 LLVM_DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000245 std::vector<CaseRange> RHS(Begin + Mid, End);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000246 LLVM_DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000247
Jim Grosbachfff56632014-06-16 16:55:20 +0000248 CaseRange &Pivot = *(Begin + Mid);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000249 LLVM_DEBUG(dbgs() << "Pivot ==> " << Pivot.Low->getValue() << " -"
250 << Pivot.High->getValue() << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000251
Jim Grosbachfff56632014-06-16 16:55:20 +0000252 // NewLowerBound here should never be the integer minimal value.
253 // This is because it is computed from a case range that is never
254 // the smallest, so there is always a case range that has at least
255 // a smaller value.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000256 ConstantInt *NewLowerBound = Pivot.Low;
Jim Grosbachfff56632014-06-16 16:55:20 +0000257
Hans Wennborgae9c9712015-01-23 20:43:51 +0000258 // Because NewLowerBound is never the smallest representable integer
259 // it is safe here to subtract one.
260 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
261 NewLowerBound->getValue() - 1);
262
263 if (!UnreachableRanges.empty()) {
264 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000265 int64_t GapLow = LHS.back().High->getSExtValue() + 1;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000266 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
267 IntRange Gap = { GapLow, GapHigh };
268 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000269 NewUpperBound = LHS.back().High;
Jim Grosbachfff56632014-06-16 16:55:20 +0000270 }
271
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000272 LLVM_DEBUG(dbgs() << "LHS Bounds ==> "; if (LowerBound) {
273 dbgs() << LowerBound->getSExtValue();
274 } else { dbgs() << "NONE"; } dbgs() << " - "
275 << NewUpperBound->getSExtValue() << "\n";
276 dbgs() << "RHS Bounds ==> ";
277 dbgs() << NewLowerBound->getSExtValue() << " - "; if (UpperBound) {
278 dbgs() << UpperBound->getSExtValue() << "\n";
279 } else { dbgs() << "NONE\n"; });
Jim Grosbachfff56632014-06-16 16:55:20 +0000280
Chris Lattnered922162003-10-07 18:46:23 +0000281 // Create a new node that checks if the value is < pivot. Go to the
282 // left branch if it is and right branch if not.
283 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000284 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattnered922162003-10-07 18:46:23 +0000285
Bob Wilsone4077362013-09-09 19:14:35 +0000286 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000287 Val, Pivot.Low, "Pivot");
Marcello Maggioni78035b12014-07-11 10:34:36 +0000288
289 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
290 NewUpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000291 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000292 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
293 UpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000294 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000295
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000296 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000297 NewNode->getInstList().push_back(Comp);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000298
Gabor Greife9ecc682008-04-06 20:25:17 +0000299 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000300 return NewNode;
301}
302
Sanjay Patel815adac2015-09-16 16:21:08 +0000303/// Create a new leaf block for the binary lookup tree. It checks if the
304/// switch's value == the case's value. If not, then it jumps to the default
305/// branch. At this point in the tree, the value can't be another valid case
306/// value, so the jump to the "default" branch is warranted.
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000307BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnered922162003-10-07 18:46:23 +0000308 BasicBlock* OrigBlock,
Eugene Zelenkofce43572017-10-21 00:57:46 +0000309 BasicBlock* Default) {
Chris Lattnered922162003-10-07 18:46:23 +0000310 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000311 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000312 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000313
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000314 // Emit comparison
Craig Topperf40110f2014-04-25 05:29:35 +0000315 ICmpInst* Comp = nullptr;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000316 if (Leaf.Low == Leaf.High) {
317 // Make the seteq instruction...
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000318 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
319 Leaf.Low, "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000320 } else {
321 // Make range comparison
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000322 if (Leaf.Low->isMinValue(true /*isSigned*/)) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000323 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000324 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
325 "SwitchLeaf");
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000326 } else if (Leaf.Low->isZero()) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000327 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000328 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +0000329 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000330 } else {
331 // Emit V-Lo <=u Hi-Lo
Owen Anderson487375e2009-07-29 18:55:55 +0000332 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000333 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000334 Val->getName()+".off",
335 NewLeaf);
Owen Anderson487375e2009-07-29 18:55:55 +0000336 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000337 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
338 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000339 }
340 }
Chris Lattnered922162003-10-07 18:46:23 +0000341
342 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000343 BasicBlock* Succ = Leaf.BB;
Gabor Greife9ecc682008-04-06 20:25:17 +0000344 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000345
346 // If there were any PHI nodes in this successor, rewrite one entry
347 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000348 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
349 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000350 // Remove all but one incoming entries from the cluster
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000351 uint64_t Range = Leaf.High->getSExtValue() -
352 Leaf.Low->getSExtValue();
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000353 for (uint64_t j = 0; j < Range; ++j) {
354 PN->removeIncomingValue(OrigBlock);
355 }
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +0000356
Chris Lattnered922162003-10-07 18:46:23 +0000357 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
358 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
359 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
360 }
361
362 return NewLeaf;
363}
364
Sanjay Patel815adac2015-09-16 16:21:08 +0000365/// Transform simple list of Cases into list of CaseRange's.
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000366unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Bob Wilsone4077362013-09-09 19:14:35 +0000367 unsigned numCmps = 0;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000368
369 // Start with "simple" cases
Chandler Carruth927d8e62017-04-12 07:27:28 +0000370 for (auto Case : SI->cases())
371 Cases.push_back(CaseRange(Case.getCaseValue(), Case.getCaseValue(),
372 Case.getCaseSuccessor()));
373
Fangrui Song0cac7262018-09-27 02:13:45 +0000374 llvm::sort(Cases, CaseCmp());
Bob Wilsone4077362013-09-09 19:14:35 +0000375
376 // Merge case into clusters
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000377 if (Cases.size() >= 2) {
378 CaseItr I = Cases.begin();
379 for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000380 int64_t nextValue = J->Low->getSExtValue();
381 int64_t currentValue = I->High->getSExtValue();
Bob Wilsone4077362013-09-09 19:14:35 +0000382 BasicBlock* nextBB = J->BB;
383 BasicBlock* currentBB = I->BB;
384
385 // If the two neighboring cases go to the same destination, merge them
386 // into a single case.
Justin Bognere46d3792015-06-20 00:28:25 +0000387 assert(nextValue > currentValue && "Cases should be strictly ascending");
388 if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
Bob Wilsone4077362013-09-09 19:14:35 +0000389 I->High = J->High;
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000390 // FIXME: Combine branch weights.
391 } else if (++I != J) {
392 *I = *J;
Bob Wilsone4077362013-09-09 19:14:35 +0000393 }
394 }
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000395 Cases.erase(std::next(I), Cases.end());
396 }
Bob Wilsone4077362013-09-09 19:14:35 +0000397
398 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
399 if (I->Low != I->High)
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000400 // A range counts double, since it requires two compares.
401 ++numCmps;
402 }
403
Bob Wilsone4077362013-09-09 19:14:35 +0000404 return numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000405}
406
Sanjay Patel815adac2015-09-16 16:21:08 +0000407/// Replace the specified switch instruction with a sequence of chained if-then
408/// insts in a balanced binary search.
Chen Li0786bc92015-08-11 20:16:17 +0000409void LowerSwitch::processSwitchInst(SwitchInst *SI,
410 SmallPtrSetImpl<BasicBlock*> &DeleteList) {
Chris Lattner1b094a02003-04-23 16:23:59 +0000411 BasicBlock *CurBlock = SI->getParent();
412 BasicBlock *OrigBlock = CurBlock;
413 Function *F = CurBlock->getParent();
Eli Friedman95031ed2011-09-29 20:21:17 +0000414 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000415 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000416
Matt Arsenault01d17e72017-04-21 23:54:12 +0000417 // Don't handle unreachable blocks. If there are successors with phis, this
418 // would leave them behind with missing predecessors.
419 if ((CurBlock != &F->getEntryBlock() && pred_empty(CurBlock)) ||
420 CurBlock->getSinglePredecessor() == CurBlock) {
421 DeleteList.insert(CurBlock);
422 return;
423 }
424
Hans Wennborgae9c9712015-01-23 20:43:51 +0000425 // If there is only the default destination, just branch.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000426 if (!SI->getNumCases()) {
Hans Wennborgae9c9712015-01-23 20:43:51 +0000427 BranchInst::Create(Default, CurBlock);
428 SI->eraseFromParent();
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000429 return;
430 }
431
Hans Wennborgae9c9712015-01-23 20:43:51 +0000432 // Prepare cases vector.
433 CaseVector Cases;
434 unsigned numCmps = Clusterify(Cases, SI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000435 LLVM_DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
436 << ". Total compares: " << numCmps << "\n");
437 LLVM_DEBUG(dbgs() << "Cases: " << Cases << "\n");
Hans Wennborgae9c9712015-01-23 20:43:51 +0000438 (void)numCmps;
439
440 ConstantInt *LowerBound = nullptr;
441 ConstantInt *UpperBound = nullptr;
442 std::vector<IntRange> UnreachableRanges;
443
444 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000445 // Make the bounds tightly fitted around the case value range, because we
Hans Wennborgae9c9712015-01-23 20:43:51 +0000446 // know that the value passed to the switch must be exactly one of the case
447 // values.
448 assert(!Cases.empty());
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000449 LowerBound = Cases.front().Low;
450 UpperBound = Cases.back().High;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000451
452 DenseMap<BasicBlock *, unsigned> Popularity;
453 unsigned MaxPop = 0;
454 BasicBlock *PopSucc = nullptr;
455
Eugene Zelenkofce43572017-10-21 00:57:46 +0000456 IntRange R = {std::numeric_limits<int64_t>::min(),
457 std::numeric_limits<int64_t>::max()};
Hans Wennborgae9c9712015-01-23 20:43:51 +0000458 UnreachableRanges.push_back(R);
459 for (const auto &I : Cases) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000460 int64_t Low = I.Low->getSExtValue();
461 int64_t High = I.High->getSExtValue();
Hans Wennborgae9c9712015-01-23 20:43:51 +0000462
463 IntRange &LastRange = UnreachableRanges.back();
464 if (LastRange.Low == Low) {
465 // There is nothing left of the previous range.
466 UnreachableRanges.pop_back();
467 } else {
468 // Terminate the previous range.
469 assert(Low > LastRange.Low);
470 LastRange.High = Low - 1;
471 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000472 if (High != std::numeric_limits<int64_t>::max()) {
473 IntRange R = { High + 1, std::numeric_limits<int64_t>::max() };
Hans Wennborgae9c9712015-01-23 20:43:51 +0000474 UnreachableRanges.push_back(R);
475 }
476
477 // Count popularity.
478 int64_t N = High - Low + 1;
479 unsigned &Pop = Popularity[I.BB];
480 if ((Pop += N) > MaxPop) {
481 MaxPop = Pop;
482 PopSucc = I.BB;
483 }
484 }
485#ifndef NDEBUG
486 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
487 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
488 I != E; ++I) {
489 assert(I->Low <= I->High);
490 auto Next = I + 1;
491 if (Next != E) {
492 assert(Next->Low > I->High);
493 }
494 }
495#endif
496
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +0000497 // As the default block in the switch is unreachable, update the PHI nodes
498 // (remove the entry to the default block) to reflect this.
499 Default->removePredecessor(OrigBlock);
500
Hans Wennborgae9c9712015-01-23 20:43:51 +0000501 // Use the most popular block as the new default, reducing the number of
502 // cases.
503 assert(MaxPop > 0 && PopSucc);
504 Default = PopSucc;
David Majnemerc7004902016-08-12 04:32:37 +0000505 Cases.erase(
Eugene Zelenkofce43572017-10-21 00:57:46 +0000506 llvm::remove_if(
507 Cases, [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
David Majnemerc7004902016-08-12 04:32:37 +0000508 Cases.end());
Hans Wennborgae9c9712015-01-23 20:43:51 +0000509
510 // If there are no cases left, just branch.
511 if (Cases.empty()) {
512 BranchInst::Create(Default, CurBlock);
513 SI->eraseFromParent();
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +0000514 // As all the cases have been replaced with a single branch, only keep
515 // one entry in the PHI nodes.
516 for (unsigned I = 0 ; I < (MaxPop - 1) ; ++I)
517 PopSucc->removePredecessor(OrigBlock);
Hans Wennborgae9c9712015-01-23 20:43:51 +0000518 return;
519 }
520 }
521
Karl-Johan Karlsson11d68a62018-05-22 08:46:48 +0000522 unsigned NrOfDefaults = (SI->getDefaultDest() == Default) ? 1 : 0;
523 for (const auto &Case : SI->cases())
524 if (Case.getCaseSuccessor() == Default)
525 NrOfDefaults++;
526
Chris Lattnered922162003-10-07 18:46:23 +0000527 // Create a new, empty default block so that the new hierarchy of
528 // if-then statements go to this and the PHI nodes are happy.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000529 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000530 F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
Hans Wennborgae9c9712015-01-23 20:43:51 +0000531 BranchInst::Create(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000532
Jim Grosbachfff56632014-06-16 16:55:20 +0000533 BasicBlock *SwitchBlock =
534 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000535 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
Chris Lattnered922162003-10-07 18:46:23 +0000536
Karl-Johan Karlsson11d68a62018-05-22 08:46:48 +0000537 // If there are entries in any PHI nodes for the default edge, make sure
538 // to update them as well.
539 fixPhis(Default, OrigBlock, NewDefault, NrOfDefaults);
540
Chris Lattnered922162003-10-07 18:46:23 +0000541 // Branch to our shiny new if-then stuff...
Gabor Greife9ecc682008-04-06 20:25:17 +0000542 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000543
Chris Lattner1b094a02003-04-23 16:23:59 +0000544 // We are now done with the switch instruction, delete it.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000545 BasicBlock *OldDefault = SI->getDefaultDest();
Chris Lattnerb6865952004-03-14 04:14:31 +0000546 CurBlock->getInstList().erase(SI);
Jim Grosbachfff56632014-06-16 16:55:20 +0000547
Chen Li10f01bd2015-08-11 18:12:26 +0000548 // If the Default block has no more predecessors just add it to DeleteList.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000549 if (pred_begin(OldDefault) == pred_end(OldDefault))
Chen Li0786bc92015-08-11 20:16:17 +0000550 DeleteList.insert(OldDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000551}