1 //===- DFAJumpThreading.cpp - Threads a switch statement inside a loop ----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Transform each threading path to effectively jump thread the DFA. For 10 // example, the CFG below could be transformed as follows, where the cloned 11 // blocks unconditionally branch to the next correct case based on what is 12 // identified in the analysis. 13 // 14 // sw.bb sw.bb 15 // / | \ / | \ 16 // case1 case2 case3 case1 case2 case3 17 // \ | / | | | 18 // determinator det.2 det.3 det.1 19 // br sw.bb / | \ 20 // sw.bb.2 sw.bb.3 sw.bb.1 21 // br case2 br case3 br case1§ 22 // 23 // Definitions and Terminology: 24 // 25 // * Threading path: 26 // a list of basic blocks, the exit state, and the block that determines 27 // the next state, for which the following notation will be used: 28 // < path of BBs that form a cycle > [ state, determinator ] 29 // 30 // * Predictable switch: 31 // The switch variable is always a known constant so that all conditional 32 // jumps based on switch variable can be converted to unconditional jump. 33 // 34 // * Determinator: 35 // The basic block that determines the next state of the DFA. 36 // 37 // Representing the optimization in C-like pseudocode: the code pattern on the 38 // left could functionally be transformed to the right pattern if the switch 39 // condition is predictable. 40 // 41 // X = A goto A 42 // for (...) A: 43 // switch (X) ... 44 // case A goto B 45 // X = B B: 46 // case B ... 47 // X = C goto C 48 // 49 // The pass first checks that switch variable X is decided by the control flow 50 // path taken in the loop; for example, in case B, the next value of X is 51 // decided to be C. It then enumerates through all paths in the loop and labels 52 // the basic blocks where the next state is decided. 53 // 54 // Using this information it creates new paths that unconditionally branch to 55 // the next case. This involves cloning code, so it only gets triggered if the 56 // amount of code duplicated is below a threshold. 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Transforms/Scalar/DFAJumpThreading.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/DenseMap.h" 63 #include "llvm/ADT/SmallSet.h" 64 #include "llvm/ADT/Statistic.h" 65 #include "llvm/Analysis/AssumptionCache.h" 66 #include "llvm/Analysis/CodeMetrics.h" 67 #include "llvm/Analysis/DomTreeUpdater.h" 68 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 69 #include "llvm/Analysis/TargetTransformInfo.h" 70 #include "llvm/IR/CFG.h" 71 #include "llvm/IR/Constants.h" 72 #include "llvm/IR/IntrinsicInst.h" 73 #include "llvm/InitializePasses.h" 74 #include "llvm/Pass.h" 75 #include "llvm/Support/CommandLine.h" 76 #include "llvm/Support/Debug.h" 77 #include "llvm/Transforms/Scalar.h" 78 #include "llvm/Transforms/Utils/Cloning.h" 79 #include "llvm/Transforms/Utils/SSAUpdaterBulk.h" 80 #include "llvm/Transforms/Utils/ValueMapper.h" 81 #include <algorithm> 82 #include <deque> 83 84 using namespace llvm; 85 86 #define DEBUG_TYPE "dfa-jump-threading" 87 88 STATISTIC(NumTransforms, "Number of transformations done"); 89 STATISTIC(NumCloned, "Number of blocks cloned"); 90 STATISTIC(NumPaths, "Number of individual paths threaded"); 91 92 static cl::opt<bool> 93 ClViewCfgBefore("dfa-jump-view-cfg-before", 94 cl::desc("View the CFG before DFA Jump Threading"), 95 cl::Hidden, cl::init(false)); 96 97 static cl::opt<unsigned> MaxPathLength( 98 "dfa-max-path-length", 99 cl::desc("Max number of blocks searched to find a threading path"), 100 cl::Hidden, cl::init(20)); 101 102 static cl::opt<unsigned> 103 CostThreshold("dfa-cost-threshold", 104 cl::desc("Maximum cost accepted for the transformation"), 105 cl::Hidden, cl::init(50)); 106 107 namespace { 108 109 class SelectInstToUnfold { 110 SelectInst *SI; 111 PHINode *SIUse; 112 113 public: 114 SelectInstToUnfold(SelectInst *SI, PHINode *SIUse) : SI(SI), SIUse(SIUse) {} 115 116 SelectInst *getInst() { return SI; } 117 PHINode *getUse() { return SIUse; } 118 119 explicit operator bool() const { return SI && SIUse; } 120 }; 121 122 void unfold(DomTreeUpdater *DTU, SelectInstToUnfold SIToUnfold, 123 std::vector<SelectInstToUnfold> *NewSIsToUnfold, 124 std::vector<BasicBlock *> *NewBBs); 125 126 class DFAJumpThreading { 127 public: 128 DFAJumpThreading(AssumptionCache *AC, DominatorTree *DT, 129 TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE) 130 : AC(AC), DT(DT), TTI(TTI), ORE(ORE) {} 131 132 bool run(Function &F); 133 134 private: 135 void 136 unfoldSelectInstrs(DominatorTree *DT, 137 const SmallVector<SelectInstToUnfold, 4> &SelectInsts) { 138 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 139 SmallVector<SelectInstToUnfold, 4> Stack; 140 for (SelectInstToUnfold SIToUnfold : SelectInsts) 141 Stack.push_back(SIToUnfold); 142 143 while (!Stack.empty()) { 144 SelectInstToUnfold SIToUnfold = Stack.pop_back_val(); 145 146 std::vector<SelectInstToUnfold> NewSIsToUnfold; 147 std::vector<BasicBlock *> NewBBs; 148 unfold(&DTU, SIToUnfold, &NewSIsToUnfold, &NewBBs); 149 150 // Put newly discovered select instructions into the work list. 151 for (const SelectInstToUnfold &NewSIToUnfold : NewSIsToUnfold) 152 Stack.push_back(NewSIToUnfold); 153 } 154 } 155 156 AssumptionCache *AC; 157 DominatorTree *DT; 158 TargetTransformInfo *TTI; 159 OptimizationRemarkEmitter *ORE; 160 }; 161 162 class DFAJumpThreadingLegacyPass : public FunctionPass { 163 public: 164 static char ID; // Pass identification 165 DFAJumpThreadingLegacyPass() : FunctionPass(ID) {} 166 167 void getAnalysisUsage(AnalysisUsage &AU) const override { 168 AU.addRequired<AssumptionCacheTracker>(); 169 AU.addRequired<DominatorTreeWrapperPass>(); 170 AU.addPreserved<DominatorTreeWrapperPass>(); 171 AU.addRequired<TargetTransformInfoWrapperPass>(); 172 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 173 } 174 175 bool runOnFunction(Function &F) override { 176 if (skipFunction(F)) 177 return false; 178 179 AssumptionCache *AC = 180 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 181 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 182 TargetTransformInfo *TTI = 183 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 184 OptimizationRemarkEmitter *ORE = 185 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 186 187 return DFAJumpThreading(AC, DT, TTI, ORE).run(F); 188 } 189 }; 190 } // end anonymous namespace 191 192 char DFAJumpThreadingLegacyPass::ID = 0; 193 INITIALIZE_PASS_BEGIN(DFAJumpThreadingLegacyPass, "dfa-jump-threading", 194 "DFA Jump Threading", false, false) 195 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 196 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 197 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 198 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 199 INITIALIZE_PASS_END(DFAJumpThreadingLegacyPass, "dfa-jump-threading", 200 "DFA Jump Threading", false, false) 201 202 // Public interface to the DFA Jump Threading pass 203 FunctionPass *llvm::createDFAJumpThreadingPass() { 204 return new DFAJumpThreadingLegacyPass(); 205 } 206 207 namespace { 208 209 /// Create a new basic block and sink \p SIToSink into it. 210 void createBasicBlockAndSinkSelectInst( 211 DomTreeUpdater *DTU, SelectInst *SI, PHINode *SIUse, SelectInst *SIToSink, 212 BasicBlock *EndBlock, StringRef NewBBName, BasicBlock **NewBlock, 213 BranchInst **NewBranch, std::vector<SelectInstToUnfold> *NewSIsToUnfold, 214 std::vector<BasicBlock *> *NewBBs) { 215 assert(SIToSink->hasOneUse()); 216 assert(NewBlock); 217 assert(NewBranch); 218 *NewBlock = BasicBlock::Create(SI->getContext(), NewBBName, 219 EndBlock->getParent(), EndBlock); 220 NewBBs->push_back(*NewBlock); 221 *NewBranch = BranchInst::Create(EndBlock, *NewBlock); 222 SIToSink->moveBefore(*NewBranch); 223 NewSIsToUnfold->push_back(SelectInstToUnfold(SIToSink, SIUse)); 224 DTU->applyUpdates({{DominatorTree::Insert, *NewBlock, EndBlock}}); 225 } 226 227 /// Unfold the select instruction held in \p SIToUnfold by replacing it with 228 /// control flow. 229 /// 230 /// Put newly discovered select instructions into \p NewSIsToUnfold. Put newly 231 /// created basic blocks into \p NewBBs. 232 /// 233 /// TODO: merge it with CodeGenPrepare::optimizeSelectInst() if possible. 234 void unfold(DomTreeUpdater *DTU, SelectInstToUnfold SIToUnfold, 235 std::vector<SelectInstToUnfold> *NewSIsToUnfold, 236 std::vector<BasicBlock *> *NewBBs) { 237 SelectInst *SI = SIToUnfold.getInst(); 238 PHINode *SIUse = SIToUnfold.getUse(); 239 BasicBlock *StartBlock = SI->getParent(); 240 BasicBlock *EndBlock = SIUse->getParent(); 241 BranchInst *StartBlockTerm = 242 dyn_cast<BranchInst>(StartBlock->getTerminator()); 243 244 assert(StartBlockTerm && StartBlockTerm->isUnconditional()); 245 assert(SI->hasOneUse()); 246 247 // These are the new basic blocks for the conditional branch. 248 // At least one will become an actual new basic block. 249 BasicBlock *TrueBlock = nullptr; 250 BasicBlock *FalseBlock = nullptr; 251 BranchInst *TrueBranch = nullptr; 252 BranchInst *FalseBranch = nullptr; 253 254 // Sink select instructions to be able to unfold them later. 255 if (SelectInst *SIOp = dyn_cast<SelectInst>(SI->getTrueValue())) { 256 createBasicBlockAndSinkSelectInst(DTU, SI, SIUse, SIOp, EndBlock, 257 "si.unfold.true", &TrueBlock, &TrueBranch, 258 NewSIsToUnfold, NewBBs); 259 } 260 if (SelectInst *SIOp = dyn_cast<SelectInst>(SI->getFalseValue())) { 261 createBasicBlockAndSinkSelectInst(DTU, SI, SIUse, SIOp, EndBlock, 262 "si.unfold.false", &FalseBlock, 263 &FalseBranch, NewSIsToUnfold, NewBBs); 264 } 265 266 // If there was nothing to sink, then arbitrarily choose the 'false' side 267 // for a new input value to the PHI. 268 if (!TrueBlock && !FalseBlock) { 269 FalseBlock = BasicBlock::Create(SI->getContext(), "si.unfold.false", 270 EndBlock->getParent(), EndBlock); 271 NewBBs->push_back(FalseBlock); 272 BranchInst::Create(EndBlock, FalseBlock); 273 DTU->applyUpdates({{DominatorTree::Insert, FalseBlock, EndBlock}}); 274 } 275 276 // Insert the real conditional branch based on the original condition. 277 // If we did not create a new block for one of the 'true' or 'false' paths 278 // of the condition, it means that side of the branch goes to the end block 279 // directly and the path originates from the start block from the point of 280 // view of the new PHI. 281 BasicBlock *TT = EndBlock; 282 BasicBlock *FT = EndBlock; 283 if (TrueBlock && FalseBlock) { 284 // A diamond. 285 TT = TrueBlock; 286 FT = FalseBlock; 287 288 // Update the phi node of SI. 289 SIUse->removeIncomingValue(StartBlock, /* DeletePHIIfEmpty = */ false); 290 SIUse->addIncoming(SI->getTrueValue(), TrueBlock); 291 SIUse->addIncoming(SI->getFalseValue(), FalseBlock); 292 293 // Update any other PHI nodes in EndBlock. 294 for (PHINode &Phi : EndBlock->phis()) { 295 if (&Phi != SIUse) { 296 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), TrueBlock); 297 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), FalseBlock); 298 } 299 } 300 } else { 301 BasicBlock *NewBlock = nullptr; 302 Value *SIOp1 = SI->getTrueValue(); 303 Value *SIOp2 = SI->getFalseValue(); 304 305 // A triangle pointing right. 306 if (!TrueBlock) { 307 NewBlock = FalseBlock; 308 FT = FalseBlock; 309 } 310 // A triangle pointing left. 311 else { 312 NewBlock = TrueBlock; 313 TT = TrueBlock; 314 std::swap(SIOp1, SIOp2); 315 } 316 317 // Update the phi node of SI. 318 for (unsigned Idx = 0; Idx < SIUse->getNumIncomingValues(); ++Idx) { 319 if (SIUse->getIncomingBlock(Idx) == StartBlock) 320 SIUse->setIncomingValue(Idx, SIOp1); 321 } 322 SIUse->addIncoming(SIOp2, NewBlock); 323 324 // Update any other PHI nodes in EndBlock. 325 for (auto II = EndBlock->begin(); PHINode *Phi = dyn_cast<PHINode>(II); 326 ++II) { 327 if (Phi != SIUse) 328 Phi->addIncoming(Phi->getIncomingValueForBlock(StartBlock), NewBlock); 329 } 330 } 331 StartBlockTerm->eraseFromParent(); 332 BranchInst::Create(TT, FT, SI->getCondition(), StartBlock); 333 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, TT}, 334 {DominatorTree::Insert, StartBlock, FT}}); 335 336 // The select is now dead. 337 SI->eraseFromParent(); 338 } 339 340 struct ClonedBlock { 341 BasicBlock *BB; 342 uint64_t State; ///< \p State corresponds to the next value of a switch stmnt. 343 }; 344 345 typedef std::deque<BasicBlock *> PathType; 346 typedef std::vector<PathType> PathsType; 347 typedef SmallPtrSet<const BasicBlock *, 8> VisitedBlocks; 348 typedef std::vector<ClonedBlock> CloneList; 349 350 // This data structure keeps track of all blocks that have been cloned. If two 351 // different ThreadingPaths clone the same block for a certain state it should 352 // be reused, and it can be looked up in this map. 353 typedef DenseMap<BasicBlock *, CloneList> DuplicateBlockMap; 354 355 // This map keeps track of all the new definitions for an instruction. This 356 // information is needed when restoring SSA form after cloning blocks. 357 typedef MapVector<Instruction *, std::vector<Instruction *>> DefMap; 358 359 inline raw_ostream &operator<<(raw_ostream &OS, const PathType &Path) { 360 OS << "< "; 361 for (const BasicBlock *BB : Path) { 362 std::string BBName; 363 if (BB->hasName()) 364 raw_string_ostream(BBName) << BB->getName(); 365 else 366 raw_string_ostream(BBName) << BB; 367 OS << BBName << " "; 368 } 369 OS << ">"; 370 return OS; 371 } 372 373 /// ThreadingPath is a path in the control flow of a loop that can be threaded 374 /// by cloning necessary basic blocks and replacing conditional branches with 375 /// unconditional ones. A threading path includes a list of basic blocks, the 376 /// exit state, and the block that determines the next state. 377 struct ThreadingPath { 378 /// Exit value is DFA's exit state for the given path. 379 uint64_t getExitValue() const { return ExitVal; } 380 void setExitValue(const ConstantInt *V) { 381 ExitVal = V->getZExtValue(); 382 IsExitValSet = true; 383 } 384 bool isExitValueSet() const { return IsExitValSet; } 385 386 /// Determinator is the basic block that determines the next state of the DFA. 387 const BasicBlock *getDeterminatorBB() const { return DBB; } 388 void setDeterminator(const BasicBlock *BB) { DBB = BB; } 389 390 /// Path is a list of basic blocks. 391 const PathType &getPath() const { return Path; } 392 void setPath(const PathType &NewPath) { Path = NewPath; } 393 394 void print(raw_ostream &OS) const { 395 OS << Path << " [ " << ExitVal << ", " << DBB->getName() << " ]"; 396 } 397 398 private: 399 PathType Path; 400 uint64_t ExitVal; 401 const BasicBlock *DBB = nullptr; 402 bool IsExitValSet = false; 403 }; 404 405 #ifndef NDEBUG 406 inline raw_ostream &operator<<(raw_ostream &OS, const ThreadingPath &TPath) { 407 TPath.print(OS); 408 return OS; 409 } 410 #endif 411 412 struct MainSwitch { 413 MainSwitch(SwitchInst *SI, OptimizationRemarkEmitter *ORE) { 414 if (isPredictable(SI)) { 415 Instr = SI; 416 } else { 417 ORE->emit([&]() { 418 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable", SI) 419 << "Switch instruction is not predictable."; 420 }); 421 } 422 } 423 424 virtual ~MainSwitch() = default; 425 426 SwitchInst *getInstr() const { return Instr; } 427 const SmallVector<SelectInstToUnfold, 4> getSelectInsts() { 428 return SelectInsts; 429 } 430 431 private: 432 /// Do a use-def chain traversal. Make sure the value of the switch variable 433 /// is always a known constant. This means that all conditional jumps based on 434 /// switch variable can be converted to unconditional jumps. 435 bool isPredictable(const SwitchInst *SI) { 436 std::deque<Instruction *> Q; 437 SmallSet<Value *, 16> SeenValues; 438 SelectInsts.clear(); 439 440 Value *FirstDef = SI->getOperand(0); 441 auto *Inst = dyn_cast<Instruction>(FirstDef); 442 443 // If this is a function argument or another non-instruction, then give up. 444 // We are interested in loop local variables. 445 if (!Inst) 446 return false; 447 448 // Require the first definition to be a PHINode 449 if (!isa<PHINode>(Inst)) 450 return false; 451 452 LLVM_DEBUG(dbgs() << "\tisPredictable() FirstDef: " << *Inst << "\n"); 453 454 Q.push_back(Inst); 455 SeenValues.insert(FirstDef); 456 457 while (!Q.empty()) { 458 Instruction *Current = Q.front(); 459 Q.pop_front(); 460 461 if (auto *Phi = dyn_cast<PHINode>(Current)) { 462 for (Value *Incoming : Phi->incoming_values()) { 463 if (!isPredictableValue(Incoming, SeenValues)) 464 return false; 465 addInstToQueue(Incoming, Q, SeenValues); 466 } 467 LLVM_DEBUG(dbgs() << "\tisPredictable() phi: " << *Phi << "\n"); 468 } else if (SelectInst *SelI = dyn_cast<SelectInst>(Current)) { 469 if (!isValidSelectInst(SelI)) 470 return false; 471 if (!isPredictableValue(SelI->getTrueValue(), SeenValues) || 472 !isPredictableValue(SelI->getFalseValue(), SeenValues)) { 473 return false; 474 } 475 addInstToQueue(SelI->getTrueValue(), Q, SeenValues); 476 addInstToQueue(SelI->getFalseValue(), Q, SeenValues); 477 LLVM_DEBUG(dbgs() << "\tisPredictable() select: " << *SelI << "\n"); 478 if (auto *SelIUse = dyn_cast<PHINode>(SelI->user_back())) 479 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse)); 480 } else { 481 // If it is neither a phi nor a select, then we give up. 482 return false; 483 } 484 } 485 486 return true; 487 } 488 489 bool isPredictableValue(Value *InpVal, SmallSet<Value *, 16> &SeenValues) { 490 if (SeenValues.contains(InpVal)) 491 return true; 492 493 if (isa<ConstantInt>(InpVal)) 494 return true; 495 496 // If this is a function argument or another non-instruction, then give up. 497 if (!isa<Instruction>(InpVal)) 498 return false; 499 500 return true; 501 } 502 503 void addInstToQueue(Value *Val, std::deque<Instruction *> &Q, 504 SmallSet<Value *, 16> &SeenValues) { 505 if (SeenValues.contains(Val)) 506 return; 507 if (Instruction *I = dyn_cast<Instruction>(Val)) 508 Q.push_back(I); 509 SeenValues.insert(Val); 510 } 511 512 bool isValidSelectInst(SelectInst *SI) { 513 if (!SI->hasOneUse()) 514 return false; 515 516 Instruction *SIUse = dyn_cast<Instruction>(SI->user_back()); 517 // The use of the select inst should be either a phi or another select. 518 if (!SIUse && !(isa<PHINode>(SIUse) || isa<SelectInst>(SIUse))) 519 return false; 520 521 BasicBlock *SIBB = SI->getParent(); 522 523 // Currently, we can only expand select instructions in basic blocks with 524 // one successor. 525 BranchInst *SITerm = dyn_cast<BranchInst>(SIBB->getTerminator()); 526 if (!SITerm || !SITerm->isUnconditional()) 527 return false; 528 529 if (isa<PHINode>(SIUse) && 530 SIBB->getSingleSuccessor() != cast<Instruction>(SIUse)->getParent()) 531 return false; 532 533 // If select will not be sunk during unfolding, and it is in the same basic 534 // block as another state defining select, then cannot unfold both. 535 for (SelectInstToUnfold SIToUnfold : SelectInsts) { 536 SelectInst *PrevSI = SIToUnfold.getInst(); 537 if (PrevSI->getTrueValue() != SI && PrevSI->getFalseValue() != SI && 538 PrevSI->getParent() == SI->getParent()) 539 return false; 540 } 541 542 return true; 543 } 544 545 SwitchInst *Instr = nullptr; 546 SmallVector<SelectInstToUnfold, 4> SelectInsts; 547 }; 548 549 struct AllSwitchPaths { 550 AllSwitchPaths(const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE) 551 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->getParent()), 552 ORE(ORE) {} 553 554 std::vector<ThreadingPath> &getThreadingPaths() { return TPaths; } 555 unsigned getNumThreadingPaths() { return TPaths.size(); } 556 SwitchInst *getSwitchInst() { return Switch; } 557 BasicBlock *getSwitchBlock() { return SwitchBlock; } 558 559 void run() { 560 VisitedBlocks Visited; 561 PathsType LoopPaths = paths(SwitchBlock, Visited, /* PathDepth = */ 1); 562 StateDefMap StateDef = getStateDefMap(); 563 564 for (PathType Path : LoopPaths) { 565 ThreadingPath TPath; 566 567 const BasicBlock *PrevBB = Path.back(); 568 for (const BasicBlock *BB : Path) { 569 if (StateDef.count(BB) != 0) { 570 const PHINode *Phi = dyn_cast<PHINode>(StateDef[BB]); 571 assert(Phi && "Expected a state-defining instr to be a phi node."); 572 573 const Value *V = Phi->getIncomingValueForBlock(PrevBB); 574 if (const ConstantInt *C = dyn_cast<const ConstantInt>(V)) { 575 TPath.setExitValue(C); 576 TPath.setDeterminator(BB); 577 TPath.setPath(Path); 578 } 579 } 580 581 // Switch block is the determinator, this is the final exit value. 582 if (TPath.isExitValueSet() && BB == Path.front()) 583 break; 584 585 PrevBB = BB; 586 } 587 588 if (TPath.isExitValueSet() && isSupported(TPath)) 589 TPaths.push_back(TPath); 590 } 591 } 592 593 private: 594 // Value: an instruction that defines a switch state; 595 // Key: the parent basic block of that instruction. 596 typedef DenseMap<const BasicBlock *, const PHINode *> StateDefMap; 597 598 PathsType paths(BasicBlock *BB, VisitedBlocks &Visited, 599 unsigned PathDepth) const { 600 PathsType Res; 601 602 // Stop exploring paths after visiting MaxPathLength blocks 603 if (PathDepth > MaxPathLength) { 604 ORE->emit([&]() { 605 return OptimizationRemarkAnalysis(DEBUG_TYPE, "MaxPathLengthReached", 606 Switch) 607 << "Exploration stopped after visiting MaxPathLength=" 608 << ore::NV("MaxPathLength", MaxPathLength) << " blocks."; 609 }); 610 return Res; 611 } 612 613 Visited.insert(BB); 614 615 // Some blocks have multiple edges to the same successor, and this set 616 // is used to prevent a duplicate path from being generated 617 SmallSet<BasicBlock *, 4> Successors; 618 for (BasicBlock *Succ : successors(BB)) { 619 if (!Successors.insert(Succ).second) 620 continue; 621 622 // Found a cycle through the SwitchBlock 623 if (Succ == SwitchBlock) { 624 Res.push_back({BB}); 625 continue; 626 } 627 628 // We have encountered a cycle, do not get caught in it 629 if (Visited.contains(Succ)) 630 continue; 631 632 PathsType SuccPaths = paths(Succ, Visited, PathDepth + 1); 633 for (PathType Path : SuccPaths) { 634 PathType NewPath(Path); 635 NewPath.push_front(BB); 636 Res.push_back(NewPath); 637 } 638 } 639 // This block could now be visited again from a different predecessor. Note 640 // that this will result in exponential runtime. Subpaths could possibly be 641 // cached but it takes a lot of memory to store them. 642 Visited.erase(BB); 643 return Res; 644 } 645 646 /// Walk the use-def chain and collect all the state-defining instructions. 647 StateDefMap getStateDefMap() const { 648 StateDefMap Res; 649 650 Value *FirstDef = Switch->getOperand(0); 651 652 assert(isa<PHINode>(FirstDef) && "After select unfolding, all state " 653 "definitions are expected to be phi " 654 "nodes."); 655 656 SmallVector<PHINode *, 8> Stack; 657 Stack.push_back(dyn_cast<PHINode>(FirstDef)); 658 SmallSet<Value *, 16> SeenValues; 659 660 while (!Stack.empty()) { 661 PHINode *CurPhi = Stack.pop_back_val(); 662 663 Res[CurPhi->getParent()] = CurPhi; 664 SeenValues.insert(CurPhi); 665 666 for (Value *Incoming : CurPhi->incoming_values()) { 667 if (Incoming == FirstDef || isa<ConstantInt>(Incoming) || 668 SeenValues.contains(Incoming)) { 669 continue; 670 } 671 672 assert(isa<PHINode>(Incoming) && "After select unfolding, all state " 673 "definitions are expected to be phi " 674 "nodes."); 675 676 Stack.push_back(cast<PHINode>(Incoming)); 677 } 678 } 679 680 return Res; 681 } 682 683 /// The determinator BB should precede the switch-defining BB. 684 /// 685 /// Otherwise, it is possible that the state defined in the determinator block 686 /// defines the state for the next iteration of the loop, rather than for the 687 /// current one. 688 /// 689 /// Currently supported paths: 690 /// \code 691 /// < switch bb1 determ def > [ 42, determ ] 692 /// < switch_and_def bb1 determ > [ 42, determ ] 693 /// < switch_and_def_and_determ bb1 > [ 42, switch_and_def_and_determ ] 694 /// \endcode 695 /// 696 /// Unsupported paths: 697 /// \code 698 /// < switch bb1 def determ > [ 43, determ ] 699 /// < switch_and_determ bb1 def > [ 43, switch_and_determ ] 700 /// \endcode 701 bool isSupported(const ThreadingPath &TPath) { 702 Instruction *SwitchCondI = dyn_cast<Instruction>(Switch->getCondition()); 703 assert(SwitchCondI); 704 if (!SwitchCondI) 705 return false; 706 707 const BasicBlock *SwitchCondDefBB = SwitchCondI->getParent(); 708 const BasicBlock *SwitchCondUseBB = Switch->getParent(); 709 const BasicBlock *DeterminatorBB = TPath.getDeterminatorBB(); 710 711 assert( 712 SwitchCondUseBB == TPath.getPath().front() && 713 "The first BB in a threading path should have the switch instruction"); 714 if (SwitchCondUseBB != TPath.getPath().front()) 715 return false; 716 717 // Make DeterminatorBB the first element in Path. 718 PathType Path = TPath.getPath(); 719 auto ItDet = std::find(Path.begin(), Path.end(), DeterminatorBB); 720 std::rotate(Path.begin(), ItDet, Path.end()); 721 722 bool IsDetBBSeen = false; 723 bool IsDefBBSeen = false; 724 bool IsUseBBSeen = false; 725 for (BasicBlock *BB : Path) { 726 if (BB == DeterminatorBB) 727 IsDetBBSeen = true; 728 if (BB == SwitchCondDefBB) 729 IsDefBBSeen = true; 730 if (BB == SwitchCondUseBB) 731 IsUseBBSeen = true; 732 if (IsDetBBSeen && IsUseBBSeen && !IsDefBBSeen) 733 return false; 734 } 735 736 return true; 737 } 738 739 SwitchInst *Switch; 740 BasicBlock *SwitchBlock; 741 OptimizationRemarkEmitter *ORE; 742 std::vector<ThreadingPath> TPaths; 743 }; 744 745 struct TransformDFA { 746 TransformDFA(AllSwitchPaths *SwitchPaths, DominatorTree *DT, 747 AssumptionCache *AC, TargetTransformInfo *TTI, 748 OptimizationRemarkEmitter *ORE, 749 SmallPtrSet<const Value *, 32> EphValues) 750 : SwitchPaths(SwitchPaths), DT(DT), AC(AC), TTI(TTI), ORE(ORE), 751 EphValues(EphValues) {} 752 753 void run() { 754 if (isLegalAndProfitableToTransform()) { 755 createAllExitPaths(); 756 NumTransforms++; 757 } 758 } 759 760 private: 761 /// This function performs both a legality check and profitability check at 762 /// the same time since it is convenient to do so. It iterates through all 763 /// blocks that will be cloned, and keeps track of the duplication cost. It 764 /// also returns false if it is illegal to clone some required block. 765 bool isLegalAndProfitableToTransform() { 766 CodeMetrics Metrics; 767 SwitchInst *Switch = SwitchPaths->getSwitchInst(); 768 769 // Note that DuplicateBlockMap is not being used as intended here. It is 770 // just being used to ensure (BB, State) pairs are only counted once. 771 DuplicateBlockMap DuplicateMap; 772 773 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) { 774 PathType PathBBs = TPath.getPath(); 775 uint64_t NextState = TPath.getExitValue(); 776 const BasicBlock *Determinator = TPath.getDeterminatorBB(); 777 778 // Update Metrics for the Switch block, this is always cloned 779 BasicBlock *BB = SwitchPaths->getSwitchBlock(); 780 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap); 781 if (!VisitedBB) { 782 Metrics.analyzeBasicBlock(BB, *TTI, EphValues); 783 DuplicateMap[BB].push_back({BB, NextState}); 784 } 785 786 // If the Switch block is the Determinator, then we can continue since 787 // this is the only block that is cloned and we already counted for it. 788 if (PathBBs.front() == Determinator) 789 continue; 790 791 // Otherwise update Metrics for all blocks that will be cloned. If any 792 // block is already cloned and would be reused, don't double count it. 793 auto DetIt = std::find(PathBBs.begin(), PathBBs.end(), Determinator); 794 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) { 795 BB = *BBIt; 796 VisitedBB = getClonedBB(BB, NextState, DuplicateMap); 797 if (VisitedBB) 798 continue; 799 Metrics.analyzeBasicBlock(BB, *TTI, EphValues); 800 DuplicateMap[BB].push_back({BB, NextState}); 801 } 802 803 if (Metrics.notDuplicatable) { 804 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains " 805 << "non-duplicatable instructions.\n"); 806 ORE->emit([&]() { 807 return OptimizationRemarkMissed(DEBUG_TYPE, "NonDuplicatableInst", 808 Switch) 809 << "Contains non-duplicatable instructions."; 810 }); 811 return false; 812 } 813 814 if (Metrics.convergent) { 815 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains " 816 << "convergent instructions.\n"); 817 ORE->emit([&]() { 818 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch) 819 << "Contains convergent instructions."; 820 }); 821 return false; 822 } 823 } 824 825 unsigned DuplicationCost = 0; 826 827 unsigned JumpTableSize = 0; 828 TTI->getEstimatedNumberOfCaseClusters(*Switch, JumpTableSize, nullptr, 829 nullptr); 830 if (JumpTableSize == 0) { 831 // Factor in the number of conditional branches reduced from jump 832 // threading. Assume that lowering the switch block is implemented by 833 // using binary search, hence the LogBase2(). 834 unsigned CondBranches = 835 APInt(32, Switch->getNumSuccessors()).ceilLogBase2(); 836 DuplicationCost = Metrics.NumInsts / CondBranches; 837 } else { 838 // Compared with jump tables, the DFA optimizer removes an indirect branch 839 // on each loop iteration, thus making branch prediction more precise. The 840 // more branch targets there are, the more likely it is for the branch 841 // predictor to make a mistake, and the more benefit there is in the DFA 842 // optimizer. Thus, the more branch targets there are, the lower is the 843 // cost of the DFA opt. 844 DuplicationCost = Metrics.NumInsts / JumpTableSize; 845 } 846 847 LLVM_DEBUG(dbgs() << "\nDFA Jump Threading: Cost to jump thread block " 848 << SwitchPaths->getSwitchBlock()->getName() 849 << " is: " << DuplicationCost << "\n\n"); 850 851 if (DuplicationCost > CostThreshold) { 852 LLVM_DEBUG(dbgs() << "Not jump threading, duplication cost exceeds the " 853 << "cost threshold.\n"); 854 ORE->emit([&]() { 855 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch) 856 << "Duplication cost exceeds the cost threshold (cost=" 857 << ore::NV("Cost", DuplicationCost) 858 << ", threshold=" << ore::NV("Threshold", CostThreshold) << ")."; 859 }); 860 return false; 861 } 862 863 ORE->emit([&]() { 864 return OptimizationRemark(DEBUG_TYPE, "JumpThreaded", Switch) 865 << "Switch statement jump-threaded."; 866 }); 867 868 return true; 869 } 870 871 /// Transform each threading path to effectively jump thread the DFA. 872 void createAllExitPaths() { 873 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager); 874 875 // Move the switch block to the end of the path, since it will be duplicated 876 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock(); 877 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) { 878 LLVM_DEBUG(dbgs() << TPath << "\n"); 879 PathType NewPath(TPath.getPath()); 880 NewPath.push_back(SwitchBlock); 881 TPath.setPath(NewPath); 882 } 883 884 // Transform the ThreadingPaths and keep track of the cloned values 885 DuplicateBlockMap DuplicateMap; 886 DefMap NewDefs; 887 888 SmallSet<BasicBlock *, 16> BlocksToClean; 889 for (BasicBlock *BB : successors(SwitchBlock)) 890 BlocksToClean.insert(BB); 891 892 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) { 893 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, &DTU); 894 NumPaths++; 895 } 896 897 // After all paths are cloned, now update the last successor of the cloned 898 // path so it skips over the switch statement 899 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) 900 updateLastSuccessor(TPath, DuplicateMap, &DTU); 901 902 // For each instruction that was cloned and used outside, update its uses 903 updateSSA(NewDefs); 904 905 // Clean PHI Nodes for the newly created blocks 906 for (BasicBlock *BB : BlocksToClean) 907 cleanPhiNodes(BB); 908 } 909 910 /// For a specific ThreadingPath \p Path, create an exit path starting from 911 /// the determinator block. 912 /// 913 /// To remember the correct destination, we have to duplicate blocks 914 /// corresponding to each state. Also update the terminating instruction of 915 /// the predecessors, and phis in the successor blocks. 916 void createExitPath(DefMap &NewDefs, ThreadingPath &Path, 917 DuplicateBlockMap &DuplicateMap, 918 SmallSet<BasicBlock *, 16> &BlocksToClean, 919 DomTreeUpdater *DTU) { 920 uint64_t NextState = Path.getExitValue(); 921 const BasicBlock *Determinator = Path.getDeterminatorBB(); 922 PathType PathBBs = Path.getPath(); 923 924 // Don't select the placeholder block in front 925 if (PathBBs.front() == Determinator) 926 PathBBs.pop_front(); 927 928 auto DetIt = std::find(PathBBs.begin(), PathBBs.end(), Determinator); 929 auto Prev = std::prev(DetIt); 930 BasicBlock *PrevBB = *Prev; 931 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) { 932 BasicBlock *BB = *BBIt; 933 BlocksToClean.insert(BB); 934 935 // We already cloned BB for this NextState, now just update the branch 936 // and continue. 937 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap); 938 if (NextBB) { 939 updatePredecessor(PrevBB, BB, NextBB, DTU); 940 PrevBB = NextBB; 941 continue; 942 } 943 944 // Clone the BB and update the successor of Prev to jump to the new block 945 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor( 946 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU); 947 DuplicateMap[BB].push_back({NewBB, NextState}); 948 BlocksToClean.insert(NewBB); 949 PrevBB = NewBB; 950 } 951 } 952 953 /// Restore SSA form after cloning blocks. 954 /// 955 /// Each cloned block creates new defs for a variable, and the uses need to be 956 /// updated to reflect this. The uses may be replaced with a cloned value, or 957 /// some derived phi instruction. Note that all uses of a value defined in the 958 /// same block were already remapped when cloning the block. 959 void updateSSA(DefMap &NewDefs) { 960 SSAUpdaterBulk SSAUpdate; 961 SmallVector<Use *, 16> UsesToRename; 962 963 for (auto KV : NewDefs) { 964 Instruction *I = KV.first; 965 BasicBlock *BB = I->getParent(); 966 std::vector<Instruction *> Cloned = KV.second; 967 968 // Scan all uses of this instruction to see if it is used outside of its 969 // block, and if so, record them in UsesToRename. 970 for (Use &U : I->uses()) { 971 Instruction *User = cast<Instruction>(U.getUser()); 972 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 973 if (UserPN->getIncomingBlock(U) == BB) 974 continue; 975 } else if (User->getParent() == BB) { 976 continue; 977 } 978 979 UsesToRename.push_back(&U); 980 } 981 982 // If there are no uses outside the block, we're done with this 983 // instruction. 984 if (UsesToRename.empty()) 985 continue; 986 LLVM_DEBUG(dbgs() << "DFA-JT: Renaming non-local uses of: " << *I 987 << "\n"); 988 989 // We found a use of I outside of BB. Rename all uses of I that are 990 // outside its block to be uses of the appropriate PHI node etc. See 991 // ValuesInBlocks with the values we know. 992 unsigned VarNum = SSAUpdate.AddVariable(I->getName(), I->getType()); 993 SSAUpdate.AddAvailableValue(VarNum, BB, I); 994 for (Instruction *New : Cloned) 995 SSAUpdate.AddAvailableValue(VarNum, New->getParent(), New); 996 997 while (!UsesToRename.empty()) 998 SSAUpdate.AddUse(VarNum, UsesToRename.pop_back_val()); 999 1000 LLVM_DEBUG(dbgs() << "\n"); 1001 } 1002 // SSAUpdater handles phi placement and renaming uses with the appropriate 1003 // value. 1004 SSAUpdate.RewriteAllUses(DT); 1005 } 1006 1007 /// Clones a basic block, and adds it to the CFG. 1008 /// 1009 /// This function also includes updating phi nodes in the successors of the 1010 /// BB, and remapping uses that were defined locally in the cloned BB. 1011 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB, 1012 uint64_t NextState, 1013 DuplicateBlockMap &DuplicateMap, 1014 DefMap &NewDefs, 1015 DomTreeUpdater *DTU) { 1016 ValueToValueMapTy VMap; 1017 BasicBlock *NewBB = CloneBasicBlock( 1018 BB, VMap, ".jt" + std::to_string(NextState), BB->getParent()); 1019 NewBB->moveAfter(BB); 1020 NumCloned++; 1021 1022 for (Instruction &I : *NewBB) { 1023 // Do not remap operands of PHINode in case a definition in BB is an 1024 // incoming value to a phi in the same block. This incoming value will 1025 // be renamed later while restoring SSA. 1026 if (isa<PHINode>(&I)) 1027 continue; 1028 RemapInstruction(&I, VMap, 1029 RF_IgnoreMissingLocals | RF_NoModuleLevelChanges); 1030 if (AssumeInst *II = dyn_cast<AssumeInst>(&I)) 1031 AC->registerAssumption(II); 1032 } 1033 1034 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap); 1035 updatePredecessor(PrevBB, BB, NewBB, DTU); 1036 updateDefMap(NewDefs, VMap); 1037 1038 // Add all successors to the DominatorTree 1039 SmallPtrSet<BasicBlock *, 4> SuccSet; 1040 for (auto *SuccBB : successors(NewBB)) { 1041 if (SuccSet.insert(SuccBB).second) 1042 DTU->applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}}); 1043 } 1044 SuccSet.clear(); 1045 return NewBB; 1046 } 1047 1048 /// Update the phi nodes in BB's successors. 1049 /// 1050 /// This means creating a new incoming value from NewBB with the new 1051 /// instruction wherever there is an incoming value from BB. 1052 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB, 1053 uint64_t NextState, ValueToValueMapTy &VMap, 1054 DuplicateBlockMap &DuplicateMap) { 1055 std::vector<BasicBlock *> BlocksToUpdate; 1056 1057 // If BB is the last block in the path, we can simply update the one case 1058 // successor that will be reached. 1059 if (BB == SwitchPaths->getSwitchBlock()) { 1060 SwitchInst *Switch = SwitchPaths->getSwitchInst(); 1061 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState); 1062 BlocksToUpdate.push_back(NextCase); 1063 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap); 1064 if (ClonedSucc) 1065 BlocksToUpdate.push_back(ClonedSucc); 1066 } 1067 // Otherwise update phis in all successors. 1068 else { 1069 for (BasicBlock *Succ : successors(BB)) { 1070 BlocksToUpdate.push_back(Succ); 1071 1072 // Check if a successor has already been cloned for the particular exit 1073 // value. In this case if a successor was already cloned, the phi nodes 1074 // in the cloned block should be updated directly. 1075 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap); 1076 if (ClonedSucc) 1077 BlocksToUpdate.push_back(ClonedSucc); 1078 } 1079 } 1080 1081 // If there is a phi with an incoming value from BB, create a new incoming 1082 // value for the new predecessor ClonedBB. The value will either be the same 1083 // value from BB or a cloned value. 1084 for (BasicBlock *Succ : BlocksToUpdate) { 1085 for (auto II = Succ->begin(); PHINode *Phi = dyn_cast<PHINode>(II); 1086 ++II) { 1087 Value *Incoming = Phi->getIncomingValueForBlock(BB); 1088 if (Incoming) { 1089 if (isa<Constant>(Incoming)) { 1090 Phi->addIncoming(Incoming, ClonedBB); 1091 continue; 1092 } 1093 Value *ClonedVal = VMap[Incoming]; 1094 if (ClonedVal) 1095 Phi->addIncoming(ClonedVal, ClonedBB); 1096 else 1097 Phi->addIncoming(Incoming, ClonedBB); 1098 } 1099 } 1100 } 1101 } 1102 1103 /// Sets the successor of PrevBB to be NewBB instead of OldBB. Note that all 1104 /// other successors are kept as well. 1105 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB, 1106 BasicBlock *NewBB, DomTreeUpdater *DTU) { 1107 // When a path is reused, there is a chance that predecessors were already 1108 // updated before. Check if the predecessor needs to be updated first. 1109 if (!isPredecessor(OldBB, PrevBB)) 1110 return; 1111 1112 Instruction *PrevTerm = PrevBB->getTerminator(); 1113 for (unsigned Idx = 0; Idx < PrevTerm->getNumSuccessors(); Idx++) { 1114 if (PrevTerm->getSuccessor(Idx) == OldBB) { 1115 OldBB->removePredecessor(PrevBB, /* KeepOneInputPHIs = */ true); 1116 PrevTerm->setSuccessor(Idx, NewBB); 1117 } 1118 } 1119 DTU->applyUpdates({{DominatorTree::Delete, PrevBB, OldBB}, 1120 {DominatorTree::Insert, PrevBB, NewBB}}); 1121 } 1122 1123 /// Add new value mappings to the DefMap to keep track of all new definitions 1124 /// for a particular instruction. These will be used while updating SSA form. 1125 void updateDefMap(DefMap &NewDefs, ValueToValueMapTy &VMap) { 1126 SmallVector<std::pair<Instruction *, Instruction *>> NewDefsVector; 1127 NewDefsVector.reserve(VMap.size()); 1128 1129 for (auto Entry : VMap) { 1130 Instruction *Inst = 1131 dyn_cast<Instruction>(const_cast<Value *>(Entry.first)); 1132 if (!Inst || !Entry.second || isa<BranchInst>(Inst) || 1133 isa<SwitchInst>(Inst)) { 1134 continue; 1135 } 1136 1137 Instruction *Cloned = dyn_cast<Instruction>(Entry.second); 1138 if (!Cloned) 1139 continue; 1140 1141 NewDefsVector.push_back({Inst, Cloned}); 1142 } 1143 1144 // Sort the defs to get deterministic insertion order into NewDefs. 1145 sort(NewDefsVector, [](const auto &LHS, const auto &RHS) { 1146 if (LHS.first == RHS.first) 1147 return LHS.second->comesBefore(RHS.second); 1148 return LHS.first->comesBefore(RHS.first); 1149 }); 1150 1151 for (const auto &KV : NewDefsVector) 1152 NewDefs[KV.first].push_back(KV.second); 1153 } 1154 1155 /// Update the last branch of a particular cloned path to point to the correct 1156 /// case successor. 1157 /// 1158 /// Note that this is an optional step and would have been done in later 1159 /// optimizations, but it makes the CFG significantly easier to work with. 1160 void updateLastSuccessor(ThreadingPath &TPath, 1161 DuplicateBlockMap &DuplicateMap, 1162 DomTreeUpdater *DTU) { 1163 uint64_t NextState = TPath.getExitValue(); 1164 BasicBlock *BB = TPath.getPath().back(); 1165 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap); 1166 1167 // Note multiple paths can end at the same block so check that it is not 1168 // updated yet 1169 if (!isa<SwitchInst>(LastBlock->getTerminator())) 1170 return; 1171 SwitchInst *Switch = cast<SwitchInst>(LastBlock->getTerminator()); 1172 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState); 1173 1174 std::vector<DominatorTree::UpdateType> DTUpdates; 1175 SmallPtrSet<BasicBlock *, 4> SuccSet; 1176 for (BasicBlock *Succ : successors(LastBlock)) { 1177 if (Succ != NextCase && SuccSet.insert(Succ).second) 1178 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ}); 1179 } 1180 1181 Switch->eraseFromParent(); 1182 BranchInst::Create(NextCase, LastBlock); 1183 1184 DTU->applyUpdates(DTUpdates); 1185 } 1186 1187 /// After cloning blocks, some of the phi nodes have extra incoming values 1188 /// that are no longer used. This function removes them. 1189 void cleanPhiNodes(BasicBlock *BB) { 1190 // If BB is no longer reachable, remove any remaining phi nodes 1191 if (pred_empty(BB)) { 1192 std::vector<PHINode *> PhiToRemove; 1193 for (auto II = BB->begin(); PHINode *Phi = dyn_cast<PHINode>(II); ++II) { 1194 PhiToRemove.push_back(Phi); 1195 } 1196 for (PHINode *PN : PhiToRemove) { 1197 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 1198 PN->eraseFromParent(); 1199 } 1200 return; 1201 } 1202 1203 // Remove any incoming values that come from an invalid predecessor 1204 for (auto II = BB->begin(); PHINode *Phi = dyn_cast<PHINode>(II); ++II) { 1205 std::vector<BasicBlock *> BlocksToRemove; 1206 for (BasicBlock *IncomingBB : Phi->blocks()) { 1207 if (!isPredecessor(BB, IncomingBB)) 1208 BlocksToRemove.push_back(IncomingBB); 1209 } 1210 for (BasicBlock *BB : BlocksToRemove) 1211 Phi->removeIncomingValue(BB); 1212 } 1213 } 1214 1215 /// Checks if BB was already cloned for a particular next state value. If it 1216 /// was then it returns this cloned block, and otherwise null. 1217 BasicBlock *getClonedBB(BasicBlock *BB, uint64_t NextState, 1218 DuplicateBlockMap &DuplicateMap) { 1219 CloneList ClonedBBs = DuplicateMap[BB]; 1220 1221 // Find an entry in the CloneList with this NextState. If it exists then 1222 // return the corresponding BB 1223 auto It = llvm::find_if(ClonedBBs, [NextState](const ClonedBlock &C) { 1224 return C.State == NextState; 1225 }); 1226 return It != ClonedBBs.end() ? (*It).BB : nullptr; 1227 } 1228 1229 /// Helper to get the successor corresponding to a particular case value for 1230 /// a switch statement. 1231 BasicBlock *getNextCaseSuccessor(SwitchInst *Switch, uint64_t NextState) { 1232 BasicBlock *NextCase = nullptr; 1233 for (auto Case : Switch->cases()) { 1234 if (Case.getCaseValue()->getZExtValue() == NextState) { 1235 NextCase = Case.getCaseSuccessor(); 1236 break; 1237 } 1238 } 1239 if (!NextCase) 1240 NextCase = Switch->getDefaultDest(); 1241 return NextCase; 1242 } 1243 1244 /// Returns true if IncomingBB is a predecessor of BB. 1245 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) { 1246 return llvm::find(predecessors(BB), IncomingBB) != pred_end(BB); 1247 } 1248 1249 AllSwitchPaths *SwitchPaths; 1250 DominatorTree *DT; 1251 AssumptionCache *AC; 1252 TargetTransformInfo *TTI; 1253 OptimizationRemarkEmitter *ORE; 1254 SmallPtrSet<const Value *, 32> EphValues; 1255 std::vector<ThreadingPath> TPaths; 1256 }; 1257 1258 bool DFAJumpThreading::run(Function &F) { 1259 LLVM_DEBUG(dbgs() << "\nDFA Jump threading: " << F.getName() << "\n"); 1260 1261 if (F.hasOptSize()) { 1262 LLVM_DEBUG(dbgs() << "Skipping due to the 'minsize' attribute\n"); 1263 return false; 1264 } 1265 1266 if (ClViewCfgBefore) 1267 F.viewCFG(); 1268 1269 SmallVector<AllSwitchPaths, 2> ThreadableLoops; 1270 bool MadeChanges = false; 1271 1272 for (BasicBlock &BB : F) { 1273 auto *SI = dyn_cast<SwitchInst>(BB.getTerminator()); 1274 if (!SI) 1275 continue; 1276 1277 LLVM_DEBUG(dbgs() << "\nCheck if SwitchInst in BB " << BB.getName() 1278 << " is predictable\n"); 1279 MainSwitch Switch(SI, ORE); 1280 1281 if (!Switch.getInstr()) 1282 continue; 1283 1284 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is a " 1285 << "candidate for jump threading\n"); 1286 LLVM_DEBUG(SI->dump()); 1287 1288 unfoldSelectInstrs(DT, Switch.getSelectInsts()); 1289 if (!Switch.getSelectInsts().empty()) 1290 MadeChanges = true; 1291 1292 AllSwitchPaths SwitchPaths(&Switch, ORE); 1293 SwitchPaths.run(); 1294 1295 if (SwitchPaths.getNumThreadingPaths() > 0) { 1296 ThreadableLoops.push_back(SwitchPaths); 1297 1298 // For the time being limit this optimization to occurring once in a 1299 // function since it can change the CFG significantly. This is not a 1300 // strict requirement but it can cause buggy behavior if there is an 1301 // overlap of blocks in different opportunities. There is a lot of room to 1302 // experiment with catching more opportunities here. 1303 break; 1304 } 1305 } 1306 1307 SmallPtrSet<const Value *, 32> EphValues; 1308 if (ThreadableLoops.size() > 0) 1309 CodeMetrics::collectEphemeralValues(&F, AC, EphValues); 1310 1311 for (AllSwitchPaths SwitchPaths : ThreadableLoops) { 1312 TransformDFA Transform(&SwitchPaths, DT, AC, TTI, ORE, EphValues); 1313 Transform.run(); 1314 MadeChanges = true; 1315 } 1316 1317 #ifdef EXPENSIVE_CHECKS 1318 assert(DT->verify(DominatorTree::VerificationLevel::Full)); 1319 verifyFunction(F, &dbgs()); 1320 #endif 1321 1322 return MadeChanges; 1323 } 1324 1325 } // end anonymous namespace 1326 1327 /// Integrate with the new Pass Manager 1328 PreservedAnalyses DFAJumpThreadingPass::run(Function &F, 1329 FunctionAnalysisManager &AM) { 1330 AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F); 1331 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 1332 TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F); 1333 OptimizationRemarkEmitter ORE(&F); 1334 1335 if (!DFAJumpThreading(&AC, &DT, &TTI, &ORE).run(F)) 1336 return PreservedAnalyses::all(); 1337 1338 PreservedAnalyses PA; 1339 PA.preserve<DominatorTreeAnalysis>(); 1340 return PA; 1341 } 1342