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