LowerSwitch.cpp revision 261cdfbe5e6e11d56ca1c49a75f26fece3b139c8
1//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
2//
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//===----------------------------------------------------------------------===//
9//
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"
17#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
18#include "llvm/Constants.h"
19#include "llvm/Function.h"
20#include "llvm/Instructions.h"
21#include "llvm/Pass.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/Support/Compiler.h"
24#include <algorithm>
25using namespace llvm;
26
27namespace {
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!
31  class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
32  public:
33    virtual bool runOnFunction(Function &F);
34
35    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
36      // This is a cluster of orthogonal Transforms
37      AU.addPreserved<UnifyFunctionExitNodes>();
38      AU.addPreservedID(PromoteMemoryToRegisterID);
39      AU.addPreservedID(LowerSelectID);
40      AU.addPreservedID(LowerInvokePassID);
41      AU.addPreservedID(LowerAllocationsID);
42    }
43
44    struct CaseRange {
45      Constant* Low;
46      Constant* High;
47      BasicBlock* BB;
48
49      CaseRange() : Low(0), High(0), BB(0) { }
50      CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
51        Low(low), High(high), BB(bb) { }
52    };
53
54    typedef std::vector<CaseRange>           CaseVector;
55    typedef std::vector<CaseRange>::iterator CaseItr;
56  private:
57    void processSwitchInst(SwitchInst *SI);
58
59    BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
60                              BasicBlock* OrigBlock, BasicBlock* Default);
61    BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
62                             BasicBlock* OrigBlock, BasicBlock* Default);
63    unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
64  };
65
66  /// The comparison function for sorting the switch case values in the vector.
67  /// WARNING: Case ranges should be disjoint!
68  struct CaseCmp {
69    bool operator () (const LowerSwitch::CaseRange& C1,
70                      const LowerSwitch::CaseRange& C2) {
71
72      const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
73      const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
74      return CI1->getValue().slt(CI2->getValue());
75    }
76  };
77
78  RegisterPass<LowerSwitch>
79  X("lowerswitch", "Lower SwitchInst's to branches");
80}
81
82// Publically exposed interface to pass...
83const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
84// createLowerSwitchPass - Interface to this file...
85FunctionPass *llvm::createLowerSwitchPass() {
86  return new LowerSwitch();
87}
88
89bool LowerSwitch::runOnFunction(Function &F) {
90  bool Changed = false;
91
92  for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
93    BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
94
95    if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
96      Changed = true;
97      processSwitchInst(SI);
98    }
99  }
100
101  return Changed;
102}
103
104// operator<< - Used for debugging purposes.
105//
106static std::ostream& operator<<(std::ostream &O,
107                                const LowerSwitch::CaseVector &C) {
108  O << "[";
109
110  for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
111         E = C.end(); B != E; ) {
112    O << *B->Low << " -" << *B->High;
113    if (++B != E) O << ", ";
114  }
115
116  return O << "]";
117}
118
119static OStream& operator<<(OStream &O, const LowerSwitch::CaseVector &C) {
120  if (O.stream()) *O.stream() << C;
121  return O;
122}
123
124// switchConvert - Convert the switch statement into a binary lookup of
125// the case values. The function recursively builds this tree.
126//
127BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
128                                       Value* Val, BasicBlock* OrigBlock,
129                                       BasicBlock* Default)
130{
131  unsigned Size = End - Begin;
132
133  if (Size == 1)
134    return newLeafBlock(*Begin, Val, OrigBlock, Default);
135
136  unsigned Mid = Size / 2;
137  std::vector<CaseRange> LHS(Begin, Begin + Mid);
138  DOUT << "LHS: " << LHS << "\n";
139  std::vector<CaseRange> RHS(Begin + Mid, End);
140  DOUT << "RHS: " << RHS << "\n";
141
142  CaseRange& Pivot = *(Begin + Mid);
143  DEBUG( DOUT << "Pivot ==> "
144              << cast<ConstantInt>(Pivot.Low)->getValue().toStringSigned(10)
145              << " -"
146              << cast<ConstantInt>(Pivot.High)->getValue().toStringSigned(10)
147              << "\n");
148
149  BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
150                                      OrigBlock, Default);
151  BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
152                                      OrigBlock, Default);
153
154  // Create a new node that checks if the value is < pivot. Go to the
155  // left branch if it is and right branch if not.
156  Function* F = OrigBlock->getParent();
157  BasicBlock* NewNode = new BasicBlock("NodeBlock");
158  Function::iterator FI = OrigBlock;
159  F->getBasicBlockList().insert(++FI, NewNode);
160
161  ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT, Val, Pivot.Low, "Pivot");
162  NewNode->getInstList().push_back(Comp);
163  new BranchInst(LBranch, RBranch, Comp, NewNode);
164  return NewNode;
165}
166
167// newLeafBlock - Create a new leaf block for the binary lookup tree. It
168// checks if the switch's value == the case's value. If not, then it
169// jumps to the default branch. At this point in the tree, the value
170// can't be another valid case value, so the jump to the "default" branch
171// is warranted.
172//
173BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
174                                      BasicBlock* OrigBlock,
175                                      BasicBlock* Default)
176{
177  Function* F = OrigBlock->getParent();
178  BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
179  Function::iterator FI = OrigBlock;
180  F->getBasicBlockList().insert(++FI, NewLeaf);
181
182  // Emit comparison
183  ICmpInst* Comp = NULL;
184  if (Leaf.Low == Leaf.High) {
185    // Make the seteq instruction...
186    Comp = new ICmpInst(ICmpInst::ICMP_EQ, Val, Leaf.Low,
187                        "SwitchLeaf", NewLeaf);
188  } else {
189    // Make range comparison
190    if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
191      // Val >= Min && Val <= Hi --> Val <= Hi
192      Comp = new ICmpInst(ICmpInst::ICMP_SLE, Val, Leaf.High,
193                          "SwitchLeaf", NewLeaf);
194    } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
195      // Val >= 0 && Val <= Hi --> Val <=u Hi
196      Comp = new ICmpInst(ICmpInst::ICMP_ULE, Val, Leaf.High,
197                          "SwitchLeaf", NewLeaf);
198    } else {
199      // Emit V-Lo <=u Hi-Lo
200      Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
201      Instruction* Add = BinaryOperator::createAdd(Val, NegLo,
202                                                   Val->getName()+".off",
203                                                   NewLeaf);
204      Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
205      Comp = new ICmpInst(ICmpInst::ICMP_ULE, Add, UpperBound,
206                          "SwitchLeaf", NewLeaf);
207    }
208  }
209
210  // Make the conditional branch...
211  BasicBlock* Succ = Leaf.BB;
212  new BranchInst(Succ, Default, Comp, NewLeaf);
213
214  // If there were any PHI nodes in this successor, rewrite one entry
215  // from OrigBlock to come from NewLeaf.
216  for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
217    PHINode* PN = cast<PHINode>(I);
218    // Remove all but one incoming entries from the cluster
219    uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
220                     cast<ConstantInt>(Leaf.Low)->getSExtValue();
221    for (uint64_t j = 0; j < Range; ++j) {
222      PN->removeIncomingValue(OrigBlock);
223    }
224
225    int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
226    assert(BlockIdx != -1 && "Switch didn't go to this successor??");
227    PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
228  }
229
230  return NewLeaf;
231}
232
233// Clusterify - Transform simple list of Cases into list of CaseRange's
234unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
235  unsigned numCmps = 0;
236
237  // Start with "simple" cases
238  for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
239    Cases.push_back(CaseRange(SI->getSuccessorValue(i),
240                              SI->getSuccessorValue(i),
241                              SI->getSuccessor(i)));
242  sort(Cases.begin(), Cases.end(), CaseCmp());
243
244  // Merge case into clusters
245  if (Cases.size()>=2)
246    for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
247      int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
248      int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
249      BasicBlock* nextBB = J->BB;
250      BasicBlock* currentBB = I->BB;
251
252      // If the two neighboring cases go to the same destination, merge them
253      // into a single case.
254      if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
255        I->High = J->High;
256        J = Cases.erase(J);
257      } else {
258        I = J++;
259      }
260    }
261
262  for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
263    if (I->Low != I->High)
264      // A range counts double, since it requires two compares.
265      ++numCmps;
266  }
267
268  return numCmps;
269}
270
271// processSwitchInst - Replace the specified switch instruction with a sequence
272// of chained if-then insts in a balanced binary search.
273//
274void LowerSwitch::processSwitchInst(SwitchInst *SI) {
275  BasicBlock *CurBlock = SI->getParent();
276  BasicBlock *OrigBlock = CurBlock;
277  Function *F = CurBlock->getParent();
278  Value *Val = SI->getOperand(0);  // The value we are switching on...
279  BasicBlock* Default = SI->getDefaultDest();
280
281  // If there is only the default destination, don't bother with the code below.
282  if (SI->getNumOperands() == 2) {
283    new BranchInst(SI->getDefaultDest(), CurBlock);
284    CurBlock->getInstList().erase(SI);
285    return;
286  }
287
288  // Create a new, empty default block so that the new hierarchy of
289  // if-then statements go to this and the PHI nodes are happy.
290  BasicBlock* NewDefault = new BasicBlock("NewDefault");
291  F->getBasicBlockList().insert(Default, NewDefault);
292
293  new BranchInst(Default, NewDefault);
294
295  // If there is an entry in any PHI nodes for the default edge, make sure
296  // to update them as well.
297  for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
298    PHINode *PN = cast<PHINode>(I);
299    int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
300    assert(BlockIdx != -1 && "Switch didn't go to this successor??");
301    PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
302  }
303
304  // Prepare cases vector.
305  CaseVector Cases;
306  unsigned numCmps = Clusterify(Cases, SI);
307
308  DOUT << "Clusterify finished. Total clusters: " << Cases.size()
309       << ". Total compares: " << numCmps << "\n";
310  DOUT << "Cases: " << Cases << "\n";
311
312  BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
313                                          OrigBlock, NewDefault);
314
315  // Branch to our shiny new if-then stuff...
316  new BranchInst(SwitchBlock, OrigBlock);
317
318  // We are now done with the switch instruction, delete it.
319  CurBlock->getInstList().erase(SI);
320}
321