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