1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===// 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 // This file implements the Jump Threading pass. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Transforms/Scalar/JumpThreading.h" 14 #include "llvm/ADT/DenseMap.h" 15 #include "llvm/ADT/DenseSet.h" 16 #include "llvm/ADT/MapVector.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AliasAnalysis.h" 23 #include "llvm/Analysis/BlockFrequencyInfo.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/CFG.h" 26 #include "llvm/Analysis/ConstantFolding.h" 27 #include "llvm/Analysis/DomTreeUpdater.h" 28 #include "llvm/Analysis/GlobalsModRef.h" 29 #include "llvm/Analysis/GuardUtils.h" 30 #include "llvm/Analysis/InstructionSimplify.h" 31 #include "llvm/Analysis/LazyValueInfo.h" 32 #include "llvm/Analysis/Loads.h" 33 #include "llvm/Analysis/LoopInfo.h" 34 #include "llvm/Analysis/MemoryLocation.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/TargetTransformInfo.h" 37 #include "llvm/Analysis/ValueTracking.h" 38 #include "llvm/IR/BasicBlock.h" 39 #include "llvm/IR/CFG.h" 40 #include "llvm/IR/Constant.h" 41 #include "llvm/IR/ConstantRange.h" 42 #include "llvm/IR/Constants.h" 43 #include "llvm/IR/DataLayout.h" 44 #include "llvm/IR/Dominators.h" 45 #include "llvm/IR/Function.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Instruction.h" 48 #include "llvm/IR/Instructions.h" 49 #include "llvm/IR/IntrinsicInst.h" 50 #include "llvm/IR/Intrinsics.h" 51 #include "llvm/IR/LLVMContext.h" 52 #include "llvm/IR/MDBuilder.h" 53 #include "llvm/IR/Metadata.h" 54 #include "llvm/IR/Module.h" 55 #include "llvm/IR/PassManager.h" 56 #include "llvm/IR/PatternMatch.h" 57 #include "llvm/IR/Type.h" 58 #include "llvm/IR/Use.h" 59 #include "llvm/IR/Value.h" 60 #include "llvm/InitializePasses.h" 61 #include "llvm/Pass.h" 62 #include "llvm/Support/BlockFrequency.h" 63 #include "llvm/Support/BranchProbability.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/CommandLine.h" 66 #include "llvm/Support/Debug.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Transforms/Scalar.h" 69 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 70 #include "llvm/Transforms/Utils/Cloning.h" 71 #include "llvm/Transforms/Utils/Local.h" 72 #include "llvm/Transforms/Utils/SSAUpdater.h" 73 #include "llvm/Transforms/Utils/ValueMapper.h" 74 #include <algorithm> 75 #include <cassert> 76 #include <cstdint> 77 #include <iterator> 78 #include <memory> 79 #include <utility> 80 81 using namespace llvm; 82 using namespace jumpthreading; 83 84 #define DEBUG_TYPE "jump-threading" 85 86 STATISTIC(NumThreads, "Number of jumps threaded"); 87 STATISTIC(NumFolds, "Number of terminators folded"); 88 STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi"); 89 90 static cl::opt<unsigned> 91 BBDuplicateThreshold("jump-threading-threshold", 92 cl::desc("Max block size to duplicate for jump threading"), 93 cl::init(6), cl::Hidden); 94 95 static cl::opt<unsigned> 96 ImplicationSearchThreshold( 97 "jump-threading-implication-search-threshold", 98 cl::desc("The number of predecessors to search for a stronger " 99 "condition to use to thread over a weaker condition"), 100 cl::init(3), cl::Hidden); 101 102 static cl::opt<bool> PrintLVIAfterJumpThreading( 103 "print-lvi-after-jump-threading", 104 cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false), 105 cl::Hidden); 106 107 static cl::opt<bool> JumpThreadingFreezeSelectCond( 108 "jump-threading-freeze-select-cond", 109 cl::desc("Freeze the condition when unfolding select"), cl::init(false), 110 cl::Hidden); 111 112 static cl::opt<bool> ThreadAcrossLoopHeaders( 113 "jump-threading-across-loop-headers", 114 cl::desc("Allow JumpThreading to thread across loop headers, for testing"), 115 cl::init(false), cl::Hidden); 116 117 118 namespace { 119 120 /// This pass performs 'jump threading', which looks at blocks that have 121 /// multiple predecessors and multiple successors. If one or more of the 122 /// predecessors of the block can be proven to always jump to one of the 123 /// successors, we forward the edge from the predecessor to the successor by 124 /// duplicating the contents of this block. 125 /// 126 /// An example of when this can occur is code like this: 127 /// 128 /// if () { ... 129 /// X = 4; 130 /// } 131 /// if (X < 3) { 132 /// 133 /// In this case, the unconditional branch at the end of the first if can be 134 /// revectored to the false side of the second if. 135 class JumpThreading : public FunctionPass { 136 JumpThreadingPass Impl; 137 138 public: 139 static char ID; // Pass identification 140 141 JumpThreading(bool InsertFreezeWhenUnfoldingSelect = false, int T = -1) 142 : FunctionPass(ID), Impl(InsertFreezeWhenUnfoldingSelect, T) { 143 initializeJumpThreadingPass(*PassRegistry::getPassRegistry()); 144 } 145 146 bool runOnFunction(Function &F) override; 147 148 void getAnalysisUsage(AnalysisUsage &AU) const override { 149 AU.addRequired<DominatorTreeWrapperPass>(); 150 AU.addPreserved<DominatorTreeWrapperPass>(); 151 AU.addRequired<AAResultsWrapperPass>(); 152 AU.addRequired<LazyValueInfoWrapperPass>(); 153 AU.addPreserved<LazyValueInfoWrapperPass>(); 154 AU.addPreserved<GlobalsAAWrapperPass>(); 155 AU.addRequired<TargetLibraryInfoWrapperPass>(); 156 AU.addRequired<TargetTransformInfoWrapperPass>(); 157 } 158 }; 159 160 } // end anonymous namespace 161 162 char JumpThreading::ID = 0; 163 164 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading", 165 "Jump Threading", false, false) 166 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 167 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 168 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 169 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 170 INITIALIZE_PASS_END(JumpThreading, "jump-threading", 171 "Jump Threading", false, false) 172 173 // Public interface to the Jump Threading pass 174 FunctionPass *llvm::createJumpThreadingPass(bool InsertFr, int Threshold) { 175 return new JumpThreading(InsertFr, Threshold); 176 } 177 178 JumpThreadingPass::JumpThreadingPass(bool InsertFr, int T) { 179 InsertFreezeWhenUnfoldingSelect = JumpThreadingFreezeSelectCond | InsertFr; 180 DefaultBBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T); 181 } 182 183 // Update branch probability information according to conditional 184 // branch probability. This is usually made possible for cloned branches 185 // in inline instances by the context specific profile in the caller. 186 // For instance, 187 // 188 // [Block PredBB] 189 // [Branch PredBr] 190 // if (t) { 191 // Block A; 192 // } else { 193 // Block B; 194 // } 195 // 196 // [Block BB] 197 // cond = PN([true, %A], [..., %B]); // PHI node 198 // [Branch CondBr] 199 // if (cond) { 200 // ... // P(cond == true) = 1% 201 // } 202 // 203 // Here we know that when block A is taken, cond must be true, which means 204 // P(cond == true | A) = 1 205 // 206 // Given that P(cond == true) = P(cond == true | A) * P(A) + 207 // P(cond == true | B) * P(B) 208 // we get: 209 // P(cond == true ) = P(A) + P(cond == true | B) * P(B) 210 // 211 // which gives us: 212 // P(A) is less than P(cond == true), i.e. 213 // P(t == true) <= P(cond == true) 214 // 215 // In other words, if we know P(cond == true) is unlikely, we know 216 // that P(t == true) is also unlikely. 217 // 218 static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) { 219 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 220 if (!CondBr) 221 return; 222 223 uint64_t TrueWeight, FalseWeight; 224 if (!CondBr->extractProfMetadata(TrueWeight, FalseWeight)) 225 return; 226 227 if (TrueWeight + FalseWeight == 0) 228 // Zero branch_weights do not give a hint for getting branch probabilities. 229 // Technically it would result in division by zero denominator, which is 230 // TrueWeight + FalseWeight. 231 return; 232 233 // Returns the outgoing edge of the dominating predecessor block 234 // that leads to the PhiNode's incoming block: 235 auto GetPredOutEdge = 236 [](BasicBlock *IncomingBB, 237 BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> { 238 auto *PredBB = IncomingBB; 239 auto *SuccBB = PhiBB; 240 SmallPtrSet<BasicBlock *, 16> Visited; 241 while (true) { 242 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()); 243 if (PredBr && PredBr->isConditional()) 244 return {PredBB, SuccBB}; 245 Visited.insert(PredBB); 246 auto *SinglePredBB = PredBB->getSinglePredecessor(); 247 if (!SinglePredBB) 248 return {nullptr, nullptr}; 249 250 // Stop searching when SinglePredBB has been visited. It means we see 251 // an unreachable loop. 252 if (Visited.count(SinglePredBB)) 253 return {nullptr, nullptr}; 254 255 SuccBB = PredBB; 256 PredBB = SinglePredBB; 257 } 258 }; 259 260 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 261 Value *PhiOpnd = PN->getIncomingValue(i); 262 ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd); 263 264 if (!CI || !CI->getType()->isIntegerTy(1)) 265 continue; 266 267 BranchProbability BP = 268 (CI->isOne() ? BranchProbability::getBranchProbability( 269 TrueWeight, TrueWeight + FalseWeight) 270 : BranchProbability::getBranchProbability( 271 FalseWeight, TrueWeight + FalseWeight)); 272 273 auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB); 274 if (!PredOutEdge.first) 275 return; 276 277 BasicBlock *PredBB = PredOutEdge.first; 278 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()); 279 if (!PredBr) 280 return; 281 282 uint64_t PredTrueWeight, PredFalseWeight; 283 // FIXME: We currently only set the profile data when it is missing. 284 // With PGO, this can be used to refine even existing profile data with 285 // context information. This needs to be done after more performance 286 // testing. 287 if (PredBr->extractProfMetadata(PredTrueWeight, PredFalseWeight)) 288 continue; 289 290 // We can not infer anything useful when BP >= 50%, because BP is the 291 // upper bound probability value. 292 if (BP >= BranchProbability(50, 100)) 293 continue; 294 295 SmallVector<uint32_t, 2> Weights; 296 if (PredBr->getSuccessor(0) == PredOutEdge.second) { 297 Weights.push_back(BP.getNumerator()); 298 Weights.push_back(BP.getCompl().getNumerator()); 299 } else { 300 Weights.push_back(BP.getCompl().getNumerator()); 301 Weights.push_back(BP.getNumerator()); 302 } 303 PredBr->setMetadata(LLVMContext::MD_prof, 304 MDBuilder(PredBr->getParent()->getContext()) 305 .createBranchWeights(Weights)); 306 } 307 } 308 309 /// runOnFunction - Toplevel algorithm. 310 bool JumpThreading::runOnFunction(Function &F) { 311 if (skipFunction(F)) 312 return false; 313 auto TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 314 // Jump Threading has no sense for the targets with divergent CF 315 if (TTI->hasBranchDivergence()) 316 return false; 317 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 318 auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 319 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI(); 320 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 321 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy); 322 std::unique_ptr<BlockFrequencyInfo> BFI; 323 std::unique_ptr<BranchProbabilityInfo> BPI; 324 if (F.hasProfileData()) { 325 LoopInfo LI{DominatorTree(F)}; 326 BPI.reset(new BranchProbabilityInfo(F, LI, TLI)); 327 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); 328 } 329 330 bool Changed = Impl.runImpl(F, TLI, TTI, LVI, AA, &DTU, F.hasProfileData(), 331 BFI.get(), BPI.get()); 332 if (PrintLVIAfterJumpThreading) { 333 dbgs() << "LVI for function '" << F.getName() << "':\n"; 334 LVI->printLVI(F, DTU.getDomTree(), dbgs()); 335 } 336 return Changed; 337 } 338 339 PreservedAnalyses JumpThreadingPass::run(Function &F, 340 FunctionAnalysisManager &AM) { 341 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 342 // Jump Threading has no sense for the targets with divergent CF 343 if (TTI.hasBranchDivergence()) 344 return PreservedAnalyses::all(); 345 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 346 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 347 auto &LVI = AM.getResult<LazyValueAnalysis>(F); 348 auto &AA = AM.getResult<AAManager>(F); 349 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 350 351 BlockFrequencyInfo *BFI = nullptr; 352 BranchProbabilityInfo *BPI = nullptr; 353 if (F.hasProfileData()) { 354 BFI = &AM.getResult<BlockFrequencyAnalysis>(F); 355 BPI = &AM.getResult<BranchProbabilityAnalysis>(F); 356 } 357 358 bool Changed = 359 runImpl(F, &TLI, &TTI, &LVI, &AA, &DTU, F.hasProfileData(), BFI, BPI); 360 361 if (PrintLVIAfterJumpThreading) { 362 dbgs() << "LVI for function '" << F.getName() << "':\n"; 363 LVI.printLVI(F, DTU.getDomTree(), dbgs()); 364 } 365 366 if (!Changed) 367 return PreservedAnalyses::all(); 368 PreservedAnalyses PA; 369 PA.preserve<DominatorTreeAnalysis>(); 370 PA.preserve<LazyValueAnalysis>(); 371 return PA; 372 } 373 374 bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_, 375 TargetTransformInfo *TTI_, LazyValueInfo *LVI_, 376 AliasAnalysis *AA_, DomTreeUpdater *DTU_, 377 bool HasProfileData_, BlockFrequencyInfo *BFI_, 378 BranchProbabilityInfo *BPI_) { 379 LLVM_DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n"); 380 TLI = TLI_; 381 TTI = TTI_; 382 LVI = LVI_; 383 AA = AA_; 384 DTU = DTU_; 385 BFI = BFI_; 386 BPI = BPI_; 387 // When profile data is available, we need to update edge weights after 388 // successful jump threading, which requires both BPI and BFI being available. 389 HasProfileData = HasProfileData_; 390 auto *GuardDecl = F.getParent()->getFunction( 391 Intrinsic::getName(Intrinsic::experimental_guard)); 392 HasGuards = GuardDecl && !GuardDecl->use_empty(); 393 if (HasProfileData) { 394 assert(BFI && "BFI not provided?"); 395 assert(BPI && "BPI not provided?"); 396 } else { 397 assert(!BFI && "BFI should not be provided?"); 398 assert(!BPI && "BPI should not be provided?"); 399 } 400 401 // Reduce the number of instructions duplicated when optimizing strictly for 402 // size. 403 if (BBDuplicateThreshold.getNumOccurrences()) 404 BBDupThreshold = BBDuplicateThreshold; 405 else if (F.hasFnAttribute(Attribute::MinSize)) 406 BBDupThreshold = 3; 407 else 408 BBDupThreshold = DefaultBBDupThreshold; 409 410 // JumpThreading must not processes blocks unreachable from entry. It's a 411 // waste of compute time and can potentially lead to hangs. 412 SmallPtrSet<BasicBlock *, 16> Unreachable; 413 assert(DTU && "DTU isn't passed into JumpThreading before using it."); 414 assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed."); 415 DominatorTree &DT = DTU->getDomTree(); 416 for (auto &BB : F) 417 if (!DT.isReachableFromEntry(&BB)) 418 Unreachable.insert(&BB); 419 420 if (!ThreadAcrossLoopHeaders) 421 findLoopHeaders(F); 422 423 bool EverChanged = false; 424 bool Changed; 425 do { 426 Changed = false; 427 for (auto &BB : F) { 428 if (Unreachable.count(&BB)) 429 continue; 430 while (processBlock(&BB)) // Thread all of the branches we can over BB. 431 Changed = true; 432 433 // Jump threading may have introduced redundant debug values into BB 434 // which should be removed. 435 if (Changed) 436 RemoveRedundantDbgInstrs(&BB); 437 438 // Stop processing BB if it's the entry or is now deleted. The following 439 // routines attempt to eliminate BB and locating a suitable replacement 440 // for the entry is non-trivial. 441 if (&BB == &F.getEntryBlock() || DTU->isBBPendingDeletion(&BB)) 442 continue; 443 444 if (pred_empty(&BB)) { 445 // When processBlock makes BB unreachable it doesn't bother to fix up 446 // the instructions in it. We must remove BB to prevent invalid IR. 447 LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName() 448 << "' with terminator: " << *BB.getTerminator() 449 << '\n'); 450 LoopHeaders.erase(&BB); 451 LVI->eraseBlock(&BB); 452 DeleteDeadBlock(&BB, DTU); 453 Changed = true; 454 continue; 455 } 456 457 // processBlock doesn't thread BBs with unconditional TIs. However, if BB 458 // is "almost empty", we attempt to merge BB with its sole successor. 459 auto *BI = dyn_cast<BranchInst>(BB.getTerminator()); 460 if (BI && BI->isUnconditional()) { 461 BasicBlock *Succ = BI->getSuccessor(0); 462 if ( 463 // The terminator must be the only non-phi instruction in BB. 464 BB.getFirstNonPHIOrDbg(true)->isTerminator() && 465 // Don't alter Loop headers and latches to ensure another pass can 466 // detect and transform nested loops later. 467 !LoopHeaders.count(&BB) && !LoopHeaders.count(Succ) && 468 TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU)) { 469 RemoveRedundantDbgInstrs(Succ); 470 // BB is valid for cleanup here because we passed in DTU. F remains 471 // BB's parent until a DTU->getDomTree() event. 472 LVI->eraseBlock(&BB); 473 Changed = true; 474 } 475 } 476 } 477 EverChanged |= Changed; 478 } while (Changed); 479 480 LoopHeaders.clear(); 481 return EverChanged; 482 } 483 484 // Replace uses of Cond with ToVal when safe to do so. If all uses are 485 // replaced, we can remove Cond. We cannot blindly replace all uses of Cond 486 // because we may incorrectly replace uses when guards/assumes are uses of 487 // of `Cond` and we used the guards/assume to reason about the `Cond` value 488 // at the end of block. RAUW unconditionally replaces all uses 489 // including the guards/assumes themselves and the uses before the 490 // guard/assume. 491 static void replaceFoldableUses(Instruction *Cond, Value *ToVal) { 492 assert(Cond->getType() == ToVal->getType()); 493 auto *BB = Cond->getParent(); 494 // We can unconditionally replace all uses in non-local blocks (i.e. uses 495 // strictly dominated by BB), since LVI information is true from the 496 // terminator of BB. 497 replaceNonLocalUsesWith(Cond, ToVal); 498 for (Instruction &I : reverse(*BB)) { 499 // Reached the Cond whose uses we are trying to replace, so there are no 500 // more uses. 501 if (&I == Cond) 502 break; 503 // We only replace uses in instructions that are guaranteed to reach the end 504 // of BB, where we know Cond is ToVal. 505 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 506 break; 507 I.replaceUsesOfWith(Cond, ToVal); 508 } 509 if (Cond->use_empty() && !Cond->mayHaveSideEffects()) 510 Cond->eraseFromParent(); 511 } 512 513 /// Return the cost of duplicating a piece of this block from first non-phi 514 /// and before StopAt instruction to thread across it. Stop scanning the block 515 /// when exceeding the threshold. If duplication is impossible, returns ~0U. 516 static unsigned getJumpThreadDuplicationCost(const TargetTransformInfo *TTI, 517 BasicBlock *BB, 518 Instruction *StopAt, 519 unsigned Threshold) { 520 assert(StopAt->getParent() == BB && "Not an instruction from proper BB?"); 521 /// Ignore PHI nodes, these will be flattened when duplication happens. 522 BasicBlock::const_iterator I(BB->getFirstNonPHI()); 523 524 // FIXME: THREADING will delete values that are just used to compute the 525 // branch, so they shouldn't count against the duplication cost. 526 527 unsigned Bonus = 0; 528 if (BB->getTerminator() == StopAt) { 529 // Threading through a switch statement is particularly profitable. If this 530 // block ends in a switch, decrease its cost to make it more likely to 531 // happen. 532 if (isa<SwitchInst>(StopAt)) 533 Bonus = 6; 534 535 // The same holds for indirect branches, but slightly more so. 536 if (isa<IndirectBrInst>(StopAt)) 537 Bonus = 8; 538 } 539 540 // Bump the threshold up so the early exit from the loop doesn't skip the 541 // terminator-based Size adjustment at the end. 542 Threshold += Bonus; 543 544 // Sum up the cost of each instruction until we get to the terminator. Don't 545 // include the terminator because the copy won't include it. 546 unsigned Size = 0; 547 for (; &*I != StopAt; ++I) { 548 549 // Stop scanning the block if we've reached the threshold. 550 if (Size > Threshold) 551 return Size; 552 553 // Bail out if this instruction gives back a token type, it is not possible 554 // to duplicate it if it is used outside this BB. 555 if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB)) 556 return ~0U; 557 558 // Blocks with NoDuplicate are modelled as having infinite cost, so they 559 // are never duplicated. 560 if (const CallInst *CI = dyn_cast<CallInst>(I)) 561 if (CI->cannotDuplicate() || CI->isConvergent()) 562 return ~0U; 563 564 if (TTI->getUserCost(&*I, TargetTransformInfo::TCK_SizeAndLatency) 565 == TargetTransformInfo::TCC_Free) 566 continue; 567 568 // All other instructions count for at least one unit. 569 ++Size; 570 571 // Calls are more expensive. If they are non-intrinsic calls, we model them 572 // as having cost of 4. If they are a non-vector intrinsic, we model them 573 // as having cost of 2 total, and if they are a vector intrinsic, we model 574 // them as having cost 1. 575 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 576 if (!isa<IntrinsicInst>(CI)) 577 Size += 3; 578 else if (!CI->getType()->isVectorTy()) 579 Size += 1; 580 } 581 } 582 583 return Size > Bonus ? Size - Bonus : 0; 584 } 585 586 /// findLoopHeaders - We do not want jump threading to turn proper loop 587 /// structures into irreducible loops. Doing this breaks up the loop nesting 588 /// hierarchy and pessimizes later transformations. To prevent this from 589 /// happening, we first have to find the loop headers. Here we approximate this 590 /// by finding targets of backedges in the CFG. 591 /// 592 /// Note that there definitely are cases when we want to allow threading of 593 /// edges across a loop header. For example, threading a jump from outside the 594 /// loop (the preheader) to an exit block of the loop is definitely profitable. 595 /// It is also almost always profitable to thread backedges from within the loop 596 /// to exit blocks, and is often profitable to thread backedges to other blocks 597 /// within the loop (forming a nested loop). This simple analysis is not rich 598 /// enough to track all of these properties and keep it up-to-date as the CFG 599 /// mutates, so we don't allow any of these transformations. 600 void JumpThreadingPass::findLoopHeaders(Function &F) { 601 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges; 602 FindFunctionBackedges(F, Edges); 603 604 for (const auto &Edge : Edges) 605 LoopHeaders.insert(Edge.second); 606 } 607 608 /// getKnownConstant - Helper method to determine if we can thread over a 609 /// terminator with the given value as its condition, and if so what value to 610 /// use for that. What kind of value this is depends on whether we want an 611 /// integer or a block address, but an undef is always accepted. 612 /// Returns null if Val is null or not an appropriate constant. 613 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) { 614 if (!Val) 615 return nullptr; 616 617 // Undef is "known" enough. 618 if (UndefValue *U = dyn_cast<UndefValue>(Val)) 619 return U; 620 621 if (Preference == WantBlockAddress) 622 return dyn_cast<BlockAddress>(Val->stripPointerCasts()); 623 624 return dyn_cast<ConstantInt>(Val); 625 } 626 627 /// computeValueKnownInPredecessors - Given a basic block BB and a value V, see 628 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef 629 /// in any of our predecessors. If so, return the known list of value and pred 630 /// BB in the result vector. 631 /// 632 /// This returns true if there were any known values. 633 bool JumpThreadingPass::computeValueKnownInPredecessorsImpl( 634 Value *V, BasicBlock *BB, PredValueInfo &Result, 635 ConstantPreference Preference, DenseSet<Value *> &RecursionSet, 636 Instruction *CxtI) { 637 // This method walks up use-def chains recursively. Because of this, we could 638 // get into an infinite loop going around loops in the use-def chain. To 639 // prevent this, keep track of what (value, block) pairs we've already visited 640 // and terminate the search if we loop back to them 641 if (!RecursionSet.insert(V).second) 642 return false; 643 644 // If V is a constant, then it is known in all predecessors. 645 if (Constant *KC = getKnownConstant(V, Preference)) { 646 for (BasicBlock *Pred : predecessors(BB)) 647 Result.emplace_back(KC, Pred); 648 649 return !Result.empty(); 650 } 651 652 // If V is a non-instruction value, or an instruction in a different block, 653 // then it can't be derived from a PHI. 654 Instruction *I = dyn_cast<Instruction>(V); 655 if (!I || I->getParent() != BB) { 656 657 // Okay, if this is a live-in value, see if it has a known value at the end 658 // of any of our predecessors. 659 // 660 // FIXME: This should be an edge property, not a block end property. 661 /// TODO: Per PR2563, we could infer value range information about a 662 /// predecessor based on its terminator. 663 // 664 // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if 665 // "I" is a non-local compare-with-a-constant instruction. This would be 666 // able to handle value inequalities better, for example if the compare is 667 // "X < 4" and "X < 3" is known true but "X < 4" itself is not available. 668 // Perhaps getConstantOnEdge should be smart enough to do this? 669 for (BasicBlock *P : predecessors(BB)) { 670 // If the value is known by LazyValueInfo to be a constant in a 671 // predecessor, use that information to try to thread this block. 672 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI); 673 if (Constant *KC = getKnownConstant(PredCst, Preference)) 674 Result.emplace_back(KC, P); 675 } 676 677 return !Result.empty(); 678 } 679 680 /// If I is a PHI node, then we know the incoming values for any constants. 681 if (PHINode *PN = dyn_cast<PHINode>(I)) { 682 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 683 Value *InVal = PN->getIncomingValue(i); 684 if (Constant *KC = getKnownConstant(InVal, Preference)) { 685 Result.emplace_back(KC, PN->getIncomingBlock(i)); 686 } else { 687 Constant *CI = LVI->getConstantOnEdge(InVal, 688 PN->getIncomingBlock(i), 689 BB, CxtI); 690 if (Constant *KC = getKnownConstant(CI, Preference)) 691 Result.emplace_back(KC, PN->getIncomingBlock(i)); 692 } 693 } 694 695 return !Result.empty(); 696 } 697 698 // Handle Cast instructions. 699 if (CastInst *CI = dyn_cast<CastInst>(I)) { 700 Value *Source = CI->getOperand(0); 701 computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference, 702 RecursionSet, CxtI); 703 if (Result.empty()) 704 return false; 705 706 // Convert the known values. 707 for (auto &R : Result) 708 R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType()); 709 710 return true; 711 } 712 713 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) { 714 Value *Source = FI->getOperand(0); 715 computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference, 716 RecursionSet, CxtI); 717 718 erase_if(Result, [](auto &Pair) { 719 return !isGuaranteedNotToBeUndefOrPoison(Pair.first); 720 }); 721 722 return !Result.empty(); 723 } 724 725 // Handle some boolean conditions. 726 if (I->getType()->getPrimitiveSizeInBits() == 1) { 727 using namespace PatternMatch; 728 if (Preference != WantInteger) 729 return false; 730 // X | true -> true 731 // X & false -> false 732 Value *Op0, *Op1; 733 if (match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))) || 734 match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 735 PredValueInfoTy LHSVals, RHSVals; 736 737 computeValueKnownInPredecessorsImpl(Op0, BB, LHSVals, WantInteger, 738 RecursionSet, CxtI); 739 computeValueKnownInPredecessorsImpl(Op1, BB, RHSVals, WantInteger, 740 RecursionSet, CxtI); 741 742 if (LHSVals.empty() && RHSVals.empty()) 743 return false; 744 745 ConstantInt *InterestingVal; 746 if (match(I, m_LogicalOr())) 747 InterestingVal = ConstantInt::getTrue(I->getContext()); 748 else 749 InterestingVal = ConstantInt::getFalse(I->getContext()); 750 751 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs; 752 753 // Scan for the sentinel. If we find an undef, force it to the 754 // interesting value: x|undef -> true and x&undef -> false. 755 for (const auto &LHSVal : LHSVals) 756 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) { 757 Result.emplace_back(InterestingVal, LHSVal.second); 758 LHSKnownBBs.insert(LHSVal.second); 759 } 760 for (const auto &RHSVal : RHSVals) 761 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) { 762 // If we already inferred a value for this block on the LHS, don't 763 // re-add it. 764 if (!LHSKnownBBs.count(RHSVal.second)) 765 Result.emplace_back(InterestingVal, RHSVal.second); 766 } 767 768 return !Result.empty(); 769 } 770 771 // Handle the NOT form of XOR. 772 if (I->getOpcode() == Instruction::Xor && 773 isa<ConstantInt>(I->getOperand(1)) && 774 cast<ConstantInt>(I->getOperand(1))->isOne()) { 775 computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result, 776 WantInteger, RecursionSet, CxtI); 777 if (Result.empty()) 778 return false; 779 780 // Invert the known values. 781 for (auto &R : Result) 782 R.first = ConstantExpr::getNot(R.first); 783 784 return true; 785 } 786 787 // Try to simplify some other binary operator values. 788 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 789 if (Preference != WantInteger) 790 return false; 791 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) { 792 PredValueInfoTy LHSVals; 793 computeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals, 794 WantInteger, RecursionSet, CxtI); 795 796 // Try to use constant folding to simplify the binary operator. 797 for (const auto &LHSVal : LHSVals) { 798 Constant *V = LHSVal.first; 799 Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI); 800 801 if (Constant *KC = getKnownConstant(Folded, WantInteger)) 802 Result.emplace_back(KC, LHSVal.second); 803 } 804 } 805 806 return !Result.empty(); 807 } 808 809 // Handle compare with phi operand, where the PHI is defined in this block. 810 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 811 if (Preference != WantInteger) 812 return false; 813 Type *CmpType = Cmp->getType(); 814 Value *CmpLHS = Cmp->getOperand(0); 815 Value *CmpRHS = Cmp->getOperand(1); 816 CmpInst::Predicate Pred = Cmp->getPredicate(); 817 818 PHINode *PN = dyn_cast<PHINode>(CmpLHS); 819 if (!PN) 820 PN = dyn_cast<PHINode>(CmpRHS); 821 if (PN && PN->getParent() == BB) { 822 const DataLayout &DL = PN->getModule()->getDataLayout(); 823 // We can do this simplification if any comparisons fold to true or false. 824 // See if any do. 825 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 826 BasicBlock *PredBB = PN->getIncomingBlock(i); 827 Value *LHS, *RHS; 828 if (PN == CmpLHS) { 829 LHS = PN->getIncomingValue(i); 830 RHS = CmpRHS->DoPHITranslation(BB, PredBB); 831 } else { 832 LHS = CmpLHS->DoPHITranslation(BB, PredBB); 833 RHS = PN->getIncomingValue(i); 834 } 835 Value *Res = SimplifyCmpInst(Pred, LHS, RHS, {DL}); 836 if (!Res) { 837 if (!isa<Constant>(RHS)) 838 continue; 839 840 // getPredicateOnEdge call will make no sense if LHS is defined in BB. 841 auto LHSInst = dyn_cast<Instruction>(LHS); 842 if (LHSInst && LHSInst->getParent() == BB) 843 continue; 844 845 LazyValueInfo::Tristate 846 ResT = LVI->getPredicateOnEdge(Pred, LHS, 847 cast<Constant>(RHS), PredBB, BB, 848 CxtI ? CxtI : Cmp); 849 if (ResT == LazyValueInfo::Unknown) 850 continue; 851 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT); 852 } 853 854 if (Constant *KC = getKnownConstant(Res, WantInteger)) 855 Result.emplace_back(KC, PredBB); 856 } 857 858 return !Result.empty(); 859 } 860 861 // If comparing a live-in value against a constant, see if we know the 862 // live-in value on any predecessors. 863 if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) { 864 Constant *CmpConst = cast<Constant>(CmpRHS); 865 866 if (!isa<Instruction>(CmpLHS) || 867 cast<Instruction>(CmpLHS)->getParent() != BB) { 868 for (BasicBlock *P : predecessors(BB)) { 869 // If the value is known by LazyValueInfo to be a constant in a 870 // predecessor, use that information to try to thread this block. 871 LazyValueInfo::Tristate Res = 872 LVI->getPredicateOnEdge(Pred, CmpLHS, 873 CmpConst, P, BB, CxtI ? CxtI : Cmp); 874 if (Res == LazyValueInfo::Unknown) 875 continue; 876 877 Constant *ResC = ConstantInt::get(CmpType, Res); 878 Result.emplace_back(ResC, P); 879 } 880 881 return !Result.empty(); 882 } 883 884 // InstCombine can fold some forms of constant range checks into 885 // (icmp (add (x, C1)), C2). See if we have we have such a thing with 886 // x as a live-in. 887 { 888 using namespace PatternMatch; 889 890 Value *AddLHS; 891 ConstantInt *AddConst; 892 if (isa<ConstantInt>(CmpConst) && 893 match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) { 894 if (!isa<Instruction>(AddLHS) || 895 cast<Instruction>(AddLHS)->getParent() != BB) { 896 for (BasicBlock *P : predecessors(BB)) { 897 // If the value is known by LazyValueInfo to be a ConstantRange in 898 // a predecessor, use that information to try to thread this 899 // block. 900 ConstantRange CR = LVI->getConstantRangeOnEdge( 901 AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS)); 902 // Propagate the range through the addition. 903 CR = CR.add(AddConst->getValue()); 904 905 // Get the range where the compare returns true. 906 ConstantRange CmpRange = ConstantRange::makeExactICmpRegion( 907 Pred, cast<ConstantInt>(CmpConst)->getValue()); 908 909 Constant *ResC; 910 if (CmpRange.contains(CR)) 911 ResC = ConstantInt::getTrue(CmpType); 912 else if (CmpRange.inverse().contains(CR)) 913 ResC = ConstantInt::getFalse(CmpType); 914 else 915 continue; 916 917 Result.emplace_back(ResC, P); 918 } 919 920 return !Result.empty(); 921 } 922 } 923 } 924 925 // Try to find a constant value for the LHS of a comparison, 926 // and evaluate it statically if we can. 927 PredValueInfoTy LHSVals; 928 computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals, 929 WantInteger, RecursionSet, CxtI); 930 931 for (const auto &LHSVal : LHSVals) { 932 Constant *V = LHSVal.first; 933 Constant *Folded = ConstantExpr::getCompare(Pred, V, CmpConst); 934 if (Constant *KC = getKnownConstant(Folded, WantInteger)) 935 Result.emplace_back(KC, LHSVal.second); 936 } 937 938 return !Result.empty(); 939 } 940 } 941 942 if (SelectInst *SI = dyn_cast<SelectInst>(I)) { 943 // Handle select instructions where at least one operand is a known constant 944 // and we can figure out the condition value for any predecessor block. 945 Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference); 946 Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference); 947 PredValueInfoTy Conds; 948 if ((TrueVal || FalseVal) && 949 computeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds, 950 WantInteger, RecursionSet, CxtI)) { 951 for (auto &C : Conds) { 952 Constant *Cond = C.first; 953 954 // Figure out what value to use for the condition. 955 bool KnownCond; 956 if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) { 957 // A known boolean. 958 KnownCond = CI->isOne(); 959 } else { 960 assert(isa<UndefValue>(Cond) && "Unexpected condition value"); 961 // Either operand will do, so be sure to pick the one that's a known 962 // constant. 963 // FIXME: Do this more cleverly if both values are known constants? 964 KnownCond = (TrueVal != nullptr); 965 } 966 967 // See if the select has a known constant value for this predecessor. 968 if (Constant *Val = KnownCond ? TrueVal : FalseVal) 969 Result.emplace_back(Val, C.second); 970 } 971 972 return !Result.empty(); 973 } 974 } 975 976 // If all else fails, see if LVI can figure out a constant value for us. 977 assert(CxtI->getParent() == BB && "CxtI should be in BB"); 978 Constant *CI = LVI->getConstant(V, CxtI); 979 if (Constant *KC = getKnownConstant(CI, Preference)) { 980 for (BasicBlock *Pred : predecessors(BB)) 981 Result.emplace_back(KC, Pred); 982 } 983 984 return !Result.empty(); 985 } 986 987 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends 988 /// in an undefined jump, decide which block is best to revector to. 989 /// 990 /// Since we can pick an arbitrary destination, we pick the successor with the 991 /// fewest predecessors. This should reduce the in-degree of the others. 992 static unsigned getBestDestForJumpOnUndef(BasicBlock *BB) { 993 Instruction *BBTerm = BB->getTerminator(); 994 unsigned MinSucc = 0; 995 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc); 996 // Compute the successor with the minimum number of predecessors. 997 unsigned MinNumPreds = pred_size(TestBB); 998 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) { 999 TestBB = BBTerm->getSuccessor(i); 1000 unsigned NumPreds = pred_size(TestBB); 1001 if (NumPreds < MinNumPreds) { 1002 MinSucc = i; 1003 MinNumPreds = NumPreds; 1004 } 1005 } 1006 1007 return MinSucc; 1008 } 1009 1010 static bool hasAddressTakenAndUsed(BasicBlock *BB) { 1011 if (!BB->hasAddressTaken()) return false; 1012 1013 // If the block has its address taken, it may be a tree of dead constants 1014 // hanging off of it. These shouldn't keep the block alive. 1015 BlockAddress *BA = BlockAddress::get(BB); 1016 BA->removeDeadConstantUsers(); 1017 return !BA->use_empty(); 1018 } 1019 1020 /// processBlock - If there are any predecessors whose control can be threaded 1021 /// through to a successor, transform them now. 1022 bool JumpThreadingPass::processBlock(BasicBlock *BB) { 1023 // If the block is trivially dead, just return and let the caller nuke it. 1024 // This simplifies other transformations. 1025 if (DTU->isBBPendingDeletion(BB) || 1026 (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock())) 1027 return false; 1028 1029 // If this block has a single predecessor, and if that pred has a single 1030 // successor, merge the blocks. This encourages recursive jump threading 1031 // because now the condition in this block can be threaded through 1032 // predecessors of our predecessor block. 1033 if (maybeMergeBasicBlockIntoOnlyPred(BB)) 1034 return true; 1035 1036 if (tryToUnfoldSelectInCurrBB(BB)) 1037 return true; 1038 1039 // Look if we can propagate guards to predecessors. 1040 if (HasGuards && processGuards(BB)) 1041 return true; 1042 1043 // What kind of constant we're looking for. 1044 ConstantPreference Preference = WantInteger; 1045 1046 // Look to see if the terminator is a conditional branch, switch or indirect 1047 // branch, if not we can't thread it. 1048 Value *Condition; 1049 Instruction *Terminator = BB->getTerminator(); 1050 if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) { 1051 // Can't thread an unconditional jump. 1052 if (BI->isUnconditional()) return false; 1053 Condition = BI->getCondition(); 1054 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) { 1055 Condition = SI->getCondition(); 1056 } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) { 1057 // Can't thread indirect branch with no successors. 1058 if (IB->getNumSuccessors() == 0) return false; 1059 Condition = IB->getAddress()->stripPointerCasts(); 1060 Preference = WantBlockAddress; 1061 } else { 1062 return false; // Must be an invoke or callbr. 1063 } 1064 1065 // Keep track if we constant folded the condition in this invocation. 1066 bool ConstantFolded = false; 1067 1068 // Run constant folding to see if we can reduce the condition to a simple 1069 // constant. 1070 if (Instruction *I = dyn_cast<Instruction>(Condition)) { 1071 Value *SimpleVal = 1072 ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI); 1073 if (SimpleVal) { 1074 I->replaceAllUsesWith(SimpleVal); 1075 if (isInstructionTriviallyDead(I, TLI)) 1076 I->eraseFromParent(); 1077 Condition = SimpleVal; 1078 ConstantFolded = true; 1079 } 1080 } 1081 1082 // If the terminator is branching on an undef or freeze undef, we can pick any 1083 // of the successors to branch to. Let getBestDestForJumpOnUndef decide. 1084 auto *FI = dyn_cast<FreezeInst>(Condition); 1085 if (isa<UndefValue>(Condition) || 1086 (FI && isa<UndefValue>(FI->getOperand(0)) && FI->hasOneUse())) { 1087 unsigned BestSucc = getBestDestForJumpOnUndef(BB); 1088 std::vector<DominatorTree::UpdateType> Updates; 1089 1090 // Fold the branch/switch. 1091 Instruction *BBTerm = BB->getTerminator(); 1092 Updates.reserve(BBTerm->getNumSuccessors()); 1093 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) { 1094 if (i == BestSucc) continue; 1095 BasicBlock *Succ = BBTerm->getSuccessor(i); 1096 Succ->removePredecessor(BB, true); 1097 Updates.push_back({DominatorTree::Delete, BB, Succ}); 1098 } 1099 1100 LLVM_DEBUG(dbgs() << " In block '" << BB->getName() 1101 << "' folding undef terminator: " << *BBTerm << '\n'); 1102 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm); 1103 ++NumFolds; 1104 BBTerm->eraseFromParent(); 1105 DTU->applyUpdatesPermissive(Updates); 1106 if (FI) 1107 FI->eraseFromParent(); 1108 return true; 1109 } 1110 1111 // If the terminator of this block is branching on a constant, simplify the 1112 // terminator to an unconditional branch. This can occur due to threading in 1113 // other blocks. 1114 if (getKnownConstant(Condition, Preference)) { 1115 LLVM_DEBUG(dbgs() << " In block '" << BB->getName() 1116 << "' folding terminator: " << *BB->getTerminator() 1117 << '\n'); 1118 ++NumFolds; 1119 ConstantFoldTerminator(BB, true, nullptr, DTU); 1120 if (HasProfileData) 1121 BPI->eraseBlock(BB); 1122 return true; 1123 } 1124 1125 Instruction *CondInst = dyn_cast<Instruction>(Condition); 1126 1127 // All the rest of our checks depend on the condition being an instruction. 1128 if (!CondInst) { 1129 // FIXME: Unify this with code below. 1130 if (processThreadableEdges(Condition, BB, Preference, Terminator)) 1131 return true; 1132 return ConstantFolded; 1133 } 1134 1135 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) { 1136 // If we're branching on a conditional, LVI might be able to determine 1137 // it's value at the branch instruction. We only handle comparisons 1138 // against a constant at this time. 1139 // TODO: This should be extended to handle switches as well. 1140 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 1141 Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1)); 1142 if (CondBr && CondConst) { 1143 // We should have returned as soon as we turn a conditional branch to 1144 // unconditional. Because its no longer interesting as far as jump 1145 // threading is concerned. 1146 assert(CondBr->isConditional() && "Threading on unconditional terminator"); 1147 1148 LazyValueInfo::Tristate Ret = 1149 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0), 1150 CondConst, CondBr, /*UseBlockValue=*/false); 1151 if (Ret != LazyValueInfo::Unknown) { 1152 unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0; 1153 unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1; 1154 BasicBlock *ToRemoveSucc = CondBr->getSuccessor(ToRemove); 1155 ToRemoveSucc->removePredecessor(BB, true); 1156 BranchInst *UncondBr = 1157 BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr); 1158 UncondBr->setDebugLoc(CondBr->getDebugLoc()); 1159 ++NumFolds; 1160 CondBr->eraseFromParent(); 1161 if (CondCmp->use_empty()) 1162 CondCmp->eraseFromParent(); 1163 // We can safely replace *some* uses of the CondInst if it has 1164 // exactly one value as returned by LVI. RAUW is incorrect in the 1165 // presence of guards and assumes, that have the `Cond` as the use. This 1166 // is because we use the guards/assume to reason about the `Cond` value 1167 // at the end of block, but RAUW unconditionally replaces all uses 1168 // including the guards/assumes themselves and the uses before the 1169 // guard/assume. 1170 else if (CondCmp->getParent() == BB) { 1171 auto *CI = Ret == LazyValueInfo::True ? 1172 ConstantInt::getTrue(CondCmp->getType()) : 1173 ConstantInt::getFalse(CondCmp->getType()); 1174 replaceFoldableUses(CondCmp, CI); 1175 } 1176 DTU->applyUpdatesPermissive( 1177 {{DominatorTree::Delete, BB, ToRemoveSucc}}); 1178 if (HasProfileData) 1179 BPI->eraseBlock(BB); 1180 return true; 1181 } 1182 1183 // We did not manage to simplify this branch, try to see whether 1184 // CondCmp depends on a known phi-select pattern. 1185 if (tryToUnfoldSelect(CondCmp, BB)) 1186 return true; 1187 } 1188 } 1189 1190 if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) 1191 if (tryToUnfoldSelect(SI, BB)) 1192 return true; 1193 1194 // Check for some cases that are worth simplifying. Right now we want to look 1195 // for loads that are used by a switch or by the condition for the branch. If 1196 // we see one, check to see if it's partially redundant. If so, insert a PHI 1197 // which can then be used to thread the values. 1198 Value *SimplifyValue = CondInst; 1199 1200 if (auto *FI = dyn_cast<FreezeInst>(SimplifyValue)) 1201 // Look into freeze's operand 1202 SimplifyValue = FI->getOperand(0); 1203 1204 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue)) 1205 if (isa<Constant>(CondCmp->getOperand(1))) 1206 SimplifyValue = CondCmp->getOperand(0); 1207 1208 // TODO: There are other places where load PRE would be profitable, such as 1209 // more complex comparisons. 1210 if (LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue)) 1211 if (simplifyPartiallyRedundantLoad(LoadI)) 1212 return true; 1213 1214 // Before threading, try to propagate profile data backwards: 1215 if (PHINode *PN = dyn_cast<PHINode>(CondInst)) 1216 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 1217 updatePredecessorProfileMetadata(PN, BB); 1218 1219 // Handle a variety of cases where we are branching on something derived from 1220 // a PHI node in the current block. If we can prove that any predecessors 1221 // compute a predictable value based on a PHI node, thread those predecessors. 1222 if (processThreadableEdges(CondInst, BB, Preference, Terminator)) 1223 return true; 1224 1225 // If this is an otherwise-unfoldable branch on a phi node or freeze(phi) in 1226 // the current block, see if we can simplify. 1227 PHINode *PN = dyn_cast<PHINode>( 1228 isa<FreezeInst>(CondInst) ? cast<FreezeInst>(CondInst)->getOperand(0) 1229 : CondInst); 1230 1231 if (PN && PN->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 1232 return processBranchOnPHI(PN); 1233 1234 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify. 1235 if (CondInst->getOpcode() == Instruction::Xor && 1236 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 1237 return processBranchOnXOR(cast<BinaryOperator>(CondInst)); 1238 1239 // Search for a stronger dominating condition that can be used to simplify a 1240 // conditional branch leaving BB. 1241 if (processImpliedCondition(BB)) 1242 return true; 1243 1244 return false; 1245 } 1246 1247 bool JumpThreadingPass::processImpliedCondition(BasicBlock *BB) { 1248 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 1249 if (!BI || !BI->isConditional()) 1250 return false; 1251 1252 Value *Cond = BI->getCondition(); 1253 BasicBlock *CurrentBB = BB; 1254 BasicBlock *CurrentPred = BB->getSinglePredecessor(); 1255 unsigned Iter = 0; 1256 1257 auto &DL = BB->getModule()->getDataLayout(); 1258 1259 while (CurrentPred && Iter++ < ImplicationSearchThreshold) { 1260 auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator()); 1261 if (!PBI || !PBI->isConditional()) 1262 return false; 1263 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB) 1264 return false; 1265 1266 bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB; 1267 Optional<bool> Implication = 1268 isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue); 1269 if (Implication) { 1270 BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1); 1271 BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0); 1272 RemoveSucc->removePredecessor(BB); 1273 BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI); 1274 UncondBI->setDebugLoc(BI->getDebugLoc()); 1275 ++NumFolds; 1276 BI->eraseFromParent(); 1277 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}}); 1278 if (HasProfileData) 1279 BPI->eraseBlock(BB); 1280 return true; 1281 } 1282 CurrentBB = CurrentPred; 1283 CurrentPred = CurrentBB->getSinglePredecessor(); 1284 } 1285 1286 return false; 1287 } 1288 1289 /// Return true if Op is an instruction defined in the given block. 1290 static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) { 1291 if (Instruction *OpInst = dyn_cast<Instruction>(Op)) 1292 if (OpInst->getParent() == BB) 1293 return true; 1294 return false; 1295 } 1296 1297 /// simplifyPartiallyRedundantLoad - If LoadI is an obviously partially 1298 /// redundant load instruction, eliminate it by replacing it with a PHI node. 1299 /// This is an important optimization that encourages jump threading, and needs 1300 /// to be run interlaced with other jump threading tasks. 1301 bool JumpThreadingPass::simplifyPartiallyRedundantLoad(LoadInst *LoadI) { 1302 // Don't hack volatile and ordered loads. 1303 if (!LoadI->isUnordered()) return false; 1304 1305 // If the load is defined in a block with exactly one predecessor, it can't be 1306 // partially redundant. 1307 BasicBlock *LoadBB = LoadI->getParent(); 1308 if (LoadBB->getSinglePredecessor()) 1309 return false; 1310 1311 // If the load is defined in an EH pad, it can't be partially redundant, 1312 // because the edges between the invoke and the EH pad cannot have other 1313 // instructions between them. 1314 if (LoadBB->isEHPad()) 1315 return false; 1316 1317 Value *LoadedPtr = LoadI->getOperand(0); 1318 1319 // If the loaded operand is defined in the LoadBB and its not a phi, 1320 // it can't be available in predecessors. 1321 if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr)) 1322 return false; 1323 1324 // Scan a few instructions up from the load, to see if it is obviously live at 1325 // the entry to its block. 1326 BasicBlock::iterator BBIt(LoadI); 1327 bool IsLoadCSE; 1328 if (Value *AvailableVal = FindAvailableLoadedValue( 1329 LoadI, LoadBB, BBIt, DefMaxInstsToScan, AA, &IsLoadCSE)) { 1330 // If the value of the load is locally available within the block, just use 1331 // it. This frequently occurs for reg2mem'd allocas. 1332 1333 if (IsLoadCSE) { 1334 LoadInst *NLoadI = cast<LoadInst>(AvailableVal); 1335 combineMetadataForCSE(NLoadI, LoadI, false); 1336 }; 1337 1338 // If the returned value is the load itself, replace with an undef. This can 1339 // only happen in dead loops. 1340 if (AvailableVal == LoadI) 1341 AvailableVal = UndefValue::get(LoadI->getType()); 1342 if (AvailableVal->getType() != LoadI->getType()) 1343 AvailableVal = CastInst::CreateBitOrPointerCast( 1344 AvailableVal, LoadI->getType(), "", LoadI); 1345 LoadI->replaceAllUsesWith(AvailableVal); 1346 LoadI->eraseFromParent(); 1347 return true; 1348 } 1349 1350 // Otherwise, if we scanned the whole block and got to the top of the block, 1351 // we know the block is locally transparent to the load. If not, something 1352 // might clobber its value. 1353 if (BBIt != LoadBB->begin()) 1354 return false; 1355 1356 // If all of the loads and stores that feed the value have the same AA tags, 1357 // then we can propagate them onto any newly inserted loads. 1358 AAMDNodes AATags = LoadI->getAAMetadata(); 1359 1360 SmallPtrSet<BasicBlock*, 8> PredsScanned; 1361 1362 using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>; 1363 1364 AvailablePredsTy AvailablePreds; 1365 BasicBlock *OneUnavailablePred = nullptr; 1366 SmallVector<LoadInst*, 8> CSELoads; 1367 1368 // If we got here, the loaded value is transparent through to the start of the 1369 // block. Check to see if it is available in any of the predecessor blocks. 1370 for (BasicBlock *PredBB : predecessors(LoadBB)) { 1371 // If we already scanned this predecessor, skip it. 1372 if (!PredsScanned.insert(PredBB).second) 1373 continue; 1374 1375 BBIt = PredBB->end(); 1376 unsigned NumScanedInst = 0; 1377 Value *PredAvailable = nullptr; 1378 // NOTE: We don't CSE load that is volatile or anything stronger than 1379 // unordered, that should have been checked when we entered the function. 1380 assert(LoadI->isUnordered() && 1381 "Attempting to CSE volatile or atomic loads"); 1382 // If this is a load on a phi pointer, phi-translate it and search 1383 // for available load/store to the pointer in predecessors. 1384 Type *AccessTy = LoadI->getType(); 1385 const auto &DL = LoadI->getModule()->getDataLayout(); 1386 MemoryLocation Loc(LoadedPtr->DoPHITranslation(LoadBB, PredBB), 1387 LocationSize::precise(DL.getTypeStoreSize(AccessTy)), 1388 AATags); 1389 PredAvailable = findAvailablePtrLoadStore(Loc, AccessTy, LoadI->isAtomic(), 1390 PredBB, BBIt, DefMaxInstsToScan, 1391 AA, &IsLoadCSE, &NumScanedInst); 1392 1393 // If PredBB has a single predecessor, continue scanning through the 1394 // single predecessor. 1395 BasicBlock *SinglePredBB = PredBB; 1396 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() && 1397 NumScanedInst < DefMaxInstsToScan) { 1398 SinglePredBB = SinglePredBB->getSinglePredecessor(); 1399 if (SinglePredBB) { 1400 BBIt = SinglePredBB->end(); 1401 PredAvailable = findAvailablePtrLoadStore( 1402 Loc, AccessTy, LoadI->isAtomic(), SinglePredBB, BBIt, 1403 (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE, 1404 &NumScanedInst); 1405 } 1406 } 1407 1408 if (!PredAvailable) { 1409 OneUnavailablePred = PredBB; 1410 continue; 1411 } 1412 1413 if (IsLoadCSE) 1414 CSELoads.push_back(cast<LoadInst>(PredAvailable)); 1415 1416 // If so, this load is partially redundant. Remember this info so that we 1417 // can create a PHI node. 1418 AvailablePreds.emplace_back(PredBB, PredAvailable); 1419 } 1420 1421 // If the loaded value isn't available in any predecessor, it isn't partially 1422 // redundant. 1423 if (AvailablePreds.empty()) return false; 1424 1425 // Okay, the loaded value is available in at least one (and maybe all!) 1426 // predecessors. If the value is unavailable in more than one unique 1427 // predecessor, we want to insert a merge block for those common predecessors. 1428 // This ensures that we only have to insert one reload, thus not increasing 1429 // code size. 1430 BasicBlock *UnavailablePred = nullptr; 1431 1432 // If the value is unavailable in one of predecessors, we will end up 1433 // inserting a new instruction into them. It is only valid if all the 1434 // instructions before LoadI are guaranteed to pass execution to its 1435 // successor, or if LoadI is safe to speculate. 1436 // TODO: If this logic becomes more complex, and we will perform PRE insertion 1437 // farther than to a predecessor, we need to reuse the code from GVN's PRE. 1438 // It requires domination tree analysis, so for this simple case it is an 1439 // overkill. 1440 if (PredsScanned.size() != AvailablePreds.size() && 1441 !isSafeToSpeculativelyExecute(LoadI)) 1442 for (auto I = LoadBB->begin(); &*I != LoadI; ++I) 1443 if (!isGuaranteedToTransferExecutionToSuccessor(&*I)) 1444 return false; 1445 1446 // If there is exactly one predecessor where the value is unavailable, the 1447 // already computed 'OneUnavailablePred' block is it. If it ends in an 1448 // unconditional branch, we know that it isn't a critical edge. 1449 if (PredsScanned.size() == AvailablePreds.size()+1 && 1450 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) { 1451 UnavailablePred = OneUnavailablePred; 1452 } else if (PredsScanned.size() != AvailablePreds.size()) { 1453 // Otherwise, we had multiple unavailable predecessors or we had a critical 1454 // edge from the one. 1455 SmallVector<BasicBlock*, 8> PredsToSplit; 1456 SmallPtrSet<BasicBlock*, 8> AvailablePredSet; 1457 1458 for (const auto &AvailablePred : AvailablePreds) 1459 AvailablePredSet.insert(AvailablePred.first); 1460 1461 // Add all the unavailable predecessors to the PredsToSplit list. 1462 for (BasicBlock *P : predecessors(LoadBB)) { 1463 // If the predecessor is an indirect goto, we can't split the edge. 1464 // Same for CallBr. 1465 if (isa<IndirectBrInst>(P->getTerminator()) || 1466 isa<CallBrInst>(P->getTerminator())) 1467 return false; 1468 1469 if (!AvailablePredSet.count(P)) 1470 PredsToSplit.push_back(P); 1471 } 1472 1473 // Split them out to their own block. 1474 UnavailablePred = splitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split"); 1475 } 1476 1477 // If the value isn't available in all predecessors, then there will be 1478 // exactly one where it isn't available. Insert a load on that edge and add 1479 // it to the AvailablePreds list. 1480 if (UnavailablePred) { 1481 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 && 1482 "Can't handle critical edge here!"); 1483 LoadInst *NewVal = new LoadInst( 1484 LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred), 1485 LoadI->getName() + ".pr", false, LoadI->getAlign(), 1486 LoadI->getOrdering(), LoadI->getSyncScopeID(), 1487 UnavailablePred->getTerminator()); 1488 NewVal->setDebugLoc(LoadI->getDebugLoc()); 1489 if (AATags) 1490 NewVal->setAAMetadata(AATags); 1491 1492 AvailablePreds.emplace_back(UnavailablePred, NewVal); 1493 } 1494 1495 // Now we know that each predecessor of this block has a value in 1496 // AvailablePreds, sort them for efficient access as we're walking the preds. 1497 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end()); 1498 1499 // Create a PHI node at the start of the block for the PRE'd load value. 1500 pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB); 1501 PHINode *PN = PHINode::Create(LoadI->getType(), std::distance(PB, PE), "", 1502 &LoadBB->front()); 1503 PN->takeName(LoadI); 1504 PN->setDebugLoc(LoadI->getDebugLoc()); 1505 1506 // Insert new entries into the PHI for each predecessor. A single block may 1507 // have multiple entries here. 1508 for (pred_iterator PI = PB; PI != PE; ++PI) { 1509 BasicBlock *P = *PI; 1510 AvailablePredsTy::iterator I = 1511 llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr)); 1512 1513 assert(I != AvailablePreds.end() && I->first == P && 1514 "Didn't find entry for predecessor!"); 1515 1516 // If we have an available predecessor but it requires casting, insert the 1517 // cast in the predecessor and use the cast. Note that we have to update the 1518 // AvailablePreds vector as we go so that all of the PHI entries for this 1519 // predecessor use the same bitcast. 1520 Value *&PredV = I->second; 1521 if (PredV->getType() != LoadI->getType()) 1522 PredV = CastInst::CreateBitOrPointerCast(PredV, LoadI->getType(), "", 1523 P->getTerminator()); 1524 1525 PN->addIncoming(PredV, I->first); 1526 } 1527 1528 for (LoadInst *PredLoadI : CSELoads) { 1529 combineMetadataForCSE(PredLoadI, LoadI, true); 1530 } 1531 1532 LoadI->replaceAllUsesWith(PN); 1533 LoadI->eraseFromParent(); 1534 1535 return true; 1536 } 1537 1538 /// findMostPopularDest - The specified list contains multiple possible 1539 /// threadable destinations. Pick the one that occurs the most frequently in 1540 /// the list. 1541 static BasicBlock * 1542 findMostPopularDest(BasicBlock *BB, 1543 const SmallVectorImpl<std::pair<BasicBlock *, 1544 BasicBlock *>> &PredToDestList) { 1545 assert(!PredToDestList.empty()); 1546 1547 // Determine popularity. If there are multiple possible destinations, we 1548 // explicitly choose to ignore 'undef' destinations. We prefer to thread 1549 // blocks with known and real destinations to threading undef. We'll handle 1550 // them later if interesting. 1551 MapVector<BasicBlock *, unsigned> DestPopularity; 1552 1553 // Populate DestPopularity with the successors in the order they appear in the 1554 // successor list. This way, we ensure determinism by iterating it in the 1555 // same order in std::max_element below. We map nullptr to 0 so that we can 1556 // return nullptr when PredToDestList contains nullptr only. 1557 DestPopularity[nullptr] = 0; 1558 for (auto *SuccBB : successors(BB)) 1559 DestPopularity[SuccBB] = 0; 1560 1561 for (const auto &PredToDest : PredToDestList) 1562 if (PredToDest.second) 1563 DestPopularity[PredToDest.second]++; 1564 1565 // Find the most popular dest. 1566 using VT = decltype(DestPopularity)::value_type; 1567 auto MostPopular = std::max_element( 1568 DestPopularity.begin(), DestPopularity.end(), 1569 [](const VT &L, const VT &R) { return L.second < R.second; }); 1570 1571 // Okay, we have finally picked the most popular destination. 1572 return MostPopular->first; 1573 } 1574 1575 // Try to evaluate the value of V when the control flows from PredPredBB to 1576 // BB->getSinglePredecessor() and then on to BB. 1577 Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB, 1578 BasicBlock *PredPredBB, 1579 Value *V) { 1580 BasicBlock *PredBB = BB->getSinglePredecessor(); 1581 assert(PredBB && "Expected a single predecessor"); 1582 1583 if (Constant *Cst = dyn_cast<Constant>(V)) { 1584 return Cst; 1585 } 1586 1587 // Consult LVI if V is not an instruction in BB or PredBB. 1588 Instruction *I = dyn_cast<Instruction>(V); 1589 if (!I || (I->getParent() != BB && I->getParent() != PredBB)) { 1590 return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr); 1591 } 1592 1593 // Look into a PHI argument. 1594 if (PHINode *PHI = dyn_cast<PHINode>(V)) { 1595 if (PHI->getParent() == PredBB) 1596 return dyn_cast<Constant>(PHI->getIncomingValueForBlock(PredPredBB)); 1597 return nullptr; 1598 } 1599 1600 // If we have a CmpInst, try to fold it for each incoming edge into PredBB. 1601 if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) { 1602 if (CondCmp->getParent() == BB) { 1603 Constant *Op0 = 1604 evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0)); 1605 Constant *Op1 = 1606 evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1)); 1607 if (Op0 && Op1) { 1608 return ConstantExpr::getCompare(CondCmp->getPredicate(), Op0, Op1); 1609 } 1610 } 1611 return nullptr; 1612 } 1613 1614 return nullptr; 1615 } 1616 1617 bool JumpThreadingPass::processThreadableEdges(Value *Cond, BasicBlock *BB, 1618 ConstantPreference Preference, 1619 Instruction *CxtI) { 1620 // If threading this would thread across a loop header, don't even try to 1621 // thread the edge. 1622 if (LoopHeaders.count(BB)) 1623 return false; 1624 1625 PredValueInfoTy PredValues; 1626 if (!computeValueKnownInPredecessors(Cond, BB, PredValues, Preference, 1627 CxtI)) { 1628 // We don't have known values in predecessors. See if we can thread through 1629 // BB and its sole predecessor. 1630 return maybethreadThroughTwoBasicBlocks(BB, Cond); 1631 } 1632 1633 assert(!PredValues.empty() && 1634 "computeValueKnownInPredecessors returned true with no values"); 1635 1636 LLVM_DEBUG(dbgs() << "IN BB: " << *BB; 1637 for (const auto &PredValue : PredValues) { 1638 dbgs() << " BB '" << BB->getName() 1639 << "': FOUND condition = " << *PredValue.first 1640 << " for pred '" << PredValue.second->getName() << "'.\n"; 1641 }); 1642 1643 // Decide what we want to thread through. Convert our list of known values to 1644 // a list of known destinations for each pred. This also discards duplicate 1645 // predecessors and keeps track of the undefined inputs (which are represented 1646 // as a null dest in the PredToDestList). 1647 SmallPtrSet<BasicBlock*, 16> SeenPreds; 1648 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList; 1649 1650 BasicBlock *OnlyDest = nullptr; 1651 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL; 1652 Constant *OnlyVal = nullptr; 1653 Constant *MultipleVal = (Constant *)(intptr_t)~0ULL; 1654 1655 for (const auto &PredValue : PredValues) { 1656 BasicBlock *Pred = PredValue.second; 1657 if (!SeenPreds.insert(Pred).second) 1658 continue; // Duplicate predecessor entry. 1659 1660 Constant *Val = PredValue.first; 1661 1662 BasicBlock *DestBB; 1663 if (isa<UndefValue>(Val)) 1664 DestBB = nullptr; 1665 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 1666 assert(isa<ConstantInt>(Val) && "Expecting a constant integer"); 1667 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero()); 1668 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 1669 assert(isa<ConstantInt>(Val) && "Expecting a constant integer"); 1670 DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor(); 1671 } else { 1672 assert(isa<IndirectBrInst>(BB->getTerminator()) 1673 && "Unexpected terminator"); 1674 assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress"); 1675 DestBB = cast<BlockAddress>(Val)->getBasicBlock(); 1676 } 1677 1678 // If we have exactly one destination, remember it for efficiency below. 1679 if (PredToDestList.empty()) { 1680 OnlyDest = DestBB; 1681 OnlyVal = Val; 1682 } else { 1683 if (OnlyDest != DestBB) 1684 OnlyDest = MultipleDestSentinel; 1685 // It possible we have same destination, but different value, e.g. default 1686 // case in switchinst. 1687 if (Val != OnlyVal) 1688 OnlyVal = MultipleVal; 1689 } 1690 1691 // If the predecessor ends with an indirect goto, we can't change its 1692 // destination. Same for CallBr. 1693 if (isa<IndirectBrInst>(Pred->getTerminator()) || 1694 isa<CallBrInst>(Pred->getTerminator())) 1695 continue; 1696 1697 PredToDestList.emplace_back(Pred, DestBB); 1698 } 1699 1700 // If all edges were unthreadable, we fail. 1701 if (PredToDestList.empty()) 1702 return false; 1703 1704 // If all the predecessors go to a single known successor, we want to fold, 1705 // not thread. By doing so, we do not need to duplicate the current block and 1706 // also miss potential opportunities in case we dont/cant duplicate. 1707 if (OnlyDest && OnlyDest != MultipleDestSentinel) { 1708 if (BB->hasNPredecessors(PredToDestList.size())) { 1709 bool SeenFirstBranchToOnlyDest = false; 1710 std::vector <DominatorTree::UpdateType> Updates; 1711 Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1); 1712 for (BasicBlock *SuccBB : successors(BB)) { 1713 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) { 1714 SeenFirstBranchToOnlyDest = true; // Don't modify the first branch. 1715 } else { 1716 SuccBB->removePredecessor(BB, true); // This is unreachable successor. 1717 Updates.push_back({DominatorTree::Delete, BB, SuccBB}); 1718 } 1719 } 1720 1721 // Finally update the terminator. 1722 Instruction *Term = BB->getTerminator(); 1723 BranchInst::Create(OnlyDest, Term); 1724 ++NumFolds; 1725 Term->eraseFromParent(); 1726 DTU->applyUpdatesPermissive(Updates); 1727 if (HasProfileData) 1728 BPI->eraseBlock(BB); 1729 1730 // If the condition is now dead due to the removal of the old terminator, 1731 // erase it. 1732 if (auto *CondInst = dyn_cast<Instruction>(Cond)) { 1733 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects()) 1734 CondInst->eraseFromParent(); 1735 // We can safely replace *some* uses of the CondInst if it has 1736 // exactly one value as returned by LVI. RAUW is incorrect in the 1737 // presence of guards and assumes, that have the `Cond` as the use. This 1738 // is because we use the guards/assume to reason about the `Cond` value 1739 // at the end of block, but RAUW unconditionally replaces all uses 1740 // including the guards/assumes themselves and the uses before the 1741 // guard/assume. 1742 else if (OnlyVal && OnlyVal != MultipleVal && 1743 CondInst->getParent() == BB) 1744 replaceFoldableUses(CondInst, OnlyVal); 1745 } 1746 return true; 1747 } 1748 } 1749 1750 // Determine which is the most common successor. If we have many inputs and 1751 // this block is a switch, we want to start by threading the batch that goes 1752 // to the most popular destination first. If we only know about one 1753 // threadable destination (the common case) we can avoid this. 1754 BasicBlock *MostPopularDest = OnlyDest; 1755 1756 if (MostPopularDest == MultipleDestSentinel) { 1757 // Remove any loop headers from the Dest list, threadEdge conservatively 1758 // won't process them, but we might have other destination that are eligible 1759 // and we still want to process. 1760 erase_if(PredToDestList, 1761 [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) { 1762 return LoopHeaders.contains(PredToDest.second); 1763 }); 1764 1765 if (PredToDestList.empty()) 1766 return false; 1767 1768 MostPopularDest = findMostPopularDest(BB, PredToDestList); 1769 } 1770 1771 // Now that we know what the most popular destination is, factor all 1772 // predecessors that will jump to it into a single predecessor. 1773 SmallVector<BasicBlock*, 16> PredsToFactor; 1774 for (const auto &PredToDest : PredToDestList) 1775 if (PredToDest.second == MostPopularDest) { 1776 BasicBlock *Pred = PredToDest.first; 1777 1778 // This predecessor may be a switch or something else that has multiple 1779 // edges to the block. Factor each of these edges by listing them 1780 // according to # occurrences in PredsToFactor. 1781 for (BasicBlock *Succ : successors(Pred)) 1782 if (Succ == BB) 1783 PredsToFactor.push_back(Pred); 1784 } 1785 1786 // If the threadable edges are branching on an undefined value, we get to pick 1787 // the destination that these predecessors should get to. 1788 if (!MostPopularDest) 1789 MostPopularDest = BB->getTerminator()-> 1790 getSuccessor(getBestDestForJumpOnUndef(BB)); 1791 1792 // Ok, try to thread it! 1793 return tryThreadEdge(BB, PredsToFactor, MostPopularDest); 1794 } 1795 1796 /// processBranchOnPHI - We have an otherwise unthreadable conditional branch on 1797 /// a PHI node (or freeze PHI) in the current block. See if there are any 1798 /// simplifications we can do based on inputs to the phi node. 1799 bool JumpThreadingPass::processBranchOnPHI(PHINode *PN) { 1800 BasicBlock *BB = PN->getParent(); 1801 1802 // TODO: We could make use of this to do it once for blocks with common PHI 1803 // values. 1804 SmallVector<BasicBlock*, 1> PredBBs; 1805 PredBBs.resize(1); 1806 1807 // If any of the predecessor blocks end in an unconditional branch, we can 1808 // *duplicate* the conditional branch into that block in order to further 1809 // encourage jump threading and to eliminate cases where we have branch on a 1810 // phi of an icmp (branch on icmp is much better). 1811 // This is still beneficial when a frozen phi is used as the branch condition 1812 // because it allows CodeGenPrepare to further canonicalize br(freeze(icmp)) 1813 // to br(icmp(freeze ...)). 1814 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1815 BasicBlock *PredBB = PN->getIncomingBlock(i); 1816 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator())) 1817 if (PredBr->isUnconditional()) { 1818 PredBBs[0] = PredBB; 1819 // Try to duplicate BB into PredBB. 1820 if (duplicateCondBranchOnPHIIntoPred(BB, PredBBs)) 1821 return true; 1822 } 1823 } 1824 1825 return false; 1826 } 1827 1828 /// processBranchOnXOR - We have an otherwise unthreadable conditional branch on 1829 /// a xor instruction in the current block. See if there are any 1830 /// simplifications we can do based on inputs to the xor. 1831 bool JumpThreadingPass::processBranchOnXOR(BinaryOperator *BO) { 1832 BasicBlock *BB = BO->getParent(); 1833 1834 // If either the LHS or RHS of the xor is a constant, don't do this 1835 // optimization. 1836 if (isa<ConstantInt>(BO->getOperand(0)) || 1837 isa<ConstantInt>(BO->getOperand(1))) 1838 return false; 1839 1840 // If the first instruction in BB isn't a phi, we won't be able to infer 1841 // anything special about any particular predecessor. 1842 if (!isa<PHINode>(BB->front())) 1843 return false; 1844 1845 // If this BB is a landing pad, we won't be able to split the edge into it. 1846 if (BB->isEHPad()) 1847 return false; 1848 1849 // If we have a xor as the branch input to this block, and we know that the 1850 // LHS or RHS of the xor in any predecessor is true/false, then we can clone 1851 // the condition into the predecessor and fix that value to true, saving some 1852 // logical ops on that path and encouraging other paths to simplify. 1853 // 1854 // This copies something like this: 1855 // 1856 // BB: 1857 // %X = phi i1 [1], [%X'] 1858 // %Y = icmp eq i32 %A, %B 1859 // %Z = xor i1 %X, %Y 1860 // br i1 %Z, ... 1861 // 1862 // Into: 1863 // BB': 1864 // %Y = icmp ne i32 %A, %B 1865 // br i1 %Y, ... 1866 1867 PredValueInfoTy XorOpValues; 1868 bool isLHS = true; 1869 if (!computeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues, 1870 WantInteger, BO)) { 1871 assert(XorOpValues.empty()); 1872 if (!computeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues, 1873 WantInteger, BO)) 1874 return false; 1875 isLHS = false; 1876 } 1877 1878 assert(!XorOpValues.empty() && 1879 "computeValueKnownInPredecessors returned true with no values"); 1880 1881 // Scan the information to see which is most popular: true or false. The 1882 // predecessors can be of the set true, false, or undef. 1883 unsigned NumTrue = 0, NumFalse = 0; 1884 for (const auto &XorOpValue : XorOpValues) { 1885 if (isa<UndefValue>(XorOpValue.first)) 1886 // Ignore undefs for the count. 1887 continue; 1888 if (cast<ConstantInt>(XorOpValue.first)->isZero()) 1889 ++NumFalse; 1890 else 1891 ++NumTrue; 1892 } 1893 1894 // Determine which value to split on, true, false, or undef if neither. 1895 ConstantInt *SplitVal = nullptr; 1896 if (NumTrue > NumFalse) 1897 SplitVal = ConstantInt::getTrue(BB->getContext()); 1898 else if (NumTrue != 0 || NumFalse != 0) 1899 SplitVal = ConstantInt::getFalse(BB->getContext()); 1900 1901 // Collect all of the blocks that this can be folded into so that we can 1902 // factor this once and clone it once. 1903 SmallVector<BasicBlock*, 8> BlocksToFoldInto; 1904 for (const auto &XorOpValue : XorOpValues) { 1905 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first)) 1906 continue; 1907 1908 BlocksToFoldInto.push_back(XorOpValue.second); 1909 } 1910 1911 // If we inferred a value for all of the predecessors, then duplication won't 1912 // help us. However, we can just replace the LHS or RHS with the constant. 1913 if (BlocksToFoldInto.size() == 1914 cast<PHINode>(BB->front()).getNumIncomingValues()) { 1915 if (!SplitVal) { 1916 // If all preds provide undef, just nuke the xor, because it is undef too. 1917 BO->replaceAllUsesWith(UndefValue::get(BO->getType())); 1918 BO->eraseFromParent(); 1919 } else if (SplitVal->isZero()) { 1920 // If all preds provide 0, replace the xor with the other input. 1921 BO->replaceAllUsesWith(BO->getOperand(isLHS)); 1922 BO->eraseFromParent(); 1923 } else { 1924 // If all preds provide 1, set the computed value to 1. 1925 BO->setOperand(!isLHS, SplitVal); 1926 } 1927 1928 return true; 1929 } 1930 1931 // If any of predecessors end with an indirect goto, we can't change its 1932 // destination. Same for CallBr. 1933 if (any_of(BlocksToFoldInto, [](BasicBlock *Pred) { 1934 return isa<IndirectBrInst>(Pred->getTerminator()) || 1935 isa<CallBrInst>(Pred->getTerminator()); 1936 })) 1937 return false; 1938 1939 // Try to duplicate BB into PredBB. 1940 return duplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto); 1941 } 1942 1943 /// addPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new 1944 /// predecessor to the PHIBB block. If it has PHI nodes, add entries for 1945 /// NewPred using the entries from OldPred (suitably mapped). 1946 static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, 1947 BasicBlock *OldPred, 1948 BasicBlock *NewPred, 1949 DenseMap<Instruction*, Value*> &ValueMap) { 1950 for (PHINode &PN : PHIBB->phis()) { 1951 // Ok, we have a PHI node. Figure out what the incoming value was for the 1952 // DestBlock. 1953 Value *IV = PN.getIncomingValueForBlock(OldPred); 1954 1955 // Remap the value if necessary. 1956 if (Instruction *Inst = dyn_cast<Instruction>(IV)) { 1957 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst); 1958 if (I != ValueMap.end()) 1959 IV = I->second; 1960 } 1961 1962 PN.addIncoming(IV, NewPred); 1963 } 1964 } 1965 1966 /// Merge basic block BB into its sole predecessor if possible. 1967 bool JumpThreadingPass::maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) { 1968 BasicBlock *SinglePred = BB->getSinglePredecessor(); 1969 if (!SinglePred) 1970 return false; 1971 1972 const Instruction *TI = SinglePred->getTerminator(); 1973 if (TI->isExceptionalTerminator() || TI->getNumSuccessors() != 1 || 1974 SinglePred == BB || hasAddressTakenAndUsed(BB)) 1975 return false; 1976 1977 // If SinglePred was a loop header, BB becomes one. 1978 if (LoopHeaders.erase(SinglePred)) 1979 LoopHeaders.insert(BB); 1980 1981 LVI->eraseBlock(SinglePred); 1982 MergeBasicBlockIntoOnlyPred(BB, DTU); 1983 1984 // Now that BB is merged into SinglePred (i.e. SinglePred code followed by 1985 // BB code within one basic block `BB`), we need to invalidate the LVI 1986 // information associated with BB, because the LVI information need not be 1987 // true for all of BB after the merge. For example, 1988 // Before the merge, LVI info and code is as follows: 1989 // SinglePred: <LVI info1 for %p val> 1990 // %y = use of %p 1991 // call @exit() // need not transfer execution to successor. 1992 // assume(%p) // from this point on %p is true 1993 // br label %BB 1994 // BB: <LVI info2 for %p val, i.e. %p is true> 1995 // %x = use of %p 1996 // br label exit 1997 // 1998 // Note that this LVI info for blocks BB and SinglPred is correct for %p 1999 // (info2 and info1 respectively). After the merge and the deletion of the 2000 // LVI info1 for SinglePred. We have the following code: 2001 // BB: <LVI info2 for %p val> 2002 // %y = use of %p 2003 // call @exit() 2004 // assume(%p) 2005 // %x = use of %p <-- LVI info2 is correct from here onwards. 2006 // br label exit 2007 // LVI info2 for BB is incorrect at the beginning of BB. 2008 2009 // Invalidate LVI information for BB if the LVI is not provably true for 2010 // all of BB. 2011 if (!isGuaranteedToTransferExecutionToSuccessor(BB)) 2012 LVI->eraseBlock(BB); 2013 return true; 2014 } 2015 2016 /// Update the SSA form. NewBB contains instructions that are copied from BB. 2017 /// ValueMapping maps old values in BB to new ones in NewBB. 2018 void JumpThreadingPass::updateSSA( 2019 BasicBlock *BB, BasicBlock *NewBB, 2020 DenseMap<Instruction *, Value *> &ValueMapping) { 2021 // If there were values defined in BB that are used outside the block, then we 2022 // now have to update all uses of the value to use either the original value, 2023 // the cloned value, or some PHI derived value. This can require arbitrary 2024 // PHI insertion, of which we are prepared to do, clean these up now. 2025 SSAUpdater SSAUpdate; 2026 SmallVector<Use *, 16> UsesToRename; 2027 2028 for (Instruction &I : *BB) { 2029 // Scan all uses of this instruction to see if it is used outside of its 2030 // block, and if so, record them in UsesToRename. 2031 for (Use &U : I.uses()) { 2032 Instruction *User = cast<Instruction>(U.getUser()); 2033 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 2034 if (UserPN->getIncomingBlock(U) == BB) 2035 continue; 2036 } else if (User->getParent() == BB) 2037 continue; 2038 2039 UsesToRename.push_back(&U); 2040 } 2041 2042 // If there are no uses outside the block, we're done with this instruction. 2043 if (UsesToRename.empty()) 2044 continue; 2045 LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n"); 2046 2047 // We found a use of I outside of BB. Rename all uses of I that are outside 2048 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 2049 // with the two values we know. 2050 SSAUpdate.Initialize(I.getType(), I.getName()); 2051 SSAUpdate.AddAvailableValue(BB, &I); 2052 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]); 2053 2054 while (!UsesToRename.empty()) 2055 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 2056 LLVM_DEBUG(dbgs() << "\n"); 2057 } 2058 } 2059 2060 /// Clone instructions in range [BI, BE) to NewBB. For PHI nodes, we only clone 2061 /// arguments that come from PredBB. Return the map from the variables in the 2062 /// source basic block to the variables in the newly created basic block. 2063 DenseMap<Instruction *, Value *> 2064 JumpThreadingPass::cloneInstructions(BasicBlock::iterator BI, 2065 BasicBlock::iterator BE, BasicBlock *NewBB, 2066 BasicBlock *PredBB) { 2067 // We are going to have to map operands from the source basic block to the new 2068 // copy of the block 'NewBB'. If there are PHI nodes in the source basic 2069 // block, evaluate them to account for entry from PredBB. 2070 DenseMap<Instruction *, Value *> ValueMapping; 2071 2072 // Clone the phi nodes of the source basic block into NewBB. The resulting 2073 // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater 2074 // might need to rewrite the operand of the cloned phi. 2075 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) { 2076 PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB); 2077 NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB); 2078 ValueMapping[PN] = NewPN; 2079 } 2080 2081 // Clone noalias scope declarations in the threaded block. When threading a 2082 // loop exit, we would otherwise end up with two idential scope declarations 2083 // visible at the same time. 2084 SmallVector<MDNode *> NoAliasScopes; 2085 DenseMap<MDNode *, MDNode *> ClonedScopes; 2086 LLVMContext &Context = PredBB->getContext(); 2087 identifyNoAliasScopesToClone(BI, BE, NoAliasScopes); 2088 cloneNoAliasScopes(NoAliasScopes, ClonedScopes, "thread", Context); 2089 2090 // Clone the non-phi instructions of the source basic block into NewBB, 2091 // keeping track of the mapping and using it to remap operands in the cloned 2092 // instructions. 2093 for (; BI != BE; ++BI) { 2094 Instruction *New = BI->clone(); 2095 New->setName(BI->getName()); 2096 NewBB->getInstList().push_back(New); 2097 ValueMapping[&*BI] = New; 2098 adaptNoAliasScopes(New, ClonedScopes, Context); 2099 2100 // Remap operands to patch up intra-block references. 2101 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 2102 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 2103 DenseMap<Instruction *, Value *>::iterator I = ValueMapping.find(Inst); 2104 if (I != ValueMapping.end()) 2105 New->setOperand(i, I->second); 2106 } 2107 } 2108 2109 return ValueMapping; 2110 } 2111 2112 /// Attempt to thread through two successive basic blocks. 2113 bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB, 2114 Value *Cond) { 2115 // Consider: 2116 // 2117 // PredBB: 2118 // %var = phi i32* [ null, %bb1 ], [ @a, %bb2 ] 2119 // %tobool = icmp eq i32 %cond, 0 2120 // br i1 %tobool, label %BB, label ... 2121 // 2122 // BB: 2123 // %cmp = icmp eq i32* %var, null 2124 // br i1 %cmp, label ..., label ... 2125 // 2126 // We don't know the value of %var at BB even if we know which incoming edge 2127 // we take to BB. However, once we duplicate PredBB for each of its incoming 2128 // edges (say, PredBB1 and PredBB2), we know the value of %var in each copy of 2129 // PredBB. Then we can thread edges PredBB1->BB and PredBB2->BB through BB. 2130 2131 // Require that BB end with a Branch for simplicity. 2132 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 2133 if (!CondBr) 2134 return false; 2135 2136 // BB must have exactly one predecessor. 2137 BasicBlock *PredBB = BB->getSinglePredecessor(); 2138 if (!PredBB) 2139 return false; 2140 2141 // Require that PredBB end with a conditional Branch. If PredBB ends with an 2142 // unconditional branch, we should be merging PredBB and BB instead. For 2143 // simplicity, we don't deal with a switch. 2144 BranchInst *PredBBBranch = dyn_cast<BranchInst>(PredBB->getTerminator()); 2145 if (!PredBBBranch || PredBBBranch->isUnconditional()) 2146 return false; 2147 2148 // If PredBB has exactly one incoming edge, we don't gain anything by copying 2149 // PredBB. 2150 if (PredBB->getSinglePredecessor()) 2151 return false; 2152 2153 // Don't thread through PredBB if it contains a successor edge to itself, in 2154 // which case we would infinite loop. Suppose we are threading an edge from 2155 // PredPredBB through PredBB and BB to SuccBB with PredBB containing a 2156 // successor edge to itself. If we allowed jump threading in this case, we 2157 // could duplicate PredBB and BB as, say, PredBB.thread and BB.thread. Since 2158 // PredBB.thread has a successor edge to PredBB, we would immediately come up 2159 // with another jump threading opportunity from PredBB.thread through PredBB 2160 // and BB to SuccBB. This jump threading would repeatedly occur. That is, we 2161 // would keep peeling one iteration from PredBB. 2162 if (llvm::is_contained(successors(PredBB), PredBB)) 2163 return false; 2164 2165 // Don't thread across a loop header. 2166 if (LoopHeaders.count(PredBB)) 2167 return false; 2168 2169 // Avoid complication with duplicating EH pads. 2170 if (PredBB->isEHPad()) 2171 return false; 2172 2173 // Find a predecessor that we can thread. For simplicity, we only consider a 2174 // successor edge out of BB to which we thread exactly one incoming edge into 2175 // PredBB. 2176 unsigned ZeroCount = 0; 2177 unsigned OneCount = 0; 2178 BasicBlock *ZeroPred = nullptr; 2179 BasicBlock *OnePred = nullptr; 2180 for (BasicBlock *P : predecessors(PredBB)) { 2181 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>( 2182 evaluateOnPredecessorEdge(BB, P, Cond))) { 2183 if (CI->isZero()) { 2184 ZeroCount++; 2185 ZeroPred = P; 2186 } else if (CI->isOne()) { 2187 OneCount++; 2188 OnePred = P; 2189 } 2190 } 2191 } 2192 2193 // Disregard complicated cases where we have to thread multiple edges. 2194 BasicBlock *PredPredBB; 2195 if (ZeroCount == 1) { 2196 PredPredBB = ZeroPred; 2197 } else if (OneCount == 1) { 2198 PredPredBB = OnePred; 2199 } else { 2200 return false; 2201 } 2202 2203 BasicBlock *SuccBB = CondBr->getSuccessor(PredPredBB == ZeroPred); 2204 2205 // If threading to the same block as we come from, we would infinite loop. 2206 if (SuccBB == BB) { 2207 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName() 2208 << "' - would thread to self!\n"); 2209 return false; 2210 } 2211 2212 // If threading this would thread across a loop header, don't thread the edge. 2213 // See the comments above findLoopHeaders for justifications and caveats. 2214 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) { 2215 LLVM_DEBUG({ 2216 bool BBIsHeader = LoopHeaders.count(BB); 2217 bool SuccIsHeader = LoopHeaders.count(SuccBB); 2218 dbgs() << " Not threading across " 2219 << (BBIsHeader ? "loop header BB '" : "block BB '") 2220 << BB->getName() << "' to dest " 2221 << (SuccIsHeader ? "loop header BB '" : "block BB '") 2222 << SuccBB->getName() 2223 << "' - it might create an irreducible loop!\n"; 2224 }); 2225 return false; 2226 } 2227 2228 // Compute the cost of duplicating BB and PredBB. 2229 unsigned BBCost = getJumpThreadDuplicationCost( 2230 TTI, BB, BB->getTerminator(), BBDupThreshold); 2231 unsigned PredBBCost = getJumpThreadDuplicationCost( 2232 TTI, PredBB, PredBB->getTerminator(), BBDupThreshold); 2233 2234 // Give up if costs are too high. We need to check BBCost and PredBBCost 2235 // individually before checking their sum because getJumpThreadDuplicationCost 2236 // return (unsigned)~0 for those basic blocks that cannot be duplicated. 2237 if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold || 2238 BBCost + PredBBCost > BBDupThreshold) { 2239 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName() 2240 << "' - Cost is too high: " << PredBBCost 2241 << " for PredBB, " << BBCost << "for BB\n"); 2242 return false; 2243 } 2244 2245 // Now we are ready to duplicate PredBB. 2246 threadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB); 2247 return true; 2248 } 2249 2250 void JumpThreadingPass::threadThroughTwoBasicBlocks(BasicBlock *PredPredBB, 2251 BasicBlock *PredBB, 2252 BasicBlock *BB, 2253 BasicBlock *SuccBB) { 2254 LLVM_DEBUG(dbgs() << " Threading through '" << PredBB->getName() << "' and '" 2255 << BB->getName() << "'\n"); 2256 2257 BranchInst *CondBr = cast<BranchInst>(BB->getTerminator()); 2258 BranchInst *PredBBBranch = cast<BranchInst>(PredBB->getTerminator()); 2259 2260 BasicBlock *NewBB = 2261 BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread", 2262 PredBB->getParent(), PredBB); 2263 NewBB->moveAfter(PredBB); 2264 2265 // Set the block frequency of NewBB. 2266 if (HasProfileData) { 2267 auto NewBBFreq = BFI->getBlockFreq(PredPredBB) * 2268 BPI->getEdgeProbability(PredPredBB, PredBB); 2269 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency()); 2270 } 2271 2272 // We are going to have to map operands from the original BB block to the new 2273 // copy of the block 'NewBB'. If there are PHI nodes in PredBB, evaluate them 2274 // to account for entry from PredPredBB. 2275 DenseMap<Instruction *, Value *> ValueMapping = 2276 cloneInstructions(PredBB->begin(), PredBB->end(), NewBB, PredPredBB); 2277 2278 // Copy the edge probabilities from PredBB to NewBB. 2279 if (HasProfileData) 2280 BPI->copyEdgeProbabilities(PredBB, NewBB); 2281 2282 // Update the terminator of PredPredBB to jump to NewBB instead of PredBB. 2283 // This eliminates predecessors from PredPredBB, which requires us to simplify 2284 // any PHI nodes in PredBB. 2285 Instruction *PredPredTerm = PredPredBB->getTerminator(); 2286 for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i) 2287 if (PredPredTerm->getSuccessor(i) == PredBB) { 2288 PredBB->removePredecessor(PredPredBB, true); 2289 PredPredTerm->setSuccessor(i, NewBB); 2290 } 2291 2292 addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB, 2293 ValueMapping); 2294 addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB, 2295 ValueMapping); 2296 2297 DTU->applyUpdatesPermissive( 2298 {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)}, 2299 {DominatorTree::Insert, NewBB, CondBr->getSuccessor(1)}, 2300 {DominatorTree::Insert, PredPredBB, NewBB}, 2301 {DominatorTree::Delete, PredPredBB, PredBB}}); 2302 2303 updateSSA(PredBB, NewBB, ValueMapping); 2304 2305 // Clean up things like PHI nodes with single operands, dead instructions, 2306 // etc. 2307 SimplifyInstructionsInBlock(NewBB, TLI); 2308 SimplifyInstructionsInBlock(PredBB, TLI); 2309 2310 SmallVector<BasicBlock *, 1> PredsToFactor; 2311 PredsToFactor.push_back(NewBB); 2312 threadEdge(BB, PredsToFactor, SuccBB); 2313 } 2314 2315 /// tryThreadEdge - Thread an edge if it's safe and profitable to do so. 2316 bool JumpThreadingPass::tryThreadEdge( 2317 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs, 2318 BasicBlock *SuccBB) { 2319 // If threading to the same block as we come from, we would infinite loop. 2320 if (SuccBB == BB) { 2321 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName() 2322 << "' - would thread to self!\n"); 2323 return false; 2324 } 2325 2326 // If threading this would thread across a loop header, don't thread the edge. 2327 // See the comments above findLoopHeaders for justifications and caveats. 2328 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) { 2329 LLVM_DEBUG({ 2330 bool BBIsHeader = LoopHeaders.count(BB); 2331 bool SuccIsHeader = LoopHeaders.count(SuccBB); 2332 dbgs() << " Not threading across " 2333 << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName() 2334 << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '") 2335 << SuccBB->getName() << "' - it might create an irreducible loop!\n"; 2336 }); 2337 return false; 2338 } 2339 2340 unsigned JumpThreadCost = getJumpThreadDuplicationCost( 2341 TTI, BB, BB->getTerminator(), BBDupThreshold); 2342 if (JumpThreadCost > BBDupThreshold) { 2343 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName() 2344 << "' - Cost is too high: " << JumpThreadCost << "\n"); 2345 return false; 2346 } 2347 2348 threadEdge(BB, PredBBs, SuccBB); 2349 return true; 2350 } 2351 2352 /// threadEdge - We have decided that it is safe and profitable to factor the 2353 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB 2354 /// across BB. Transform the IR to reflect this change. 2355 void JumpThreadingPass::threadEdge(BasicBlock *BB, 2356 const SmallVectorImpl<BasicBlock *> &PredBBs, 2357 BasicBlock *SuccBB) { 2358 assert(SuccBB != BB && "Don't create an infinite loop"); 2359 2360 assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) && 2361 "Don't thread across loop headers"); 2362 2363 // And finally, do it! Start by factoring the predecessors if needed. 2364 BasicBlock *PredBB; 2365 if (PredBBs.size() == 1) 2366 PredBB = PredBBs[0]; 2367 else { 2368 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size() 2369 << " common predecessors.\n"); 2370 PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm"); 2371 } 2372 2373 // And finally, do it! 2374 LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() 2375 << "' to '" << SuccBB->getName() 2376 << ", across block:\n " << *BB << "\n"); 2377 2378 LVI->threadEdge(PredBB, BB, SuccBB); 2379 2380 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), 2381 BB->getName()+".thread", 2382 BB->getParent(), BB); 2383 NewBB->moveAfter(PredBB); 2384 2385 // Set the block frequency of NewBB. 2386 if (HasProfileData) { 2387 auto NewBBFreq = 2388 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB); 2389 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency()); 2390 } 2391 2392 // Copy all the instructions from BB to NewBB except the terminator. 2393 DenseMap<Instruction *, Value *> ValueMapping = 2394 cloneInstructions(BB->begin(), std::prev(BB->end()), NewBB, PredBB); 2395 2396 // We didn't copy the terminator from BB over to NewBB, because there is now 2397 // an unconditional jump to SuccBB. Insert the unconditional jump. 2398 BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB); 2399 NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc()); 2400 2401 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the 2402 // PHI nodes for NewBB now. 2403 addPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping); 2404 2405 // Update the terminator of PredBB to jump to NewBB instead of BB. This 2406 // eliminates predecessors from BB, which requires us to simplify any PHI 2407 // nodes in BB. 2408 Instruction *PredTerm = PredBB->getTerminator(); 2409 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) 2410 if (PredTerm->getSuccessor(i) == BB) { 2411 BB->removePredecessor(PredBB, true); 2412 PredTerm->setSuccessor(i, NewBB); 2413 } 2414 2415 // Enqueue required DT updates. 2416 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB}, 2417 {DominatorTree::Insert, PredBB, NewBB}, 2418 {DominatorTree::Delete, PredBB, BB}}); 2419 2420 updateSSA(BB, NewBB, ValueMapping); 2421 2422 // At this point, the IR is fully up to date and consistent. Do a quick scan 2423 // over the new instructions and zap any that are constants or dead. This 2424 // frequently happens because of phi translation. 2425 SimplifyInstructionsInBlock(NewBB, TLI); 2426 2427 // Update the edge weight from BB to SuccBB, which should be less than before. 2428 updateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB); 2429 2430 // Threaded an edge! 2431 ++NumThreads; 2432 } 2433 2434 /// Create a new basic block that will be the predecessor of BB and successor of 2435 /// all blocks in Preds. When profile data is available, update the frequency of 2436 /// this new block. 2437 BasicBlock *JumpThreadingPass::splitBlockPreds(BasicBlock *BB, 2438 ArrayRef<BasicBlock *> Preds, 2439 const char *Suffix) { 2440 SmallVector<BasicBlock *, 2> NewBBs; 2441 2442 // Collect the frequencies of all predecessors of BB, which will be used to 2443 // update the edge weight of the result of splitting predecessors. 2444 DenseMap<BasicBlock *, BlockFrequency> FreqMap; 2445 if (HasProfileData) 2446 for (auto Pred : Preds) 2447 FreqMap.insert(std::make_pair( 2448 Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB))); 2449 2450 // In the case when BB is a LandingPad block we create 2 new predecessors 2451 // instead of just one. 2452 if (BB->isLandingPad()) { 2453 std::string NewName = std::string(Suffix) + ".split-lp"; 2454 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs); 2455 } else { 2456 NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix)); 2457 } 2458 2459 std::vector<DominatorTree::UpdateType> Updates; 2460 Updates.reserve((2 * Preds.size()) + NewBBs.size()); 2461 for (auto NewBB : NewBBs) { 2462 BlockFrequency NewBBFreq(0); 2463 Updates.push_back({DominatorTree::Insert, NewBB, BB}); 2464 for (auto Pred : predecessors(NewBB)) { 2465 Updates.push_back({DominatorTree::Delete, Pred, BB}); 2466 Updates.push_back({DominatorTree::Insert, Pred, NewBB}); 2467 if (HasProfileData) // Update frequencies between Pred -> NewBB. 2468 NewBBFreq += FreqMap.lookup(Pred); 2469 } 2470 if (HasProfileData) // Apply the summed frequency to NewBB. 2471 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency()); 2472 } 2473 2474 DTU->applyUpdatesPermissive(Updates); 2475 return NewBBs[0]; 2476 } 2477 2478 bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) { 2479 const Instruction *TI = BB->getTerminator(); 2480 assert(TI->getNumSuccessors() > 1 && "not a split"); 2481 2482 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof); 2483 if (!WeightsNode) 2484 return false; 2485 2486 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0)); 2487 if (MDName->getString() != "branch_weights") 2488 return false; 2489 2490 // Ensure there are weights for all of the successors. Note that the first 2491 // operand to the metadata node is a name, not a weight. 2492 return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1; 2493 } 2494 2495 /// Update the block frequency of BB and branch weight and the metadata on the 2496 /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 - 2497 /// Freq(PredBB->BB) / Freq(BB->SuccBB). 2498 void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB, 2499 BasicBlock *BB, 2500 BasicBlock *NewBB, 2501 BasicBlock *SuccBB) { 2502 if (!HasProfileData) 2503 return; 2504 2505 assert(BFI && BPI && "BFI & BPI should have been created here"); 2506 2507 // As the edge from PredBB to BB is deleted, we have to update the block 2508 // frequency of BB. 2509 auto BBOrigFreq = BFI->getBlockFreq(BB); 2510 auto NewBBFreq = BFI->getBlockFreq(NewBB); 2511 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB); 2512 auto BBNewFreq = BBOrigFreq - NewBBFreq; 2513 BFI->setBlockFreq(BB, BBNewFreq.getFrequency()); 2514 2515 // Collect updated outgoing edges' frequencies from BB and use them to update 2516 // edge probabilities. 2517 SmallVector<uint64_t, 4> BBSuccFreq; 2518 for (BasicBlock *Succ : successors(BB)) { 2519 auto SuccFreq = (Succ == SuccBB) 2520 ? BB2SuccBBFreq - NewBBFreq 2521 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ); 2522 BBSuccFreq.push_back(SuccFreq.getFrequency()); 2523 } 2524 2525 uint64_t MaxBBSuccFreq = 2526 *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end()); 2527 2528 SmallVector<BranchProbability, 4> BBSuccProbs; 2529 if (MaxBBSuccFreq == 0) 2530 BBSuccProbs.assign(BBSuccFreq.size(), 2531 {1, static_cast<unsigned>(BBSuccFreq.size())}); 2532 else { 2533 for (uint64_t Freq : BBSuccFreq) 2534 BBSuccProbs.push_back( 2535 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq)); 2536 // Normalize edge probabilities so that they sum up to one. 2537 BranchProbability::normalizeProbabilities(BBSuccProbs.begin(), 2538 BBSuccProbs.end()); 2539 } 2540 2541 // Update edge probabilities in BPI. 2542 BPI->setEdgeProbability(BB, BBSuccProbs); 2543 2544 // Update the profile metadata as well. 2545 // 2546 // Don't do this if the profile of the transformed blocks was statically 2547 // estimated. (This could occur despite the function having an entry 2548 // frequency in completely cold parts of the CFG.) 2549 // 2550 // In this case we don't want to suggest to subsequent passes that the 2551 // calculated weights are fully consistent. Consider this graph: 2552 // 2553 // check_1 2554 // 50% / | 2555 // eq_1 | 50% 2556 // \ | 2557 // check_2 2558 // 50% / | 2559 // eq_2 | 50% 2560 // \ | 2561 // check_3 2562 // 50% / | 2563 // eq_3 | 50% 2564 // \ | 2565 // 2566 // Assuming the blocks check_* all compare the same value against 1, 2 and 3, 2567 // the overall probabilities are inconsistent; the total probability that the 2568 // value is either 1, 2 or 3 is 150%. 2569 // 2570 // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3 2571 // becomes 0%. This is even worse if the edge whose probability becomes 0% is 2572 // the loop exit edge. Then based solely on static estimation we would assume 2573 // the loop was extremely hot. 2574 // 2575 // FIXME this locally as well so that BPI and BFI are consistent as well. We 2576 // shouldn't make edges extremely likely or unlikely based solely on static 2577 // estimation. 2578 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) { 2579 SmallVector<uint32_t, 4> Weights; 2580 for (auto Prob : BBSuccProbs) 2581 Weights.push_back(Prob.getNumerator()); 2582 2583 auto TI = BB->getTerminator(); 2584 TI->setMetadata( 2585 LLVMContext::MD_prof, 2586 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights)); 2587 } 2588 } 2589 2590 /// duplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch 2591 /// to BB which contains an i1 PHI node and a conditional branch on that PHI. 2592 /// If we can duplicate the contents of BB up into PredBB do so now, this 2593 /// improves the odds that the branch will be on an analyzable instruction like 2594 /// a compare. 2595 bool JumpThreadingPass::duplicateCondBranchOnPHIIntoPred( 2596 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) { 2597 assert(!PredBBs.empty() && "Can't handle an empty set"); 2598 2599 // If BB is a loop header, then duplicating this block outside the loop would 2600 // cause us to transform this into an irreducible loop, don't do this. 2601 // See the comments above findLoopHeaders for justifications and caveats. 2602 if (LoopHeaders.count(BB)) { 2603 LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName() 2604 << "' into predecessor block '" << PredBBs[0]->getName() 2605 << "' - it might create an irreducible loop!\n"); 2606 return false; 2607 } 2608 2609 unsigned DuplicationCost = getJumpThreadDuplicationCost( 2610 TTI, BB, BB->getTerminator(), BBDupThreshold); 2611 if (DuplicationCost > BBDupThreshold) { 2612 LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName() 2613 << "' - Cost is too high: " << DuplicationCost << "\n"); 2614 return false; 2615 } 2616 2617 // And finally, do it! Start by factoring the predecessors if needed. 2618 std::vector<DominatorTree::UpdateType> Updates; 2619 BasicBlock *PredBB; 2620 if (PredBBs.size() == 1) 2621 PredBB = PredBBs[0]; 2622 else { 2623 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size() 2624 << " common predecessors.\n"); 2625 PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm"); 2626 } 2627 Updates.push_back({DominatorTree::Delete, PredBB, BB}); 2628 2629 // Okay, we decided to do this! Clone all the instructions in BB onto the end 2630 // of PredBB. 2631 LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName() 2632 << "' into end of '" << PredBB->getName() 2633 << "' to eliminate branch on phi. Cost: " 2634 << DuplicationCost << " block is:" << *BB << "\n"); 2635 2636 // Unless PredBB ends with an unconditional branch, split the edge so that we 2637 // can just clone the bits from BB into the end of the new PredBB. 2638 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator()); 2639 2640 if (!OldPredBranch || !OldPredBranch->isUnconditional()) { 2641 BasicBlock *OldPredBB = PredBB; 2642 PredBB = SplitEdge(OldPredBB, BB); 2643 Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB}); 2644 Updates.push_back({DominatorTree::Insert, PredBB, BB}); 2645 Updates.push_back({DominatorTree::Delete, OldPredBB, BB}); 2646 OldPredBranch = cast<BranchInst>(PredBB->getTerminator()); 2647 } 2648 2649 // We are going to have to map operands from the original BB block into the 2650 // PredBB block. Evaluate PHI nodes in BB. 2651 DenseMap<Instruction*, Value*> ValueMapping; 2652 2653 BasicBlock::iterator BI = BB->begin(); 2654 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 2655 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 2656 // Clone the non-phi instructions of BB into PredBB, keeping track of the 2657 // mapping and using it to remap operands in the cloned instructions. 2658 for (; BI != BB->end(); ++BI) { 2659 Instruction *New = BI->clone(); 2660 2661 // Remap operands to patch up intra-block references. 2662 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 2663 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 2664 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 2665 if (I != ValueMapping.end()) 2666 New->setOperand(i, I->second); 2667 } 2668 2669 // If this instruction can be simplified after the operands are updated, 2670 // just use the simplified value instead. This frequently happens due to 2671 // phi translation. 2672 if (Value *IV = SimplifyInstruction( 2673 New, 2674 {BB->getModule()->getDataLayout(), TLI, nullptr, nullptr, New})) { 2675 ValueMapping[&*BI] = IV; 2676 if (!New->mayHaveSideEffects()) { 2677 New->deleteValue(); 2678 New = nullptr; 2679 } 2680 } else { 2681 ValueMapping[&*BI] = New; 2682 } 2683 if (New) { 2684 // Otherwise, insert the new instruction into the block. 2685 New->setName(BI->getName()); 2686 PredBB->getInstList().insert(OldPredBranch->getIterator(), New); 2687 // Update Dominance from simplified New instruction operands. 2688 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 2689 if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i))) 2690 Updates.push_back({DominatorTree::Insert, PredBB, SuccBB}); 2691 } 2692 } 2693 2694 // Check to see if the targets of the branch had PHI nodes. If so, we need to 2695 // add entries to the PHI nodes for branch from PredBB now. 2696 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator()); 2697 addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB, 2698 ValueMapping); 2699 addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB, 2700 ValueMapping); 2701 2702 updateSSA(BB, PredBB, ValueMapping); 2703 2704 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge 2705 // that we nuked. 2706 BB->removePredecessor(PredBB, true); 2707 2708 // Remove the unconditional branch at the end of the PredBB block. 2709 OldPredBranch->eraseFromParent(); 2710 if (HasProfileData) 2711 BPI->copyEdgeProbabilities(BB, PredBB); 2712 DTU->applyUpdatesPermissive(Updates); 2713 2714 ++NumDupes; 2715 return true; 2716 } 2717 2718 // Pred is a predecessor of BB with an unconditional branch to BB. SI is 2719 // a Select instruction in Pred. BB has other predecessors and SI is used in 2720 // a PHI node in BB. SI has no other use. 2721 // A new basic block, NewBB, is created and SI is converted to compare and 2722 // conditional branch. SI is erased from parent. 2723 void JumpThreadingPass::unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB, 2724 SelectInst *SI, PHINode *SIUse, 2725 unsigned Idx) { 2726 // Expand the select. 2727 // 2728 // Pred -- 2729 // | v 2730 // | NewBB 2731 // | | 2732 // |----- 2733 // v 2734 // BB 2735 BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator()); 2736 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold", 2737 BB->getParent(), BB); 2738 // Move the unconditional branch to NewBB. 2739 PredTerm->removeFromParent(); 2740 NewBB->getInstList().insert(NewBB->end(), PredTerm); 2741 // Create a conditional branch and update PHI nodes. 2742 auto *BI = BranchInst::Create(NewBB, BB, SI->getCondition(), Pred); 2743 BI->applyMergedLocation(PredTerm->getDebugLoc(), SI->getDebugLoc()); 2744 SIUse->setIncomingValue(Idx, SI->getFalseValue()); 2745 SIUse->addIncoming(SI->getTrueValue(), NewBB); 2746 2747 // The select is now dead. 2748 SI->eraseFromParent(); 2749 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB}, 2750 {DominatorTree::Insert, Pred, NewBB}}); 2751 2752 // Update any other PHI nodes in BB. 2753 for (BasicBlock::iterator BI = BB->begin(); 2754 PHINode *Phi = dyn_cast<PHINode>(BI); ++BI) 2755 if (Phi != SIUse) 2756 Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB); 2757 } 2758 2759 bool JumpThreadingPass::tryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) { 2760 PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition()); 2761 2762 if (!CondPHI || CondPHI->getParent() != BB) 2763 return false; 2764 2765 for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) { 2766 BasicBlock *Pred = CondPHI->getIncomingBlock(I); 2767 SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I)); 2768 2769 // The second and third condition can be potentially relaxed. Currently 2770 // the conditions help to simplify the code and allow us to reuse existing 2771 // code, developed for tryToUnfoldSelect(CmpInst *, BasicBlock *) 2772 if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse()) 2773 continue; 2774 2775 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator()); 2776 if (!PredTerm || !PredTerm->isUnconditional()) 2777 continue; 2778 2779 unfoldSelectInstr(Pred, BB, PredSI, CondPHI, I); 2780 return true; 2781 } 2782 return false; 2783 } 2784 2785 /// tryToUnfoldSelect - Look for blocks of the form 2786 /// bb1: 2787 /// %a = select 2788 /// br bb2 2789 /// 2790 /// bb2: 2791 /// %p = phi [%a, %bb1] ... 2792 /// %c = icmp %p 2793 /// br i1 %c 2794 /// 2795 /// And expand the select into a branch structure if one of its arms allows %c 2796 /// to be folded. This later enables threading from bb1 over bb2. 2797 bool JumpThreadingPass::tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) { 2798 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 2799 PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0)); 2800 Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1)); 2801 2802 if (!CondBr || !CondBr->isConditional() || !CondLHS || 2803 CondLHS->getParent() != BB) 2804 return false; 2805 2806 for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) { 2807 BasicBlock *Pred = CondLHS->getIncomingBlock(I); 2808 SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I)); 2809 2810 // Look if one of the incoming values is a select in the corresponding 2811 // predecessor. 2812 if (!SI || SI->getParent() != Pred || !SI->hasOneUse()) 2813 continue; 2814 2815 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator()); 2816 if (!PredTerm || !PredTerm->isUnconditional()) 2817 continue; 2818 2819 // Now check if one of the select values would allow us to constant fold the 2820 // terminator in BB. We don't do the transform if both sides fold, those 2821 // cases will be threaded in any case. 2822 LazyValueInfo::Tristate LHSFolds = 2823 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1), 2824 CondRHS, Pred, BB, CondCmp); 2825 LazyValueInfo::Tristate RHSFolds = 2826 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2), 2827 CondRHS, Pred, BB, CondCmp); 2828 if ((LHSFolds != LazyValueInfo::Unknown || 2829 RHSFolds != LazyValueInfo::Unknown) && 2830 LHSFolds != RHSFolds) { 2831 unfoldSelectInstr(Pred, BB, SI, CondLHS, I); 2832 return true; 2833 } 2834 } 2835 return false; 2836 } 2837 2838 /// tryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the 2839 /// same BB in the form 2840 /// bb: 2841 /// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ... 2842 /// %s = select %p, trueval, falseval 2843 /// 2844 /// or 2845 /// 2846 /// bb: 2847 /// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ... 2848 /// %c = cmp %p, 0 2849 /// %s = select %c, trueval, falseval 2850 /// 2851 /// And expand the select into a branch structure. This later enables 2852 /// jump-threading over bb in this pass. 2853 /// 2854 /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold 2855 /// select if the associated PHI has at least one constant. If the unfolded 2856 /// select is not jump-threaded, it will be folded again in the later 2857 /// optimizations. 2858 bool JumpThreadingPass::tryToUnfoldSelectInCurrBB(BasicBlock *BB) { 2859 // This transform would reduce the quality of msan diagnostics. 2860 // Disable this transform under MemorySanitizer. 2861 if (BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory)) 2862 return false; 2863 2864 // If threading this would thread across a loop header, don't thread the edge. 2865 // See the comments above findLoopHeaders for justifications and caveats. 2866 if (LoopHeaders.count(BB)) 2867 return false; 2868 2869 for (BasicBlock::iterator BI = BB->begin(); 2870 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) { 2871 // Look for a Phi having at least one constant incoming value. 2872 if (llvm::all_of(PN->incoming_values(), 2873 [](Value *V) { return !isa<ConstantInt>(V); })) 2874 continue; 2875 2876 auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) { 2877 using namespace PatternMatch; 2878 2879 // Check if SI is in BB and use V as condition. 2880 if (SI->getParent() != BB) 2881 return false; 2882 Value *Cond = SI->getCondition(); 2883 bool IsAndOr = match(SI, m_CombineOr(m_LogicalAnd(), m_LogicalOr())); 2884 return Cond && Cond == V && Cond->getType()->isIntegerTy(1) && !IsAndOr; 2885 }; 2886 2887 SelectInst *SI = nullptr; 2888 for (Use &U : PN->uses()) { 2889 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) { 2890 // Look for a ICmp in BB that compares PN with a constant and is the 2891 // condition of a Select. 2892 if (Cmp->getParent() == BB && Cmp->hasOneUse() && 2893 isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo()))) 2894 if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back())) 2895 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) { 2896 SI = SelectI; 2897 break; 2898 } 2899 } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) { 2900 // Look for a Select in BB that uses PN as condition. 2901 if (isUnfoldCandidate(SelectI, U.get())) { 2902 SI = SelectI; 2903 break; 2904 } 2905 } 2906 } 2907 2908 if (!SI) 2909 continue; 2910 // Expand the select. 2911 Value *Cond = SI->getCondition(); 2912 if (InsertFreezeWhenUnfoldingSelect && 2913 !isGuaranteedNotToBeUndefOrPoison(Cond, nullptr, SI, 2914 &DTU->getDomTree())) 2915 Cond = new FreezeInst(Cond, "cond.fr", SI); 2916 Instruction *Term = SplitBlockAndInsertIfThen(Cond, SI, false); 2917 BasicBlock *SplitBB = SI->getParent(); 2918 BasicBlock *NewBB = Term->getParent(); 2919 PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI); 2920 NewPN->addIncoming(SI->getTrueValue(), Term->getParent()); 2921 NewPN->addIncoming(SI->getFalseValue(), BB); 2922 SI->replaceAllUsesWith(NewPN); 2923 SI->eraseFromParent(); 2924 // NewBB and SplitBB are newly created blocks which require insertion. 2925 std::vector<DominatorTree::UpdateType> Updates; 2926 Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3); 2927 Updates.push_back({DominatorTree::Insert, BB, SplitBB}); 2928 Updates.push_back({DominatorTree::Insert, BB, NewBB}); 2929 Updates.push_back({DominatorTree::Insert, NewBB, SplitBB}); 2930 // BB's successors were moved to SplitBB, update DTU accordingly. 2931 for (auto *Succ : successors(SplitBB)) { 2932 Updates.push_back({DominatorTree::Delete, BB, Succ}); 2933 Updates.push_back({DominatorTree::Insert, SplitBB, Succ}); 2934 } 2935 DTU->applyUpdatesPermissive(Updates); 2936 return true; 2937 } 2938 return false; 2939 } 2940 2941 /// Try to propagate a guard from the current BB into one of its predecessors 2942 /// in case if another branch of execution implies that the condition of this 2943 /// guard is always true. Currently we only process the simplest case that 2944 /// looks like: 2945 /// 2946 /// Start: 2947 /// %cond = ... 2948 /// br i1 %cond, label %T1, label %F1 2949 /// T1: 2950 /// br label %Merge 2951 /// F1: 2952 /// br label %Merge 2953 /// Merge: 2954 /// %condGuard = ... 2955 /// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ] 2956 /// 2957 /// And cond either implies condGuard or !condGuard. In this case all the 2958 /// instructions before the guard can be duplicated in both branches, and the 2959 /// guard is then threaded to one of them. 2960 bool JumpThreadingPass::processGuards(BasicBlock *BB) { 2961 using namespace PatternMatch; 2962 2963 // We only want to deal with two predecessors. 2964 BasicBlock *Pred1, *Pred2; 2965 auto PI = pred_begin(BB), PE = pred_end(BB); 2966 if (PI == PE) 2967 return false; 2968 Pred1 = *PI++; 2969 if (PI == PE) 2970 return false; 2971 Pred2 = *PI++; 2972 if (PI != PE) 2973 return false; 2974 if (Pred1 == Pred2) 2975 return false; 2976 2977 // Try to thread one of the guards of the block. 2978 // TODO: Look up deeper than to immediate predecessor? 2979 auto *Parent = Pred1->getSinglePredecessor(); 2980 if (!Parent || Parent != Pred2->getSinglePredecessor()) 2981 return false; 2982 2983 if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator())) 2984 for (auto &I : *BB) 2985 if (isGuard(&I) && threadGuard(BB, cast<IntrinsicInst>(&I), BI)) 2986 return true; 2987 2988 return false; 2989 } 2990 2991 /// Try to propagate the guard from BB which is the lower block of a diamond 2992 /// to one of its branches, in case if diamond's condition implies guard's 2993 /// condition. 2994 bool JumpThreadingPass::threadGuard(BasicBlock *BB, IntrinsicInst *Guard, 2995 BranchInst *BI) { 2996 assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?"); 2997 assert(BI->isConditional() && "Unconditional branch has 2 successors?"); 2998 Value *GuardCond = Guard->getArgOperand(0); 2999 Value *BranchCond = BI->getCondition(); 3000 BasicBlock *TrueDest = BI->getSuccessor(0); 3001 BasicBlock *FalseDest = BI->getSuccessor(1); 3002 3003 auto &DL = BB->getModule()->getDataLayout(); 3004 bool TrueDestIsSafe = false; 3005 bool FalseDestIsSafe = false; 3006 3007 // True dest is safe if BranchCond => GuardCond. 3008 auto Impl = isImpliedCondition(BranchCond, GuardCond, DL); 3009 if (Impl && *Impl) 3010 TrueDestIsSafe = true; 3011 else { 3012 // False dest is safe if !BranchCond => GuardCond. 3013 Impl = isImpliedCondition(BranchCond, GuardCond, DL, /* LHSIsTrue */ false); 3014 if (Impl && *Impl) 3015 FalseDestIsSafe = true; 3016 } 3017 3018 if (!TrueDestIsSafe && !FalseDestIsSafe) 3019 return false; 3020 3021 BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest; 3022 BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest; 3023 3024 ValueToValueMapTy UnguardedMapping, GuardedMapping; 3025 Instruction *AfterGuard = Guard->getNextNode(); 3026 unsigned Cost = 3027 getJumpThreadDuplicationCost(TTI, BB, AfterGuard, BBDupThreshold); 3028 if (Cost > BBDupThreshold) 3029 return false; 3030 // Duplicate all instructions before the guard and the guard itself to the 3031 // branch where implication is not proved. 3032 BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween( 3033 BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU); 3034 assert(GuardedBlock && "Could not create the guarded block?"); 3035 // Duplicate all instructions before the guard in the unguarded branch. 3036 // Since we have successfully duplicated the guarded block and this block 3037 // has fewer instructions, we expect it to succeed. 3038 BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween( 3039 BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU); 3040 assert(UnguardedBlock && "Could not create the unguarded block?"); 3041 LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block " 3042 << GuardedBlock->getName() << "\n"); 3043 // Some instructions before the guard may still have uses. For them, we need 3044 // to create Phi nodes merging their copies in both guarded and unguarded 3045 // branches. Those instructions that have no uses can be just removed. 3046 SmallVector<Instruction *, 4> ToRemove; 3047 for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI) 3048 if (!isa<PHINode>(&*BI)) 3049 ToRemove.push_back(&*BI); 3050 3051 Instruction *InsertionPoint = &*BB->getFirstInsertionPt(); 3052 assert(InsertionPoint && "Empty block?"); 3053 // Substitute with Phis & remove. 3054 for (auto *Inst : reverse(ToRemove)) { 3055 if (!Inst->use_empty()) { 3056 PHINode *NewPN = PHINode::Create(Inst->getType(), 2); 3057 NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock); 3058 NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock); 3059 NewPN->insertBefore(InsertionPoint); 3060 Inst->replaceAllUsesWith(NewPN); 3061 } 3062 Inst->eraseFromParent(); 3063 } 3064 return true; 3065 } 3066