blob: 379a2e45703e591a0890495cfcf26346486f78ca [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//
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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner1b094a02003-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 Lattner4fe87d62006-05-09 04:13:41 +000017#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
Chris Lattnered922162003-10-07 18:46:23 +000018#include "llvm/Constants.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000019#include "llvm/Function.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000020#include "llvm/Instructions.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000021#include "llvm/Pass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000022#include "llvm/Support/Debug.h"
23#include "llvm/ADT/Statistic.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000024#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000025#include <iostream>
Chris Lattner49525f82004-01-09 06:02:20 +000026using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000027
Chris Lattner1b094a02003-04-23 16:23:59 +000028namespace {
29 Statistic<> NumLowered("lowerswitch", "Number of SwitchInst's replaced");
30
31 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
32 /// instructions. Note that this cannot be a BasicBlock pass because it
33 /// modifies the CFG!
Chris Lattnered922162003-10-07 18:46:23 +000034 class LowerSwitch : public FunctionPass {
35 public:
Chris Lattner4fe87d62006-05-09 04:13:41 +000036 virtual bool runOnFunction(Function &F);
Chris Lattnere4cb4762006-05-17 21:05:27 +000037
Chris Lattner4fe87d62006-05-09 04:13:41 +000038 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnere4cb4762006-05-17 21:05:27 +000039 // This is a cluster of orthogonal Transforms
Chris Lattner4fe87d62006-05-09 04:13:41 +000040 AU.addPreserved<UnifyFunctionExitNodes>();
41 AU.addPreservedID(PromoteMemoryToRegisterID);
42 AU.addPreservedID(LowerSelectID);
Chris Lattnere4cb4762006-05-17 21:05:27 +000043 AU.addPreservedID(LowerInvokePassID);
44 AU.addPreservedID(LowerAllocationsID);
Chris Lattner4fe87d62006-05-09 04:13:41 +000045 }
Chris Lattnere4cb4762006-05-17 21:05:27 +000046
Chris Lattnered922162003-10-07 18:46:23 +000047 typedef std::pair<Constant*, BasicBlock*> Case;
48 typedef std::vector<Case>::iterator CaseItr;
49 private:
Chris Lattner1b094a02003-04-23 16:23:59 +000050 void processSwitchInst(SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000051
52 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
53 BasicBlock* OrigBlock, BasicBlock* Default);
54 BasicBlock* newLeafBlock(Case& Leaf, Value* Val,
55 BasicBlock* OrigBlock, BasicBlock* Default);
56 };
57
58 /// The comparison function for sorting the switch case values in the vector.
59 struct CaseCmp {
60 bool operator () (const LowerSwitch::Case& C1,
61 const LowerSwitch::Case& C2) {
62 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
63 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
64
65 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
66 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
67 }
Chris Lattner1b094a02003-04-23 16:23:59 +000068 };
69
70 RegisterOpt<LowerSwitch>
71 X("lowerswitch", "Lower SwitchInst's to branches");
72}
73
Chris Lattner2d3a0272006-05-02 04:24:36 +000074// Publically exposed interface to pass...
75const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
Chris Lattner1b094a02003-04-23 16:23:59 +000076// createLowerSwitchPass - Interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +000077FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +000078 return new LowerSwitch();
79}
80
81bool LowerSwitch::runOnFunction(Function &F) {
82 bool Changed = false;
83
84 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
85 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
86
87 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
88 Changed = true;
89 processSwitchInst(SI);
90 }
91 }
92
93 return Changed;
94}
95
Chris Lattnered922162003-10-07 18:46:23 +000096// operator<< - Used for debugging purposes.
97//
Chris Lattner49525f82004-01-09 06:02:20 +000098std::ostream& operator<<(std::ostream &O,
99 const std::vector<LowerSwitch::Case> &C) {
Chris Lattnered922162003-10-07 18:46:23 +0000100 O << "[";
101
Chris Lattner49525f82004-01-09 06:02:20 +0000102 for (std::vector<LowerSwitch::Case>::const_iterator B = C.begin(),
103 E = C.end(); B != E; ) {
Chris Lattnered922162003-10-07 18:46:23 +0000104 O << *B->first;
105 if (++B != E) O << ", ";
106 }
107
108 return O << "]";
109}
110
111// switchConvert - Convert the switch statement into a binary lookup of
112// the case values. The function recursively builds this tree.
113//
114BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
115 Value* Val, BasicBlock* OrigBlock,
116 BasicBlock* Default)
117{
118 unsigned Size = End - Begin;
119
120 if (Size == 1)
121 return newLeafBlock(*Begin, Val, OrigBlock, Default);
122
123 unsigned Mid = Size / 2;
124 std::vector<Case> LHS(Begin, Begin + Mid);
125 DEBUG(std::cerr << "LHS: " << LHS << "\n");
126 std::vector<Case> RHS(Begin + Mid, End);
127 DEBUG(std::cerr << "RHS: " << RHS << "\n");
128
129 Case& Pivot = *(Begin + Mid);
130 DEBUG(std::cerr << "Pivot ==> "
Chris Lattner9c6833c2004-02-25 15:15:04 +0000131 << (int64_t)cast<ConstantInt>(Pivot.first)->getRawValue()
132 << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000133
134 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
135 OrigBlock, Default);
136 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
137 OrigBlock, Default);
138
139 // Create a new node that checks if the value is < pivot. Go to the
140 // left branch if it is and right branch if not.
141 Function* F = OrigBlock->getParent();
142 BasicBlock* NewNode = new BasicBlock("NodeBlock");
143 F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
144
145 SetCondInst* Comp = new SetCondInst(Instruction::SetLT, Val, Pivot.first,
146 "Pivot");
147 NewNode->getInstList().push_back(Comp);
Chris Lattner2af51722003-11-20 18:25:24 +0000148 new BranchInst(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000149 return NewNode;
150}
151
152// newLeafBlock - Create a new leaf block for the binary lookup tree. It
153// checks if the switch's value == the case's value. If not, then it
154// jumps to the default branch. At this point in the tree, the value
155// can't be another valid case value, so the jump to the "default" branch
156// is warranted.
157//
158BasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,
159 BasicBlock* OrigBlock,
160 BasicBlock* Default)
161{
162 Function* F = OrigBlock->getParent();
163 BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
164 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
165
166 // Make the seteq instruction...
167 SetCondInst* Comp = new SetCondInst(Instruction::SetEQ, Val,
168 Leaf.first, "SwitchLeaf");
169 NewLeaf->getInstList().push_back(Comp);
170
171 // Make the conditional branch...
172 BasicBlock* Succ = Leaf.second;
Chris Lattner2af51722003-11-20 18:25:24 +0000173 new BranchInst(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000174
175 // If there were any PHI nodes in this successor, rewrite one entry
176 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000177 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
178 PHINode* PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000179 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
180 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
181 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
182 }
183
184 return NewLeaf;
185}
186
Chris Lattner1b094a02003-04-23 16:23:59 +0000187// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnered922162003-10-07 18:46:23 +0000188// of chained if-then insts in a balanced binary search.
Chris Lattner1b094a02003-04-23 16:23:59 +0000189//
190void LowerSwitch::processSwitchInst(SwitchInst *SI) {
191 BasicBlock *CurBlock = SI->getParent();
192 BasicBlock *OrigBlock = CurBlock;
193 Function *F = CurBlock->getParent();
194 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000195 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000196
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000197 // If there is only the default destination, don't bother with the code below.
198 if (SI->getNumOperands() == 2) {
Chris Lattnera2960002003-11-21 16:52:05 +0000199 new BranchInst(SI->getDefaultDest(), CurBlock);
Chris Lattnerb6865952004-03-14 04:14:31 +0000200 CurBlock->getInstList().erase(SI);
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000201 return;
202 }
203
Chris Lattnered922162003-10-07 18:46:23 +0000204 // Create a new, empty default block so that the new hierarchy of
205 // if-then statements go to this and the PHI nodes are happy.
206 BasicBlock* NewDefault = new BasicBlock("NewDefault");
207 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000208
Chris Lattnera2960002003-11-21 16:52:05 +0000209 new BranchInst(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000210
Chris Lattnered922162003-10-07 18:46:23 +0000211 // If there is an entry in any PHI nodes for the default edge, make sure
212 // to update them as well.
Reid Spencer66149462004-09-15 17:06:42 +0000213 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
214 PHINode *PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000215 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
216 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
217 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000218 }
219
Chris Lattnered922162003-10-07 18:46:23 +0000220 std::vector<Case> Cases;
221
222 // Expand comparisons for all of the non-default cases...
223 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
224 Cases.push_back(Case(SI->getSuccessorValue(i), SI->getSuccessor(i)));
225
226 std::sort(Cases.begin(), Cases.end(), CaseCmp());
227 DEBUG(std::cerr << "Cases: " << Cases << "\n");
228 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
229 OrigBlock, NewDefault);
230
231 // Branch to our shiny new if-then stuff...
Chris Lattnera2960002003-11-21 16:52:05 +0000232 new BranchInst(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000233
Chris Lattner1b094a02003-04-23 16:23:59 +0000234 // We are now done with the switch instruction, delete it.
Chris Lattnerb6865952004-03-14 04:14:31 +0000235 CurBlock->getInstList().erase(SI);
Chris Lattner1b094a02003-04-23 16:23:59 +0000236}