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/CFG.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/Function.h" 21 #include "llvm/IR/Instructions.h" 22 #include "llvm/IR/LLVMContext.h" 23 #include "llvm/Pass.h" 24 #include "llvm/Support/Compiler.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 28 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h" 29 #include <algorithm> 30 using namespace llvm; 31 32 #define DEBUG_TYPE "lower-switch" 33 34 namespace { 35 struct IntRange { 36 int64_t Low, High; 37 }; 38 // Return true iff R is covered by Ranges. 39 static bool IsInRanges(const IntRange &R, 40 const std::vector<IntRange> &Ranges) { 41 // Note: Ranges must be sorted, non-overlapping and non-adjacent. 42 43 // Find the first range whose High field is >= R.High, 44 // then check if the Low field is <= R.Low. If so, we 45 // have a Range that covers R. 46 auto I = std::lower_bound( 47 Ranges.begin(), Ranges.end(), R, 48 [](const IntRange &A, const IntRange &B) { return A.High < B.High; }); 49 return I != Ranges.end() && I->Low <= R.Low; 50 } 51 52 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch 53 /// instructions. 54 class LowerSwitch : public FunctionPass { 55 public: 56 static char ID; // Pass identification, replacement for typeid 57 LowerSwitch() : FunctionPass(ID) { 58 initializeLowerSwitchPass(*PassRegistry::getPassRegistry()); 59 } 60 61 bool runOnFunction(Function &F) override; 62 63 void getAnalysisUsage(AnalysisUsage &AU) const override { 64 // This is a cluster of orthogonal Transforms 65 AU.addPreserved<UnifyFunctionExitNodes>(); 66 AU.addPreservedID(LowerInvokePassID); 67 } 68 69 struct CaseRange { 70 ConstantInt* Low; 71 ConstantInt* High; 72 BasicBlock* BB; 73 74 CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb) 75 : Low(low), High(high), BB(bb) {} 76 }; 77 78 typedef std::vector<CaseRange> CaseVector; 79 typedef std::vector<CaseRange>::iterator CaseItr; 80 private: 81 void processSwitchInst(SwitchInst *SI, SmallPtrSetImpl<BasicBlock*> &DeleteList); 82 83 BasicBlock *switchConvert(CaseItr Begin, CaseItr End, 84 ConstantInt *LowerBound, ConstantInt *UpperBound, 85 Value *Val, BasicBlock *Predecessor, 86 BasicBlock *OrigBlock, BasicBlock *Default, 87 const std::vector<IntRange> &UnreachableRanges); 88 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock, 89 BasicBlock *Default); 90 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI); 91 }; 92 93 /// The comparison function for sorting the switch case values in the vector. 94 /// WARNING: Case ranges should be disjoint! 95 struct CaseCmp { 96 bool operator () (const LowerSwitch::CaseRange& C1, 97 const LowerSwitch::CaseRange& C2) { 98 99 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low); 100 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High); 101 return CI1->getValue().slt(CI2->getValue()); 102 } 103 }; 104 } 105 106 char LowerSwitch::ID = 0; 107 INITIALIZE_PASS(LowerSwitch, "lowerswitch", 108 "Lower SwitchInst's to branches", false, false) 109 110 // Publicly exposed interface to pass... 111 char &llvm::LowerSwitchID = LowerSwitch::ID; 112 // createLowerSwitchPass - Interface to this file... 113 FunctionPass *llvm::createLowerSwitchPass() { 114 return new LowerSwitch(); 115 } 116 117 bool LowerSwitch::runOnFunction(Function &F) { 118 bool Changed = false; 119 SmallPtrSet<BasicBlock*, 8> DeleteList; 120 121 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) { 122 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks 123 124 // If the block is a dead Default block that will be deleted later, don't 125 // waste time processing it. 126 if (DeleteList.count(Cur)) 127 continue; 128 129 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) { 130 Changed = true; 131 processSwitchInst(SI, DeleteList); 132 } 133 } 134 135 for (BasicBlock* BB: DeleteList) { 136 DeleteDeadBlock(BB); 137 } 138 139 return Changed; 140 } 141 142 // operator<< - Used for debugging purposes. 143 // 144 static raw_ostream& operator<<(raw_ostream &O, 145 const LowerSwitch::CaseVector &C) 146 LLVM_ATTRIBUTE_USED; 147 static raw_ostream& operator<<(raw_ostream &O, 148 const LowerSwitch::CaseVector &C) { 149 O << "["; 150 151 for (LowerSwitch::CaseVector::const_iterator B = C.begin(), 152 E = C.end(); B != E; ) { 153 O << *B->Low << " -" << *B->High; 154 if (++B != E) O << ", "; 155 } 156 157 return O << "]"; 158 } 159 160 // \brief Update the first occurrence of the "switch statement" BB in the PHI 161 // node with the "new" BB. The other occurrences will: 162 // 163 // 1) Be updated by subsequent calls to this function. Switch statements may 164 // have more than one outcoming edge into the same BB if they all have the same 165 // value. When the switch statement is converted these incoming edges are now 166 // coming from multiple BBs. 167 // 2) Removed if subsequent incoming values now share the same case, i.e., 168 // multiple outcome edges are condensed into one. This is necessary to keep the 169 // number of phi values equal to the number of branches to SuccBB. 170 static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB, 171 unsigned NumMergedCases) { 172 for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI(); 173 I != IE; ++I) { 174 PHINode *PN = cast<PHINode>(I); 175 176 // Only update the first occurrence. 177 unsigned Idx = 0, E = PN->getNumIncomingValues(); 178 unsigned LocalNumMergedCases = NumMergedCases; 179 for (; Idx != E; ++Idx) { 180 if (PN->getIncomingBlock(Idx) == OrigBB) { 181 PN->setIncomingBlock(Idx, NewBB); 182 break; 183 } 184 } 185 186 // Remove additional occurrences coming from condensed cases and keep the 187 // number of incoming values equal to the number of branches to SuccBB. 188 SmallVector<unsigned, 8> Indices; 189 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx) 190 if (PN->getIncomingBlock(Idx) == OrigBB) { 191 Indices.push_back(Idx); 192 LocalNumMergedCases--; 193 } 194 // Remove incoming values in the reverse order to prevent invalidating 195 // *successive* index. 196 for (auto III = Indices.rbegin(), IIE = Indices.rend(); III != IIE; ++III) 197 PN->removeIncomingValue(*III); 198 } 199 } 200 201 // switchConvert - Convert the switch statement into a binary lookup of 202 // the case values. The function recursively builds this tree. 203 // LowerBound and UpperBound are used to keep track of the bounds for Val 204 // that have already been checked by a block emitted by one of the previous 205 // calls to switchConvert in the call stack. 206 BasicBlock * 207 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound, 208 ConstantInt *UpperBound, Value *Val, 209 BasicBlock *Predecessor, BasicBlock *OrigBlock, 210 BasicBlock *Default, 211 const std::vector<IntRange> &UnreachableRanges) { 212 unsigned Size = End - Begin; 213 214 if (Size == 1) { 215 // Check if the Case Range is perfectly squeezed in between 216 // already checked Upper and Lower bounds. If it is then we can avoid 217 // emitting the code that checks if the value actually falls in the range 218 // because the bounds already tell us so. 219 if (Begin->Low == LowerBound && Begin->High == UpperBound) { 220 unsigned NumMergedCases = 0; 221 if (LowerBound && UpperBound) 222 NumMergedCases = 223 UpperBound->getSExtValue() - LowerBound->getSExtValue(); 224 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases); 225 return Begin->BB; 226 } 227 return newLeafBlock(*Begin, Val, OrigBlock, Default); 228 } 229 230 unsigned Mid = Size / 2; 231 std::vector<CaseRange> LHS(Begin, Begin + Mid); 232 DEBUG(dbgs() << "LHS: " << LHS << "\n"); 233 std::vector<CaseRange> RHS(Begin + Mid, End); 234 DEBUG(dbgs() << "RHS: " << RHS << "\n"); 235 236 CaseRange &Pivot = *(Begin + Mid); 237 DEBUG(dbgs() << "Pivot ==> " 238 << Pivot.Low->getValue() 239 << " -" << Pivot.High->getValue() << "\n"); 240 241 // NewLowerBound here should never be the integer minimal value. 242 // This is because it is computed from a case range that is never 243 // the smallest, so there is always a case range that has at least 244 // a smaller value. 245 ConstantInt *NewLowerBound = Pivot.Low; 246 247 // Because NewLowerBound is never the smallest representable integer 248 // it is safe here to subtract one. 249 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(), 250 NewLowerBound->getValue() - 1); 251 252 if (!UnreachableRanges.empty()) { 253 // Check if the gap between LHS's highest and NewLowerBound is unreachable. 254 int64_t GapLow = LHS.back().High->getSExtValue() + 1; 255 int64_t GapHigh = NewLowerBound->getSExtValue() - 1; 256 IntRange Gap = { GapLow, GapHigh }; 257 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges)) 258 NewUpperBound = LHS.back().High; 259 } 260 261 DEBUG(dbgs() << "LHS Bounds ==> "; 262 if (LowerBound) { 263 dbgs() << LowerBound->getSExtValue(); 264 } else { 265 dbgs() << "NONE"; 266 } 267 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n"; 268 dbgs() << "RHS Bounds ==> "; 269 dbgs() << NewLowerBound->getSExtValue() << " - "; 270 if (UpperBound) { 271 dbgs() << UpperBound->getSExtValue() << "\n"; 272 } else { 273 dbgs() << "NONE\n"; 274 }); 275 276 // Create a new node that checks if the value is < pivot. Go to the 277 // left branch if it is and right branch if not. 278 Function* F = OrigBlock->getParent(); 279 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock"); 280 281 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT, 282 Val, Pivot.Low, "Pivot"); 283 284 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound, 285 NewUpperBound, Val, NewNode, OrigBlock, 286 Default, UnreachableRanges); 287 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound, 288 UpperBound, Val, NewNode, OrigBlock, 289 Default, UnreachableRanges); 290 291 Function::iterator FI = OrigBlock; 292 F->getBasicBlockList().insert(++FI, NewNode); 293 NewNode->getInstList().push_back(Comp); 294 295 BranchInst::Create(LBranch, RBranch, Comp, NewNode); 296 return NewNode; 297 } 298 299 // newLeafBlock - Create a new leaf block for the binary lookup tree. It 300 // checks if the switch's value == the case's value. If not, then it 301 // jumps to the default branch. At this point in the tree, the value 302 // can't be another valid case value, so the jump to the "default" branch 303 // is warranted. 304 // 305 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val, 306 BasicBlock* OrigBlock, 307 BasicBlock* Default) 308 { 309 Function* F = OrigBlock->getParent(); 310 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock"); 311 Function::iterator FI = OrigBlock; 312 F->getBasicBlockList().insert(++FI, NewLeaf); 313 314 // Emit comparison 315 ICmpInst* Comp = nullptr; 316 if (Leaf.Low == Leaf.High) { 317 // Make the seteq instruction... 318 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val, 319 Leaf.Low, "SwitchLeaf"); 320 } else { 321 // Make range comparison 322 if (Leaf.Low->isMinValue(true /*isSigned*/)) { 323 // Val >= Min && Val <= Hi --> Val <= Hi 324 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High, 325 "SwitchLeaf"); 326 } else if (Leaf.Low->isZero()) { 327 // Val >= 0 && Val <= Hi --> Val <=u Hi 328 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High, 329 "SwitchLeaf"); 330 } else { 331 // Emit V-Lo <=u Hi-Lo 332 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low); 333 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo, 334 Val->getName()+".off", 335 NewLeaf); 336 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High); 337 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound, 338 "SwitchLeaf"); 339 } 340 } 341 342 // Make the conditional branch... 343 BasicBlock* Succ = Leaf.BB; 344 BranchInst::Create(Succ, Default, Comp, NewLeaf); 345 346 // If there were any PHI nodes in this successor, rewrite one entry 347 // from OrigBlock to come from NewLeaf. 348 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 349 PHINode* PN = cast<PHINode>(I); 350 // Remove all but one incoming entries from the cluster 351 uint64_t Range = Leaf.High->getSExtValue() - 352 Leaf.Low->getSExtValue(); 353 for (uint64_t j = 0; j < Range; ++j) { 354 PN->removeIncomingValue(OrigBlock); 355 } 356 357 int BlockIdx = PN->getBasicBlockIndex(OrigBlock); 358 assert(BlockIdx != -1 && "Switch didn't go to this successor??"); 359 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf); 360 } 361 362 return NewLeaf; 363 } 364 365 // Clusterify - Transform simple list of Cases into list of CaseRange's 366 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) { 367 unsigned numCmps = 0; 368 369 // Start with "simple" cases 370 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i) 371 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(), 372 i.getCaseSuccessor())); 373 374 std::sort(Cases.begin(), Cases.end(), CaseCmp()); 375 376 // Merge case into clusters 377 if (Cases.size() >= 2) { 378 CaseItr I = Cases.begin(); 379 for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) { 380 int64_t nextValue = J->Low->getSExtValue(); 381 int64_t currentValue = I->High->getSExtValue(); 382 BasicBlock* nextBB = J->BB; 383 BasicBlock* currentBB = I->BB; 384 385 // If the two neighboring cases go to the same destination, merge them 386 // into a single case. 387 assert(nextValue > currentValue && "Cases should be strictly ascending"); 388 if ((nextValue == currentValue + 1) && (currentBB == nextBB)) { 389 I->High = J->High; 390 // FIXME: Combine branch weights. 391 } else if (++I != J) { 392 *I = *J; 393 } 394 } 395 Cases.erase(std::next(I), Cases.end()); 396 } 397 398 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) { 399 if (I->Low != I->High) 400 // A range counts double, since it requires two compares. 401 ++numCmps; 402 } 403 404 return numCmps; 405 } 406 407 // processSwitchInst - Replace the specified switch instruction with a sequence 408 // of chained if-then insts in a balanced binary search. 409 // 410 void LowerSwitch::processSwitchInst(SwitchInst *SI, 411 SmallPtrSetImpl<BasicBlock*> &DeleteList) { 412 BasicBlock *CurBlock = SI->getParent(); 413 BasicBlock *OrigBlock = CurBlock; 414 Function *F = CurBlock->getParent(); 415 Value *Val = SI->getCondition(); // The value we are switching on... 416 BasicBlock* Default = SI->getDefaultDest(); 417 418 // If there is only the default destination, just branch. 419 if (!SI->getNumCases()) { 420 BranchInst::Create(Default, CurBlock); 421 SI->eraseFromParent(); 422 return; 423 } 424 425 // Prepare cases vector. 426 CaseVector Cases; 427 unsigned numCmps = Clusterify(Cases, SI); 428 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size() 429 << ". Total compares: " << numCmps << "\n"); 430 DEBUG(dbgs() << "Cases: " << Cases << "\n"); 431 (void)numCmps; 432 433 ConstantInt *LowerBound = nullptr; 434 ConstantInt *UpperBound = nullptr; 435 std::vector<IntRange> UnreachableRanges; 436 437 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) { 438 // Make the bounds tightly fitted around the case value range, because we 439 // know that the value passed to the switch must be exactly one of the case 440 // values. 441 assert(!Cases.empty()); 442 LowerBound = Cases.front().Low; 443 UpperBound = Cases.back().High; 444 445 DenseMap<BasicBlock *, unsigned> Popularity; 446 unsigned MaxPop = 0; 447 BasicBlock *PopSucc = nullptr; 448 449 IntRange R = { INT64_MIN, INT64_MAX }; 450 UnreachableRanges.push_back(R); 451 for (const auto &I : Cases) { 452 int64_t Low = I.Low->getSExtValue(); 453 int64_t High = I.High->getSExtValue(); 454 455 IntRange &LastRange = UnreachableRanges.back(); 456 if (LastRange.Low == Low) { 457 // There is nothing left of the previous range. 458 UnreachableRanges.pop_back(); 459 } else { 460 // Terminate the previous range. 461 assert(Low > LastRange.Low); 462 LastRange.High = Low - 1; 463 } 464 if (High != INT64_MAX) { 465 IntRange R = { High + 1, INT64_MAX }; 466 UnreachableRanges.push_back(R); 467 } 468 469 // Count popularity. 470 int64_t N = High - Low + 1; 471 unsigned &Pop = Popularity[I.BB]; 472 if ((Pop += N) > MaxPop) { 473 MaxPop = Pop; 474 PopSucc = I.BB; 475 } 476 } 477 #ifndef NDEBUG 478 /* UnreachableRanges should be sorted and the ranges non-adjacent. */ 479 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end(); 480 I != E; ++I) { 481 assert(I->Low <= I->High); 482 auto Next = I + 1; 483 if (Next != E) { 484 assert(Next->Low > I->High); 485 } 486 } 487 #endif 488 489 // Use the most popular block as the new default, reducing the number of 490 // cases. 491 assert(MaxPop > 0 && PopSucc); 492 Default = PopSucc; 493 Cases.erase(std::remove_if( 494 Cases.begin(), Cases.end(), 495 [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }), 496 Cases.end()); 497 498 // If there are no cases left, just branch. 499 if (Cases.empty()) { 500 BranchInst::Create(Default, CurBlock); 501 SI->eraseFromParent(); 502 return; 503 } 504 } 505 506 // Create a new, empty default block so that the new hierarchy of 507 // if-then statements go to this and the PHI nodes are happy. 508 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault"); 509 F->getBasicBlockList().insert(Default, NewDefault); 510 BranchInst::Create(Default, NewDefault); 511 512 // If there is an entry in any PHI nodes for the default edge, make sure 513 // to update them as well. 514 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) { 515 PHINode *PN = cast<PHINode>(I); 516 int BlockIdx = PN->getBasicBlockIndex(OrigBlock); 517 assert(BlockIdx != -1 && "Switch didn't go to this successor??"); 518 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault); 519 } 520 521 BasicBlock *SwitchBlock = 522 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val, 523 OrigBlock, OrigBlock, NewDefault, UnreachableRanges); 524 525 // Branch to our shiny new if-then stuff... 526 BranchInst::Create(SwitchBlock, OrigBlock); 527 528 // We are now done with the switch instruction, delete it. 529 BasicBlock *OldDefault = SI->getDefaultDest(); 530 CurBlock->getInstList().erase(SI); 531 532 // If the Default block has no more predecessors just add it to DeleteList. 533 if (pred_begin(OldDefault) == pred_end(OldDefault)) 534 DeleteList.insert(OldDefault); 535 } 536