LowerSwitch.cpp revision c4558fde76bdb17bff28375fe20ee02e027095b8
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 F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode); 159 160 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT, Val, Pivot.Low, "Pivot"); 161 NewNode->getInstList().push_back(Comp); 162 new BranchInst(LBranch, RBranch, Comp, NewNode); 163 return NewNode; 164} 165 166// newLeafBlock - Create a new leaf block for the binary lookup tree. It 167// checks if the switch's value == the case's value. If not, then it 168// jumps to the default branch. At this point in the tree, the value 169// can't be another valid case value, so the jump to the "default" branch 170// is warranted. 171// 172BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val, 173 BasicBlock* OrigBlock, 174 BasicBlock* Default) 175{ 176 Function* F = OrigBlock->getParent(); 177 BasicBlock* NewLeaf = new BasicBlock("LeafBlock"); 178 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf); 179 180 // Emit comparison 181 ICmpInst* Comp = NULL; 182 if (Leaf.Low == Leaf.High) { 183 // Make the seteq instruction... 184 Comp = new ICmpInst(ICmpInst::ICMP_EQ, Val, Leaf.Low, 185 "SwitchLeaf", NewLeaf); 186 } else { 187 // Make range comparison 188 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) { 189 // Val >= Min && Val <= Hi --> Val <= Hi 190 Comp = new ICmpInst(ICmpInst::ICMP_SLE, Val, Leaf.High, 191 "SwitchLeaf", NewLeaf); 192 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) { 193 // Val >= 0 && Val <= Hi --> Val <=u Hi 194 Comp = new ICmpInst(ICmpInst::ICMP_ULE, Val, Leaf.High, 195 "SwitchLeaf", NewLeaf); 196 } else { 197 // Emit V-Lo <=u Hi-Lo 198 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low); 199 Instruction* Add = BinaryOperator::createAdd(Val, NegLo, 200 Val->getName()+".off", 201 NewLeaf); 202 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High); 203 Comp = new ICmpInst(ICmpInst::ICMP_ULE, Add, UpperBound, 204 "SwitchLeaf", NewLeaf); 205 } 206 } 207 208 // Make the conditional branch... 209 BasicBlock* Succ = Leaf.BB; 210 new BranchInst(Succ, Default, Comp, NewLeaf); 211 212 // If there were any PHI nodes in this successor, rewrite one entry 213 // from OrigBlock to come from NewLeaf. 214 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 215 PHINode* PN = cast<PHINode>(I); 216 // Remove all but one incoming entries from the cluster 217 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() - 218 cast<ConstantInt>(Leaf.Low)->getSExtValue(); 219 for (uint64_t j = 0; j < Range; ++j) { 220 PN->removeIncomingValue(OrigBlock); 221 } 222 223 int BlockIdx = PN->getBasicBlockIndex(OrigBlock); 224 assert(BlockIdx != -1 && "Switch didn't go to this successor??"); 225 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf); 226 } 227 228 return NewLeaf; 229} 230 231// Clusterify - Transform simple list of Cases into list of CaseRange's 232unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) { 233 unsigned numCmps = 0; 234 235 // Start with "simple" cases 236 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i) 237 Cases.push_back(CaseRange(SI->getSuccessorValue(i), 238 SI->getSuccessorValue(i), 239 SI->getSuccessor(i))); 240 sort(Cases.begin(), Cases.end(), CaseCmp()); 241 242 // Merge case into clusters 243 if (Cases.size()>=2) 244 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) { 245 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue(); 246 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue(); 247 BasicBlock* nextBB = J->BB; 248 BasicBlock* currentBB = I->BB; 249 250 // If the two neighboring cases go to the same destination, merge them 251 // into a single case. 252 if ((nextValue-currentValue==1) && (currentBB == nextBB)) { 253 I->High = J->High; 254 J = Cases.erase(J); 255 } else { 256 I = J++; 257 } 258 } 259 260 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) { 261 if (I->Low != I->High) 262 // A range counts double, since it requires two compares. 263 ++numCmps; 264 } 265 266 return numCmps; 267} 268 269// processSwitchInst - Replace the specified switch instruction with a sequence 270// of chained if-then insts in a balanced binary search. 271// 272void LowerSwitch::processSwitchInst(SwitchInst *SI) { 273 BasicBlock *CurBlock = SI->getParent(); 274 BasicBlock *OrigBlock = CurBlock; 275 Function *F = CurBlock->getParent(); 276 Value *Val = SI->getOperand(0); // The value we are switching on... 277 BasicBlock* Default = SI->getDefaultDest(); 278 279 // If there is only the default destination, don't bother with the code below. 280 if (SI->getNumOperands() == 2) { 281 new BranchInst(SI->getDefaultDest(), CurBlock); 282 CurBlock->getInstList().erase(SI); 283 return; 284 } 285 286 // Create a new, empty default block so that the new hierarchy of 287 // if-then statements go to this and the PHI nodes are happy. 288 BasicBlock* NewDefault = new BasicBlock("NewDefault"); 289 F->getBasicBlockList().insert(Default, NewDefault); 290 291 new BranchInst(Default, NewDefault); 292 293 // If there is an entry in any PHI nodes for the default edge, make sure 294 // to update them as well. 295 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) { 296 PHINode *PN = cast<PHINode>(I); 297 int BlockIdx = PN->getBasicBlockIndex(OrigBlock); 298 assert(BlockIdx != -1 && "Switch didn't go to this successor??"); 299 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault); 300 } 301 302 // Prepare cases vector. 303 CaseVector Cases; 304 unsigned numCmps = Clusterify(Cases, SI); 305 306 DOUT << "Clusterify finished. Total clusters: " << Cases.size() 307 << ". Total compares: " << numCmps << "\n"; 308 DOUT << "Cases: " << Cases << "\n"; 309 310 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val, 311 OrigBlock, NewDefault); 312 313 // Branch to our shiny new if-then stuff... 314 new BranchInst(SwitchBlock, OrigBlock); 315 316 // We are now done with the switch instruction, delete it. 317 CurBlock->getInstList().erase(SI); 318} 319