blob: 710188aa2b6bc2cf6fab4e3b93d6e567cb817f55 [file] [log] [blame]
Chris Lattner14383482003-04-23 16:23:59 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner14383482003-04-23 16:23:59 +00009//
10// The LowerSwitch transformation rewrites switch statements with a sequence of
11// branches, which allows targets to get away with not implementing the switch
12// statement until it is convenient.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/Scalar.h"
Chris Lattnerebbc1a52003-10-07 18:46:23 +000017#include "llvm/Constants.h"
Chris Lattner14383482003-04-23 16:23:59 +000018#include "llvm/Function.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000019#include "llvm/Instructions.h"
Chris Lattner14383482003-04-23 16:23:59 +000020#include "llvm/Pass.h"
Chris Lattnerebbc1a52003-10-07 18:46:23 +000021#include "Support/Debug.h"
Chris Lattner14383482003-04-23 16:23:59 +000022#include "Support/Statistic.h"
Chris Lattnerd7456022004-01-09 06:02:20 +000023using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000024
Chris Lattner14383482003-04-23 16:23:59 +000025namespace {
26 Statistic<> NumLowered("lowerswitch", "Number of SwitchInst's replaced");
27
28 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
29 /// instructions. Note that this cannot be a BasicBlock pass because it
30 /// modifies the CFG!
Chris Lattnerebbc1a52003-10-07 18:46:23 +000031 class LowerSwitch : public FunctionPass {
32 public:
Chris Lattner14383482003-04-23 16:23:59 +000033 bool runOnFunction(Function &F);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000034 typedef std::pair<Constant*, BasicBlock*> Case;
35 typedef std::vector<Case>::iterator CaseItr;
36 private:
Chris Lattner14383482003-04-23 16:23:59 +000037 void processSwitchInst(SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000038
39 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
40 BasicBlock* OrigBlock, BasicBlock* Default);
41 BasicBlock* newLeafBlock(Case& Leaf, Value* Val,
42 BasicBlock* OrigBlock, BasicBlock* Default);
43 };
44
45 /// The comparison function for sorting the switch case values in the vector.
46 struct CaseCmp {
47 bool operator () (const LowerSwitch::Case& C1,
48 const LowerSwitch::Case& C2) {
49 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
50 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
51
52 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
53 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
54 }
Chris Lattner14383482003-04-23 16:23:59 +000055 };
56
57 RegisterOpt<LowerSwitch>
58 X("lowerswitch", "Lower SwitchInst's to branches");
59}
60
61// createLowerSwitchPass - Interface to this file...
Chris Lattnerd7456022004-01-09 06:02:20 +000062FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner14383482003-04-23 16:23:59 +000063 return new LowerSwitch();
64}
65
66bool LowerSwitch::runOnFunction(Function &F) {
67 bool Changed = false;
68
69 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
70 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
71
72 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
73 Changed = true;
74 processSwitchInst(SI);
75 }
76 }
77
78 return Changed;
79}
80
Chris Lattnerebbc1a52003-10-07 18:46:23 +000081// operator<< - Used for debugging purposes.
82//
Chris Lattnerd7456022004-01-09 06:02:20 +000083std::ostream& operator<<(std::ostream &O,
84 const std::vector<LowerSwitch::Case> &C) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000085 O << "[";
86
Chris Lattnerd7456022004-01-09 06:02:20 +000087 for (std::vector<LowerSwitch::Case>::const_iterator B = C.begin(),
88 E = C.end(); B != E; ) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000089 O << *B->first;
90 if (++B != E) O << ", ";
91 }
92
93 return O << "]";
94}
95
96// switchConvert - Convert the switch statement into a binary lookup of
97// the case values. The function recursively builds this tree.
98//
99BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
100 Value* Val, BasicBlock* OrigBlock,
101 BasicBlock* Default)
102{
103 unsigned Size = End - Begin;
104
105 if (Size == 1)
106 return newLeafBlock(*Begin, Val, OrigBlock, Default);
107
108 unsigned Mid = Size / 2;
109 std::vector<Case> LHS(Begin, Begin + Mid);
110 DEBUG(std::cerr << "LHS: " << LHS << "\n");
111 std::vector<Case> RHS(Begin + Mid, End);
112 DEBUG(std::cerr << "RHS: " << RHS << "\n");
113
114 Case& Pivot = *(Begin + Mid);
115 DEBUG(std::cerr << "Pivot ==> "
Chris Lattner940ff562004-02-25 15:15:04 +0000116 << (int64_t)cast<ConstantInt>(Pivot.first)->getRawValue()
117 << "\n");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000118
119 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
120 OrigBlock, Default);
121 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
122 OrigBlock, Default);
123
124 // Create a new node that checks if the value is < pivot. Go to the
125 // left branch if it is and right branch if not.
126 Function* F = OrigBlock->getParent();
127 BasicBlock* NewNode = new BasicBlock("NodeBlock");
128 F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
129
130 SetCondInst* Comp = new SetCondInst(Instruction::SetLT, Val, Pivot.first,
131 "Pivot");
132 NewNode->getInstList().push_back(Comp);
Chris Lattnerf8485c62003-11-20 18:25:24 +0000133 new BranchInst(LBranch, RBranch, Comp, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000134 return NewNode;
135}
136
137// newLeafBlock - Create a new leaf block for the binary lookup tree. It
138// checks if the switch's value == the case's value. If not, then it
139// jumps to the default branch. At this point in the tree, the value
140// can't be another valid case value, so the jump to the "default" branch
141// is warranted.
142//
143BasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,
144 BasicBlock* OrigBlock,
145 BasicBlock* Default)
146{
147 Function* F = OrigBlock->getParent();
148 BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
149 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
150
151 // Make the seteq instruction...
152 SetCondInst* Comp = new SetCondInst(Instruction::SetEQ, Val,
153 Leaf.first, "SwitchLeaf");
154 NewLeaf->getInstList().push_back(Comp);
155
156 // Make the conditional branch...
157 BasicBlock* Succ = Leaf.second;
Chris Lattnerf8485c62003-11-20 18:25:24 +0000158 new BranchInst(Succ, Default, Comp, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000159
160 // If there were any PHI nodes in this successor, rewrite one entry
161 // from OrigBlock to come from NewLeaf.
162 for (BasicBlock::iterator I = Succ->begin();
163 PHINode* PN = dyn_cast<PHINode>(I); ++I) {
164 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
165 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
166 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
167 }
168
169 return NewLeaf;
170}
171
Chris Lattner14383482003-04-23 16:23:59 +0000172// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000173// of chained if-then insts in a balanced binary search.
Chris Lattner14383482003-04-23 16:23:59 +0000174//
175void LowerSwitch::processSwitchInst(SwitchInst *SI) {
176 BasicBlock *CurBlock = SI->getParent();
177 BasicBlock *OrigBlock = CurBlock;
178 Function *F = CurBlock->getParent();
179 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000180 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner14383482003-04-23 16:23:59 +0000181
Chris Lattner44bb5412003-08-23 22:54:34 +0000182 // If there is only the default destination, don't bother with the code below.
183 if (SI->getNumOperands() == 2) {
Chris Lattner108e4ab2003-11-21 16:52:05 +0000184 new BranchInst(SI->getDefaultDest(), CurBlock);
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000185 CurBlock->getInstList().erase(SI);
Chris Lattner44bb5412003-08-23 22:54:34 +0000186 return;
187 }
188
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000189 // Create a new, empty default block so that the new hierarchy of
190 // if-then statements go to this and the PHI nodes are happy.
191 BasicBlock* NewDefault = new BasicBlock("NewDefault");
192 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000193
Chris Lattner108e4ab2003-11-21 16:52:05 +0000194 new BranchInst(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000195
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000196 // If there is an entry in any PHI nodes for the default edge, make sure
197 // to update them as well.
198 for (BasicBlock::iterator I = Default->begin();
199 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
200 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
201 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
202 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000203 }
204
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000205 std::vector<Case> Cases;
206
207 // Expand comparisons for all of the non-default cases...
208 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
209 Cases.push_back(Case(SI->getSuccessorValue(i), SI->getSuccessor(i)));
210
211 std::sort(Cases.begin(), Cases.end(), CaseCmp());
212 DEBUG(std::cerr << "Cases: " << Cases << "\n");
213 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
214 OrigBlock, NewDefault);
215
216 // Branch to our shiny new if-then stuff...
Chris Lattner108e4ab2003-11-21 16:52:05 +0000217 new BranchInst(SwitchBlock, OrigBlock);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000218
Chris Lattner14383482003-04-23 16:23:59 +0000219 // We are now done with the switch instruction, delete it.
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000220 CurBlock->getInstList().erase(SI);
Chris Lattner14383482003-04-23 16:23:59 +0000221}