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