blob: 9ef694c4cea30a59329d4eb77e4f5c59e1a760e0 [file] [log] [blame]
Chris Lattner14383482003-04-23 16:23:59 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner14383482003-04-23 16:23:59 +00009//
Gordon Henriksenc86b6772007-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 Lattner14383482003-04-23 16:23:59 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/Scalar.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000018#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/LLVMContext.h"
Chris Lattner14383482003-04-23 16:23:59 +000022#include "llvm/Pass.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000023#include "llvm/Support/Compiler.h"
Nick Lewyckyf5a86f42009-10-25 06:57:41 +000024#include "llvm/Support/Debug.h"
Chris Lattner944fac72008-08-23 22:23:09 +000025#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000026#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000027#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Stephen Hinesdce4a402014-05-29 02:49:00 -070030#define DEBUG_TYPE "lower-switch"
31
Chris Lattner14383482003-04-23 16:23:59 +000032namespace {
Chris Lattner14383482003-04-23 16:23:59 +000033 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
Chris Lattner473fc962010-08-18 02:41:56 +000034 /// instructions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000035 class LowerSwitch : public FunctionPass {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000036 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000037 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000038 LowerSwitch() : FunctionPass(ID) {
39 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
40 }
Devang Patel794fd752007-05-01 21:15:47 +000041
Stephen Hines36b56882014-04-23 16:57:46 -070042 bool runOnFunction(Function &F) override;
43
44 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anton Korobeynikovbed29462007-04-16 18:10:23 +000045 // This is a cluster of orthogonal Transforms
Chris Lattner8d89e7b2006-05-09 04:13:41 +000046 AU.addPreserved<UnifyFunctionExitNodes>();
Dan Gohman60493c32010-08-06 21:48:06 +000047 AU.addPreserved("mem2reg");
Chris Lattnered96fe82006-05-17 21:05:27 +000048 AU.addPreservedID(LowerInvokePassID);
Chris Lattner8d89e7b2006-05-09 04:13:41 +000049 }
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000050
51 struct CaseRange {
52 Constant* Low;
53 Constant* High;
54 BasicBlock* BB;
55
Stephen Hinesdce4a402014-05-29 02:49:00 -070056 CaseRange(Constant *low = nullptr, Constant *high = nullptr,
57 BasicBlock *bb = nullptr) :
Jeff Cohenc4558fd2007-03-12 17:56:27 +000058 Low(low), High(high), BB(bb) { }
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000059 };
60
61 typedef std::vector<CaseRange> CaseVector;
62 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnerebbc1a52003-10-07 18:46:23 +000063 private:
Chris Lattner14383482003-04-23 16:23:59 +000064 void processSwitchInst(SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000065
66 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
67 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000068 BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnerebbc1a52003-10-07 18:46:23 +000069 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000070 unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000071 };
Bob Wilsondb3a9e62013-09-09 19:14:35 +000072
73 /// The comparison function for sorting the switch case values in the vector.
74 /// WARNING: Case ranges should be disjoint!
75 struct CaseCmp {
76 bool operator () (const LowerSwitch::CaseRange& C1,
77 const LowerSwitch::CaseRange& C2) {
78
79 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
80 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
81 return CI1->getValue().slt(CI2->getValue());
82 }
83 };
Chris Lattner14383482003-04-23 16:23:59 +000084}
85
Dan Gohman844731a2008-05-13 00:00:25 +000086char LowerSwitch::ID = 0;
Owen Anderson02dd53e2010-08-23 17:52:01 +000087INITIALIZE_PASS(LowerSwitch, "lowerswitch",
Owen Andersonce665bd2010-10-07 22:25:06 +000088 "Lower SwitchInst's to branches", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000089
Chris Lattner7a2bdde2011-04-15 05:18:47 +000090// Publicly exposed interface to pass...
Owen Anderson90c579d2010-08-06 18:33:48 +000091char &llvm::LowerSwitchID = LowerSwitch::ID;
Chris Lattner14383482003-04-23 16:23:59 +000092// createLowerSwitchPass - Interface to this file...
Chris Lattnerd7456022004-01-09 06:02:20 +000093FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner14383482003-04-23 16:23:59 +000094 return new LowerSwitch();
95}
96
97bool LowerSwitch::runOnFunction(Function &F) {
98 bool Changed = false;
99
100 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
101 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
102
103 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
104 Changed = true;
105 processSwitchInst(SI);
106 }
107 }
108
109 return Changed;
110}
111
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000112// operator<< - Used for debugging purposes.
113//
Daniel Dunbar1cd1d982009-07-24 10:36:58 +0000114static raw_ostream& operator<<(raw_ostream &O,
Chandler Carruth100c2672010-10-23 08:10:43 +0000115 const LowerSwitch::CaseVector &C)
116 LLVM_ATTRIBUTE_USED;
Mike Stump66ad89c2009-07-27 23:33:34 +0000117static raw_ostream& operator<<(raw_ostream &O,
Daniel Dunbar1cd1d982009-07-24 10:36:58 +0000118 const LowerSwitch::CaseVector &C) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000119 O << "[";
120
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000121 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattnerd7456022004-01-09 06:02:20 +0000122 E = C.end(); B != E; ) {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000123 O << *B->Low << " -" << *B->High;
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000124 if (++B != E) O << ", ";
125 }
126
127 return O << "]";
128}
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000129
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000130// switchConvert - Convert the switch statement into a binary lookup of
131// the case values. The function recursively builds this tree.
132//
133BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
134 Value* Val, BasicBlock* OrigBlock,
135 BasicBlock* Default)
136{
137 unsigned Size = End - Begin;
138
139 if (Size == 1)
140 return newLeafBlock(*Begin, Val, OrigBlock, Default);
141
142 unsigned Mid = Size / 2;
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000143 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greene0f4c9882010-01-05 01:26:45 +0000144 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000145 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greene0f4c9882010-01-05 01:26:45 +0000146 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000147
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000148 CaseRange& Pivot = *(Begin + Mid);
David Greene0f4c9882010-01-05 01:26:45 +0000149 DEBUG(dbgs() << "Pivot ==> "
Chris Lattner944fac72008-08-23 22:23:09 +0000150 << cast<ConstantInt>(Pivot.Low)->getValue() << " -"
Dan Gohmanf871ccb2009-03-23 15:57:19 +0000151 << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000152
153 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
154 OrigBlock, Default);
155 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
156 OrigBlock, Default);
157
158 // Create a new node that checks if the value is < pivot. Go to the
159 // left branch if it is and right branch if not.
160 Function* F = OrigBlock->getParent();
Owen Anderson1d0be152009-08-13 21:58:54 +0000161 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattner261cdfb2007-04-17 18:09:47 +0000162 Function::iterator FI = OrigBlock;
163 F->getBasicBlockList().insert(++FI, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000164
Bob Wilsondb3a9e62013-09-09 19:14:35 +0000165 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson333c4002009-07-09 23:48:35 +0000166 Val, Pivot.Low, "Pivot");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000167 NewNode->getInstList().push_back(Comp);
Gabor Greif051a9502008-04-06 20:25:17 +0000168 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000169 return NewNode;
170}
171
172// newLeafBlock - Create a new leaf block for the binary lookup tree. It
173// checks if the switch's value == the case's value. If not, then it
174// jumps to the default branch. At this point in the tree, the value
175// can't be another valid case value, so the jump to the "default" branch
176// is warranted.
177//
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000178BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000179 BasicBlock* OrigBlock,
180 BasicBlock* Default)
181{
182 Function* F = OrigBlock->getParent();
Owen Anderson1d0be152009-08-13 21:58:54 +0000183 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Chris Lattner261cdfb2007-04-17 18:09:47 +0000184 Function::iterator FI = OrigBlock;
185 F->getBasicBlockList().insert(++FI, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000186
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000187 // Emit comparison
Stephen Hinesdce4a402014-05-29 02:49:00 -0700188 ICmpInst* Comp = nullptr;
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000189 if (Leaf.Low == Leaf.High) {
190 // Make the seteq instruction...
Owen Anderson333c4002009-07-09 23:48:35 +0000191 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
192 Leaf.Low, "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000193 } else {
194 // Make range comparison
195 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
196 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson333c4002009-07-09 23:48:35 +0000197 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
198 "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000199 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
200 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson333c4002009-07-09 23:48:35 +0000201 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
202 "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000203 } else {
204 // Emit V-Lo <=u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +0000205 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000206 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000207 Val->getName()+".off",
208 NewLeaf);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000209 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson333c4002009-07-09 23:48:35 +0000210 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
211 "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000212 }
213 }
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000214
215 // Make the conditional branch...
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000216 BasicBlock* Succ = Leaf.BB;
Gabor Greif051a9502008-04-06 20:25:17 +0000217 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000218
219 // If there were any PHI nodes in this successor, rewrite one entry
220 // from OrigBlock to come from NewLeaf.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000221 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
222 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000223 // Remove all but one incoming entries from the cluster
224 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
225 cast<ConstantInt>(Leaf.Low)->getSExtValue();
226 for (uint64_t j = 0; j < Range; ++j) {
227 PN->removeIncomingValue(OrigBlock);
228 }
229
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000230 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
231 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
232 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
233 }
234
235 return NewLeaf;
236}
237
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000238// Clusterify - Transform simple list of Cases into list of CaseRange's
239unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Bob Wilsondb3a9e62013-09-09 19:14:35 +0000240 unsigned numCmps = 0;
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000241
242 // Start with "simple" cases
Bob Wilsondb3a9e62013-09-09 19:14:35 +0000243 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
244 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
245 i.getCaseSuccessor()));
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000246
Bob Wilsondb3a9e62013-09-09 19:14:35 +0000247 std::sort(Cases.begin(), Cases.end(), CaseCmp());
248
249 // Merge case into clusters
250 if (Cases.size()>=2)
Stephen Hines36b56882014-04-23 16:57:46 -0700251 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
252 J != Cases.end();) {
Bob Wilsondb3a9e62013-09-09 19:14:35 +0000253 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
254 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
255 BasicBlock* nextBB = J->BB;
256 BasicBlock* currentBB = I->BB;
257
258 // If the two neighboring cases go to the same destination, merge them
259 // into a single case.
260 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
261 I->High = J->High;
262 J = Cases.erase(J);
263 } else {
264 I = J++;
265 }
266 }
267
268 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
269 if (I->Low != I->High)
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000270 // A range counts double, since it requires two compares.
271 ++numCmps;
272 }
273
Bob Wilsondb3a9e62013-09-09 19:14:35 +0000274 return numCmps;
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000275}
276
Chris Lattner14383482003-04-23 16:23:59 +0000277// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000278// of chained if-then insts in a balanced binary search.
Chris Lattner14383482003-04-23 16:23:59 +0000279//
280void LowerSwitch::processSwitchInst(SwitchInst *SI) {
281 BasicBlock *CurBlock = SI->getParent();
282 BasicBlock *OrigBlock = CurBlock;
283 Function *F = CurBlock->getParent();
Eli Friedmanbb5a7442011-09-29 20:21:17 +0000284 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000285 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner14383482003-04-23 16:23:59 +0000286
Chris Lattner44bb5412003-08-23 22:54:34 +0000287 // If there is only the default destination, don't bother with the code below.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +0000288 if (!SI->getNumCases()) {
Gabor Greif051a9502008-04-06 20:25:17 +0000289 BranchInst::Create(SI->getDefaultDest(), CurBlock);
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000290 CurBlock->getInstList().erase(SI);
Chris Lattner44bb5412003-08-23 22:54:34 +0000291 return;
292 }
293
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000294 // Create a new, empty default block so that the new hierarchy of
295 // if-then statements go to this and the PHI nodes are happy.
Owen Anderson1d0be152009-08-13 21:58:54 +0000296 BasicBlock* NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000297 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000298
Gabor Greif051a9502008-04-06 20:25:17 +0000299 BranchInst::Create(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000300
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000301 // If there is an entry in any PHI nodes for the default edge, make sure
302 // to update them as well.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000303 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
304 PHINode *PN = cast<PHINode>(I);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000305 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
306 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
307 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000308 }
309
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000310 // Prepare cases vector.
311 CaseVector Cases;
312 unsigned numCmps = Clusterify(Cases, SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000313
David Greene0f4c9882010-01-05 01:26:45 +0000314 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Dan Gohman6c1980b2009-07-25 01:13:51 +0000315 << ". Total compares: " << numCmps << "\n");
David Greene0f4c9882010-01-05 01:26:45 +0000316 DEBUG(dbgs() << "Cases: " << Cases << "\n");
Mike Stump02efa782009-07-27 23:14:11 +0000317 (void)numCmps;
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000318
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000319 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
320 OrigBlock, NewDefault);
321
322 // Branch to our shiny new if-then stuff...
Gabor Greif051a9502008-04-06 20:25:17 +0000323 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000324
Chris Lattner14383482003-04-23 16:23:59 +0000325 // We are now done with the switch instruction, delete it.
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000326 CurBlock->getInstList().erase(SI);
Chris Lattner14383482003-04-23 16:23:59 +0000327}