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