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/Transforms/Scalar.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/DenseSet.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/GlobalsModRef.h" 21 #include "llvm/Analysis/CFG.h" 22 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 23 #include "llvm/Analysis/ConstantFolding.h" 24 #include "llvm/Analysis/InstructionSimplify.h" 25 #include "llvm/Analysis/Loads.h" 26 #include "llvm/Analysis/LoopInfo.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/MDBuilder.h" 32 #include "llvm/IR/Metadata.h" 33 #include "llvm/Pass.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38 #include "llvm/Transforms/Utils/Local.h" 39 #include "llvm/Transforms/Utils/SSAUpdater.h" 40 #include <algorithm> 41 #include <memory> 42 using namespace llvm; 43 using namespace jumpthreading; 44 45 #define DEBUG_TYPE "jump-threading" 46 47 STATISTIC(NumThreads, "Number of jumps threaded"); 48 STATISTIC(NumFolds, "Number of terminators folded"); 49 STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi"); 50 51 static cl::opt<unsigned> 52 BBDuplicateThreshold("jump-threading-threshold", 53 cl::desc("Max block size to duplicate for jump threading"), 54 cl::init(6), cl::Hidden); 55 56 static cl::opt<unsigned> 57 ImplicationSearchThreshold( 58 "jump-threading-implication-search-threshold", 59 cl::desc("The number of predecessors to search for a stronger " 60 "condition to use to thread over a weaker condition"), 61 cl::init(3), cl::Hidden); 62 63 namespace { 64 /// This pass performs 'jump threading', which looks at blocks that have 65 /// multiple predecessors and multiple successors. If one or more of the 66 /// predecessors of the block can be proven to always jump to one of the 67 /// successors, we forward the edge from the predecessor to the successor by 68 /// duplicating the contents of this block. 69 /// 70 /// An example of when this can occur is code like this: 71 /// 72 /// if () { ... 73 /// X = 4; 74 /// } 75 /// if (X < 3) { 76 /// 77 /// In this case, the unconditional branch at the end of the first if can be 78 /// revectored to the false side of the second if. 79 /// 80 class JumpThreading : public FunctionPass { 81 JumpThreadingPass Impl; 82 83 public: 84 static char ID; // Pass identification 85 JumpThreading(int T = -1) : FunctionPass(ID), Impl(T) { 86 initializeJumpThreadingPass(*PassRegistry::getPassRegistry()); 87 } 88 89 bool runOnFunction(Function &F) override; 90 91 void getAnalysisUsage(AnalysisUsage &AU) const override { 92 AU.addRequired<LazyValueInfoWrapperPass>(); 93 AU.addPreserved<LazyValueInfoWrapperPass>(); 94 AU.addPreserved<GlobalsAAWrapperPass>(); 95 AU.addRequired<TargetLibraryInfoWrapperPass>(); 96 } 97 98 void releaseMemory() override { Impl.releaseMemory(); } 99 }; 100 } 101 102 char JumpThreading::ID = 0; 103 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading", 104 "Jump Threading", false, false) 105 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 106 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 107 INITIALIZE_PASS_END(JumpThreading, "jump-threading", 108 "Jump Threading", false, false) 109 110 // Public interface to the Jump Threading pass 111 FunctionPass *llvm::createJumpThreadingPass(int Threshold) { return new JumpThreading(Threshold); } 112 113 JumpThreadingPass::JumpThreadingPass(int T) { 114 BBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T); 115 } 116 117 /// runOnFunction - Top level algorithm. 118 /// 119 bool JumpThreading::runOnFunction(Function &F) { 120 if (skipFunction(F)) 121 return false; 122 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 123 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI(); 124 std::unique_ptr<BlockFrequencyInfo> BFI; 125 std::unique_ptr<BranchProbabilityInfo> BPI; 126 bool HasProfileData = F.getEntryCount().hasValue(); 127 if (HasProfileData) { 128 LoopInfo LI{DominatorTree(F)}; 129 BPI.reset(new BranchProbabilityInfo(F, LI)); 130 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); 131 } 132 return Impl.runImpl(F, TLI, LVI, HasProfileData, std::move(BFI), 133 std::move(BPI)); 134 } 135 136 PreservedAnalyses JumpThreadingPass::run(Function &F, 137 FunctionAnalysisManager &AM) { 138 139 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 140 auto &LVI = AM.getResult<LazyValueAnalysis>(F); 141 std::unique_ptr<BlockFrequencyInfo> BFI; 142 std::unique_ptr<BranchProbabilityInfo> BPI; 143 bool HasProfileData = F.getEntryCount().hasValue(); 144 if (HasProfileData) { 145 LoopInfo LI{DominatorTree(F)}; 146 BPI.reset(new BranchProbabilityInfo(F, LI)); 147 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); 148 } 149 bool Changed = 150 runImpl(F, &TLI, &LVI, HasProfileData, std::move(BFI), std::move(BPI)); 151 152 if (!Changed) 153 return PreservedAnalyses::all(); 154 PreservedAnalyses PA; 155 PA.preserve<GlobalsAA>(); 156 return PA; 157 } 158 159 bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_, 160 LazyValueInfo *LVI_, bool HasProfileData_, 161 std::unique_ptr<BlockFrequencyInfo> BFI_, 162 std::unique_ptr<BranchProbabilityInfo> BPI_) { 163 164 DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n"); 165 TLI = TLI_; 166 LVI = LVI_; 167 BFI.reset(); 168 BPI.reset(); 169 // When profile data is available, we need to update edge weights after 170 // successful jump threading, which requires both BPI and BFI being available. 171 HasProfileData = HasProfileData_; 172 if (HasProfileData) { 173 BPI = std::move(BPI_); 174 BFI = std::move(BFI_); 175 } 176 177 // Remove unreachable blocks from function as they may result in infinite 178 // loop. We do threading if we found something profitable. Jump threading a 179 // branch can create other opportunities. If these opportunities form a cycle 180 // i.e. if any jump threading is undoing previous threading in the path, then 181 // we will loop forever. We take care of this issue by not jump threading for 182 // back edges. This works for normal cases but not for unreachable blocks as 183 // they may have cycle with no back edge. 184 bool EverChanged = false; 185 EverChanged |= removeUnreachableBlocks(F, LVI); 186 187 FindLoopHeaders(F); 188 189 bool Changed; 190 do { 191 Changed = false; 192 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 193 BasicBlock *BB = &*I; 194 // Thread all of the branches we can over this block. 195 while (ProcessBlock(BB)) 196 Changed = true; 197 198 ++I; 199 200 // If the block is trivially dead, zap it. This eliminates the successor 201 // edges which simplifies the CFG. 202 if (pred_empty(BB) && 203 BB != &BB->getParent()->getEntryBlock()) { 204 DEBUG(dbgs() << " JT: Deleting dead block '" << BB->getName() 205 << "' with terminator: " << *BB->getTerminator() << '\n'); 206 LoopHeaders.erase(BB); 207 LVI->eraseBlock(BB); 208 DeleteDeadBlock(BB); 209 Changed = true; 210 continue; 211 } 212 213 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); 214 215 // Can't thread an unconditional jump, but if the block is "almost 216 // empty", we can replace uses of it with uses of the successor and make 217 // this dead. 218 // We should not eliminate the loop header either, because eliminating 219 // a loop header might later prevent LoopSimplify from transforming nested 220 // loops into simplified form. 221 if (BI && BI->isUnconditional() && 222 BB != &BB->getParent()->getEntryBlock() && 223 // If the terminator is the only non-phi instruction, try to nuke it. 224 BB->getFirstNonPHIOrDbg()->isTerminator() && !LoopHeaders.count(BB)) { 225 // FIXME: It is always conservatively correct to drop the info 226 // for a block even if it doesn't get erased. This isn't totally 227 // awesome, but it allows us to use AssertingVH to prevent nasty 228 // dangling pointer issues within LazyValueInfo. 229 LVI->eraseBlock(BB); 230 if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) 231 Changed = true; 232 } 233 } 234 EverChanged |= Changed; 235 } while (Changed); 236 237 LoopHeaders.clear(); 238 return EverChanged; 239 } 240 241 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to 242 /// thread across it. Stop scanning the block when passing the threshold. 243 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB, 244 unsigned Threshold) { 245 /// Ignore PHI nodes, these will be flattened when duplication happens. 246 BasicBlock::const_iterator I(BB->getFirstNonPHI()); 247 248 // FIXME: THREADING will delete values that are just used to compute the 249 // branch, so they shouldn't count against the duplication cost. 250 251 unsigned Bonus = 0; 252 const TerminatorInst *BBTerm = BB->getTerminator(); 253 // Threading through a switch statement is particularly profitable. If this 254 // block ends in a switch, decrease its cost to make it more likely to happen. 255 if (isa<SwitchInst>(BBTerm)) 256 Bonus = 6; 257 258 // The same holds for indirect branches, but slightly more so. 259 if (isa<IndirectBrInst>(BBTerm)) 260 Bonus = 8; 261 262 // Bump the threshold up so the early exit from the loop doesn't skip the 263 // terminator-based Size adjustment at the end. 264 Threshold += Bonus; 265 266 // Sum up the cost of each instruction until we get to the terminator. Don't 267 // include the terminator because the copy won't include it. 268 unsigned Size = 0; 269 for (; !isa<TerminatorInst>(I); ++I) { 270 271 // Stop scanning the block if we've reached the threshold. 272 if (Size > Threshold) 273 return Size; 274 275 // Debugger intrinsics don't incur code size. 276 if (isa<DbgInfoIntrinsic>(I)) continue; 277 278 // If this is a pointer->pointer bitcast, it is free. 279 if (isa<BitCastInst>(I) && I->getType()->isPointerTy()) 280 continue; 281 282 // Bail out if this instruction gives back a token type, it is not possible 283 // to duplicate it if it is used outside this BB. 284 if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB)) 285 return ~0U; 286 287 // All other instructions count for at least one unit. 288 ++Size; 289 290 // Calls are more expensive. If they are non-intrinsic calls, we model them 291 // as having cost of 4. If they are a non-vector intrinsic, we model them 292 // as having cost of 2 total, and if they are a vector intrinsic, we model 293 // them as having cost 1. 294 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 295 if (CI->cannotDuplicate() || CI->isConvergent()) 296 // Blocks with NoDuplicate are modelled as having infinite cost, so they 297 // are never duplicated. 298 return ~0U; 299 else if (!isa<IntrinsicInst>(CI)) 300 Size += 3; 301 else if (!CI->getType()->isVectorTy()) 302 Size += 1; 303 } 304 } 305 306 return Size > Bonus ? Size - Bonus : 0; 307 } 308 309 /// FindLoopHeaders - We do not want jump threading to turn proper loop 310 /// structures into irreducible loops. Doing this breaks up the loop nesting 311 /// hierarchy and pessimizes later transformations. To prevent this from 312 /// happening, we first have to find the loop headers. Here we approximate this 313 /// by finding targets of backedges in the CFG. 314 /// 315 /// Note that there definitely are cases when we want to allow threading of 316 /// edges across a loop header. For example, threading a jump from outside the 317 /// loop (the preheader) to an exit block of the loop is definitely profitable. 318 /// It is also almost always profitable to thread backedges from within the loop 319 /// to exit blocks, and is often profitable to thread backedges to other blocks 320 /// within the loop (forming a nested loop). This simple analysis is not rich 321 /// enough to track all of these properties and keep it up-to-date as the CFG 322 /// mutates, so we don't allow any of these transformations. 323 /// 324 void JumpThreadingPass::FindLoopHeaders(Function &F) { 325 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges; 326 FindFunctionBackedges(F, Edges); 327 328 for (const auto &Edge : Edges) 329 LoopHeaders.insert(Edge.second); 330 } 331 332 /// getKnownConstant - Helper method to determine if we can thread over a 333 /// terminator with the given value as its condition, and if so what value to 334 /// use for that. What kind of value this is depends on whether we want an 335 /// integer or a block address, but an undef is always accepted. 336 /// Returns null if Val is null or not an appropriate constant. 337 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) { 338 if (!Val) 339 return nullptr; 340 341 // Undef is "known" enough. 342 if (UndefValue *U = dyn_cast<UndefValue>(Val)) 343 return U; 344 345 if (Preference == WantBlockAddress) 346 return dyn_cast<BlockAddress>(Val->stripPointerCasts()); 347 348 return dyn_cast<ConstantInt>(Val); 349 } 350 351 /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see 352 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef 353 /// in any of our predecessors. If so, return the known list of value and pred 354 /// BB in the result vector. 355 /// 356 /// This returns true if there were any known values. 357 /// 358 bool JumpThreadingPass::ComputeValueKnownInPredecessors( 359 Value *V, BasicBlock *BB, PredValueInfo &Result, 360 ConstantPreference Preference, Instruction *CxtI) { 361 // This method walks up use-def chains recursively. Because of this, we could 362 // get into an infinite loop going around loops in the use-def chain. To 363 // prevent this, keep track of what (value, block) pairs we've already visited 364 // and terminate the search if we loop back to them 365 if (!RecursionSet.insert(std::make_pair(V, BB)).second) 366 return false; 367 368 // An RAII help to remove this pair from the recursion set once the recursion 369 // stack pops back out again. 370 RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB)); 371 372 // If V is a constant, then it is known in all predecessors. 373 if (Constant *KC = getKnownConstant(V, Preference)) { 374 for (BasicBlock *Pred : predecessors(BB)) 375 Result.push_back(std::make_pair(KC, Pred)); 376 377 return !Result.empty(); 378 } 379 380 // If V is a non-instruction value, or an instruction in a different block, 381 // then it can't be derived from a PHI. 382 Instruction *I = dyn_cast<Instruction>(V); 383 if (!I || I->getParent() != BB) { 384 385 // Okay, if this is a live-in value, see if it has a known value at the end 386 // of any of our predecessors. 387 // 388 // FIXME: This should be an edge property, not a block end property. 389 /// TODO: Per PR2563, we could infer value range information about a 390 /// predecessor based on its terminator. 391 // 392 // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if 393 // "I" is a non-local compare-with-a-constant instruction. This would be 394 // able to handle value inequalities better, for example if the compare is 395 // "X < 4" and "X < 3" is known true but "X < 4" itself is not available. 396 // Perhaps getConstantOnEdge should be smart enough to do this? 397 398 for (BasicBlock *P : predecessors(BB)) { 399 // If the value is known by LazyValueInfo to be a constant in a 400 // predecessor, use that information to try to thread this block. 401 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI); 402 if (Constant *KC = getKnownConstant(PredCst, Preference)) 403 Result.push_back(std::make_pair(KC, P)); 404 } 405 406 return !Result.empty(); 407 } 408 409 /// If I is a PHI node, then we know the incoming values for any constants. 410 if (PHINode *PN = dyn_cast<PHINode>(I)) { 411 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 412 Value *InVal = PN->getIncomingValue(i); 413 if (Constant *KC = getKnownConstant(InVal, Preference)) { 414 Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i))); 415 } else { 416 Constant *CI = LVI->getConstantOnEdge(InVal, 417 PN->getIncomingBlock(i), 418 BB, CxtI); 419 if (Constant *KC = getKnownConstant(CI, Preference)) 420 Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i))); 421 } 422 } 423 424 return !Result.empty(); 425 } 426 427 // Handle Cast instructions. Only see through Cast when the source operand is 428 // PHI or Cmp and the source type is i1 to save the compilation time. 429 if (CastInst *CI = dyn_cast<CastInst>(I)) { 430 Value *Source = CI->getOperand(0); 431 if (!Source->getType()->isIntegerTy(1)) 432 return false; 433 if (!isa<PHINode>(Source) && !isa<CmpInst>(Source)) 434 return false; 435 ComputeValueKnownInPredecessors(Source, BB, Result, Preference, CxtI); 436 if (Result.empty()) 437 return false; 438 439 // Convert the known values. 440 for (auto &R : Result) 441 R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType()); 442 443 return true; 444 } 445 446 PredValueInfoTy LHSVals, RHSVals; 447 448 // Handle some boolean conditions. 449 if (I->getType()->getPrimitiveSizeInBits() == 1) { 450 assert(Preference == WantInteger && "One-bit non-integer type?"); 451 // X | true -> true 452 // X & false -> false 453 if (I->getOpcode() == Instruction::Or || 454 I->getOpcode() == Instruction::And) { 455 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals, 456 WantInteger, CxtI); 457 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals, 458 WantInteger, CxtI); 459 460 if (LHSVals.empty() && RHSVals.empty()) 461 return false; 462 463 ConstantInt *InterestingVal; 464 if (I->getOpcode() == Instruction::Or) 465 InterestingVal = ConstantInt::getTrue(I->getContext()); 466 else 467 InterestingVal = ConstantInt::getFalse(I->getContext()); 468 469 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs; 470 471 // Scan for the sentinel. If we find an undef, force it to the 472 // interesting value: x|undef -> true and x&undef -> false. 473 for (const auto &LHSVal : LHSVals) 474 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) { 475 Result.emplace_back(InterestingVal, LHSVal.second); 476 LHSKnownBBs.insert(LHSVal.second); 477 } 478 for (const auto &RHSVal : RHSVals) 479 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) { 480 // If we already inferred a value for this block on the LHS, don't 481 // re-add it. 482 if (!LHSKnownBBs.count(RHSVal.second)) 483 Result.emplace_back(InterestingVal, RHSVal.second); 484 } 485 486 return !Result.empty(); 487 } 488 489 // Handle the NOT form of XOR. 490 if (I->getOpcode() == Instruction::Xor && 491 isa<ConstantInt>(I->getOperand(1)) && 492 cast<ConstantInt>(I->getOperand(1))->isOne()) { 493 ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result, 494 WantInteger, CxtI); 495 if (Result.empty()) 496 return false; 497 498 // Invert the known values. 499 for (auto &R : Result) 500 R.first = ConstantExpr::getNot(R.first); 501 502 return true; 503 } 504 505 // Try to simplify some other binary operator values. 506 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 507 assert(Preference != WantBlockAddress 508 && "A binary operator creating a block address?"); 509 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) { 510 PredValueInfoTy LHSVals; 511 ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals, 512 WantInteger, CxtI); 513 514 // Try to use constant folding to simplify the binary operator. 515 for (const auto &LHSVal : LHSVals) { 516 Constant *V = LHSVal.first; 517 Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI); 518 519 if (Constant *KC = getKnownConstant(Folded, WantInteger)) 520 Result.push_back(std::make_pair(KC, LHSVal.second)); 521 } 522 } 523 524 return !Result.empty(); 525 } 526 527 // Handle compare with phi operand, where the PHI is defined in this block. 528 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 529 assert(Preference == WantInteger && "Compares only produce integers"); 530 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0)); 531 if (PN && PN->getParent() == BB) { 532 const DataLayout &DL = PN->getModule()->getDataLayout(); 533 // We can do this simplification if any comparisons fold to true or false. 534 // See if any do. 535 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 536 BasicBlock *PredBB = PN->getIncomingBlock(i); 537 Value *LHS = PN->getIncomingValue(i); 538 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB); 539 540 Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, DL); 541 if (!Res) { 542 if (!isa<Constant>(RHS)) 543 continue; 544 545 LazyValueInfo::Tristate 546 ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS, 547 cast<Constant>(RHS), PredBB, BB, 548 CxtI ? CxtI : Cmp); 549 if (ResT == LazyValueInfo::Unknown) 550 continue; 551 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT); 552 } 553 554 if (Constant *KC = getKnownConstant(Res, WantInteger)) 555 Result.push_back(std::make_pair(KC, PredBB)); 556 } 557 558 return !Result.empty(); 559 } 560 561 // If comparing a live-in value against a constant, see if we know the 562 // live-in value on any predecessors. 563 if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) { 564 if (!isa<Instruction>(Cmp->getOperand(0)) || 565 cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) { 566 Constant *RHSCst = cast<Constant>(Cmp->getOperand(1)); 567 568 for (BasicBlock *P : predecessors(BB)) { 569 // If the value is known by LazyValueInfo to be a constant in a 570 // predecessor, use that information to try to thread this block. 571 LazyValueInfo::Tristate Res = 572 LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0), 573 RHSCst, P, BB, CxtI ? CxtI : Cmp); 574 if (Res == LazyValueInfo::Unknown) 575 continue; 576 577 Constant *ResC = ConstantInt::get(Cmp->getType(), Res); 578 Result.push_back(std::make_pair(ResC, P)); 579 } 580 581 return !Result.empty(); 582 } 583 584 // Try to find a constant value for the LHS of a comparison, 585 // and evaluate it statically if we can. 586 if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) { 587 PredValueInfoTy LHSVals; 588 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals, 589 WantInteger, CxtI); 590 591 for (const auto &LHSVal : LHSVals) { 592 Constant *V = LHSVal.first; 593 Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(), 594 V, CmpConst); 595 if (Constant *KC = getKnownConstant(Folded, WantInteger)) 596 Result.push_back(std::make_pair(KC, LHSVal.second)); 597 } 598 599 return !Result.empty(); 600 } 601 } 602 } 603 604 if (SelectInst *SI = dyn_cast<SelectInst>(I)) { 605 // Handle select instructions where at least one operand is a known constant 606 // and we can figure out the condition value for any predecessor block. 607 Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference); 608 Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference); 609 PredValueInfoTy Conds; 610 if ((TrueVal || FalseVal) && 611 ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds, 612 WantInteger, CxtI)) { 613 for (auto &C : Conds) { 614 Constant *Cond = C.first; 615 616 // Figure out what value to use for the condition. 617 bool KnownCond; 618 if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) { 619 // A known boolean. 620 KnownCond = CI->isOne(); 621 } else { 622 assert(isa<UndefValue>(Cond) && "Unexpected condition value"); 623 // Either operand will do, so be sure to pick the one that's a known 624 // constant. 625 // FIXME: Do this more cleverly if both values are known constants? 626 KnownCond = (TrueVal != nullptr); 627 } 628 629 // See if the select has a known constant value for this predecessor. 630 if (Constant *Val = KnownCond ? TrueVal : FalseVal) 631 Result.push_back(std::make_pair(Val, C.second)); 632 } 633 634 return !Result.empty(); 635 } 636 } 637 638 // If all else fails, see if LVI can figure out a constant value for us. 639 Constant *CI = LVI->getConstant(V, BB, CxtI); 640 if (Constant *KC = getKnownConstant(CI, Preference)) { 641 for (BasicBlock *Pred : predecessors(BB)) 642 Result.push_back(std::make_pair(KC, Pred)); 643 } 644 645 return !Result.empty(); 646 } 647 648 649 650 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends 651 /// in an undefined jump, decide which block is best to revector to. 652 /// 653 /// Since we can pick an arbitrary destination, we pick the successor with the 654 /// fewest predecessors. This should reduce the in-degree of the others. 655 /// 656 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) { 657 TerminatorInst *BBTerm = BB->getTerminator(); 658 unsigned MinSucc = 0; 659 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc); 660 // Compute the successor with the minimum number of predecessors. 661 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); 662 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) { 663 TestBB = BBTerm->getSuccessor(i); 664 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); 665 if (NumPreds < MinNumPreds) { 666 MinSucc = i; 667 MinNumPreds = NumPreds; 668 } 669 } 670 671 return MinSucc; 672 } 673 674 static bool hasAddressTakenAndUsed(BasicBlock *BB) { 675 if (!BB->hasAddressTaken()) return false; 676 677 // If the block has its address taken, it may be a tree of dead constants 678 // hanging off of it. These shouldn't keep the block alive. 679 BlockAddress *BA = BlockAddress::get(BB); 680 BA->removeDeadConstantUsers(); 681 return !BA->use_empty(); 682 } 683 684 /// ProcessBlock - If there are any predecessors whose control can be threaded 685 /// through to a successor, transform them now. 686 bool JumpThreadingPass::ProcessBlock(BasicBlock *BB) { 687 // If the block is trivially dead, just return and let the caller nuke it. 688 // This simplifies other transformations. 689 if (pred_empty(BB) && 690 BB != &BB->getParent()->getEntryBlock()) 691 return false; 692 693 // If this block has a single predecessor, and if that pred has a single 694 // successor, merge the blocks. This encourages recursive jump threading 695 // because now the condition in this block can be threaded through 696 // predecessors of our predecessor block. 697 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) { 698 const TerminatorInst *TI = SinglePred->getTerminator(); 699 if (!TI->isExceptional() && TI->getNumSuccessors() == 1 && 700 SinglePred != BB && !hasAddressTakenAndUsed(BB)) { 701 // If SinglePred was a loop header, BB becomes one. 702 if (LoopHeaders.erase(SinglePred)) 703 LoopHeaders.insert(BB); 704 705 LVI->eraseBlock(SinglePred); 706 MergeBasicBlockIntoOnlyPred(BB); 707 708 return true; 709 } 710 } 711 712 if (TryToUnfoldSelectInCurrBB(BB)) 713 return true; 714 715 // What kind of constant we're looking for. 716 ConstantPreference Preference = WantInteger; 717 718 // Look to see if the terminator is a conditional branch, switch or indirect 719 // branch, if not we can't thread it. 720 Value *Condition; 721 Instruction *Terminator = BB->getTerminator(); 722 if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) { 723 // Can't thread an unconditional jump. 724 if (BI->isUnconditional()) return false; 725 Condition = BI->getCondition(); 726 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) { 727 Condition = SI->getCondition(); 728 } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) { 729 // Can't thread indirect branch with no successors. 730 if (IB->getNumSuccessors() == 0) return false; 731 Condition = IB->getAddress()->stripPointerCasts(); 732 Preference = WantBlockAddress; 733 } else { 734 return false; // Must be an invoke. 735 } 736 737 // Run constant folding to see if we can reduce the condition to a simple 738 // constant. 739 if (Instruction *I = dyn_cast<Instruction>(Condition)) { 740 Value *SimpleVal = 741 ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI); 742 if (SimpleVal) { 743 I->replaceAllUsesWith(SimpleVal); 744 if (isInstructionTriviallyDead(I, TLI)) 745 I->eraseFromParent(); 746 Condition = SimpleVal; 747 } 748 } 749 750 // If the terminator is branching on an undef, we can pick any of the 751 // successors to branch to. Let GetBestDestForJumpOnUndef decide. 752 if (isa<UndefValue>(Condition)) { 753 unsigned BestSucc = GetBestDestForJumpOnUndef(BB); 754 755 // Fold the branch/switch. 756 TerminatorInst *BBTerm = BB->getTerminator(); 757 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) { 758 if (i == BestSucc) continue; 759 BBTerm->getSuccessor(i)->removePredecessor(BB, true); 760 } 761 762 DEBUG(dbgs() << " In block '" << BB->getName() 763 << "' folding undef terminator: " << *BBTerm << '\n'); 764 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm); 765 BBTerm->eraseFromParent(); 766 return true; 767 } 768 769 // If the terminator of this block is branching on a constant, simplify the 770 // terminator to an unconditional branch. This can occur due to threading in 771 // other blocks. 772 if (getKnownConstant(Condition, Preference)) { 773 DEBUG(dbgs() << " In block '" << BB->getName() 774 << "' folding terminator: " << *BB->getTerminator() << '\n'); 775 ++NumFolds; 776 ConstantFoldTerminator(BB, true); 777 return true; 778 } 779 780 Instruction *CondInst = dyn_cast<Instruction>(Condition); 781 782 // All the rest of our checks depend on the condition being an instruction. 783 if (!CondInst) { 784 // FIXME: Unify this with code below. 785 if (ProcessThreadableEdges(Condition, BB, Preference, Terminator)) 786 return true; 787 return false; 788 } 789 790 791 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) { 792 // If we're branching on a conditional, LVI might be able to determine 793 // it's value at the branch instruction. We only handle comparisons 794 // against a constant at this time. 795 // TODO: This should be extended to handle switches as well. 796 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 797 Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1)); 798 if (CondBr && CondConst && CondBr->isConditional()) { 799 LazyValueInfo::Tristate Ret = 800 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0), 801 CondConst, CondBr); 802 if (Ret != LazyValueInfo::Unknown) { 803 unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0; 804 unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1; 805 CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true); 806 BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr); 807 CondBr->eraseFromParent(); 808 if (CondCmp->use_empty()) 809 CondCmp->eraseFromParent(); 810 else if (CondCmp->getParent() == BB) { 811 // If the fact we just learned is true for all uses of the 812 // condition, replace it with a constant value 813 auto *CI = Ret == LazyValueInfo::True ? 814 ConstantInt::getTrue(CondCmp->getType()) : 815 ConstantInt::getFalse(CondCmp->getType()); 816 CondCmp->replaceAllUsesWith(CI); 817 CondCmp->eraseFromParent(); 818 } 819 return true; 820 } 821 } 822 823 if (CondBr && CondConst && TryToUnfoldSelect(CondCmp, BB)) 824 return true; 825 } 826 827 // Check for some cases that are worth simplifying. Right now we want to look 828 // for loads that are used by a switch or by the condition for the branch. If 829 // we see one, check to see if it's partially redundant. If so, insert a PHI 830 // which can then be used to thread the values. 831 // 832 Value *SimplifyValue = CondInst; 833 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue)) 834 if (isa<Constant>(CondCmp->getOperand(1))) 835 SimplifyValue = CondCmp->getOperand(0); 836 837 // TODO: There are other places where load PRE would be profitable, such as 838 // more complex comparisons. 839 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue)) 840 if (SimplifyPartiallyRedundantLoad(LI)) 841 return true; 842 843 844 // Handle a variety of cases where we are branching on something derived from 845 // a PHI node in the current block. If we can prove that any predecessors 846 // compute a predictable value based on a PHI node, thread those predecessors. 847 // 848 if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator)) 849 return true; 850 851 // If this is an otherwise-unfoldable branch on a phi node in the current 852 // block, see if we can simplify. 853 if (PHINode *PN = dyn_cast<PHINode>(CondInst)) 854 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 855 return ProcessBranchOnPHI(PN); 856 857 858 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify. 859 if (CondInst->getOpcode() == Instruction::Xor && 860 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 861 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst)); 862 863 // Search for a stronger dominating condition that can be used to simplify a 864 // conditional branch leaving BB. 865 if (ProcessImpliedCondition(BB)) 866 return true; 867 868 return false; 869 } 870 871 bool JumpThreadingPass::ProcessImpliedCondition(BasicBlock *BB) { 872 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 873 if (!BI || !BI->isConditional()) 874 return false; 875 876 Value *Cond = BI->getCondition(); 877 BasicBlock *CurrentBB = BB; 878 BasicBlock *CurrentPred = BB->getSinglePredecessor(); 879 unsigned Iter = 0; 880 881 auto &DL = BB->getModule()->getDataLayout(); 882 883 while (CurrentPred && Iter++ < ImplicationSearchThreshold) { 884 auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator()); 885 if (!PBI || !PBI->isConditional()) 886 return false; 887 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB) 888 return false; 889 890 bool FalseDest = PBI->getSuccessor(1) == CurrentBB; 891 Optional<bool> Implication = 892 isImpliedCondition(PBI->getCondition(), Cond, DL, FalseDest); 893 if (Implication) { 894 BI->getSuccessor(*Implication ? 1 : 0)->removePredecessor(BB); 895 BranchInst::Create(BI->getSuccessor(*Implication ? 0 : 1), BI); 896 BI->eraseFromParent(); 897 return true; 898 } 899 CurrentBB = CurrentPred; 900 CurrentPred = CurrentBB->getSinglePredecessor(); 901 } 902 903 return false; 904 } 905 906 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant 907 /// load instruction, eliminate it by replacing it with a PHI node. This is an 908 /// important optimization that encourages jump threading, and needs to be run 909 /// interlaced with other jump threading tasks. 910 bool JumpThreadingPass::SimplifyPartiallyRedundantLoad(LoadInst *LI) { 911 // Don't hack volatile and ordered loads. 912 if (!LI->isUnordered()) return false; 913 914 // If the load is defined in a block with exactly one predecessor, it can't be 915 // partially redundant. 916 BasicBlock *LoadBB = LI->getParent(); 917 if (LoadBB->getSinglePredecessor()) 918 return false; 919 920 // If the load is defined in an EH pad, it can't be partially redundant, 921 // because the edges between the invoke and the EH pad cannot have other 922 // instructions between them. 923 if (LoadBB->isEHPad()) 924 return false; 925 926 Value *LoadedPtr = LI->getOperand(0); 927 928 // If the loaded operand is defined in the LoadBB, it can't be available. 929 // TODO: Could do simple PHI translation, that would be fun :) 930 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr)) 931 if (PtrOp->getParent() == LoadBB) 932 return false; 933 934 // Scan a few instructions up from the load, to see if it is obviously live at 935 // the entry to its block. 936 BasicBlock::iterator BBIt(LI); 937 bool IsLoadCSE; 938 if (Value *AvailableVal = 939 FindAvailableLoadedValue(LI, LoadBB, BBIt, DefMaxInstsToScan, nullptr, &IsLoadCSE)) { 940 // If the value of the load is locally available within the block, just use 941 // it. This frequently occurs for reg2mem'd allocas. 942 943 if (IsLoadCSE) { 944 LoadInst *NLI = cast<LoadInst>(AvailableVal); 945 combineMetadataForCSE(NLI, LI); 946 }; 947 948 // If the returned value is the load itself, replace with an undef. This can 949 // only happen in dead loops. 950 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType()); 951 if (AvailableVal->getType() != LI->getType()) 952 AvailableVal = 953 CastInst::CreateBitOrPointerCast(AvailableVal, LI->getType(), "", LI); 954 LI->replaceAllUsesWith(AvailableVal); 955 LI->eraseFromParent(); 956 return true; 957 } 958 959 // Otherwise, if we scanned the whole block and got to the top of the block, 960 // we know the block is locally transparent to the load. If not, something 961 // might clobber its value. 962 if (BBIt != LoadBB->begin()) 963 return false; 964 965 // If all of the loads and stores that feed the value have the same AA tags, 966 // then we can propagate them onto any newly inserted loads. 967 AAMDNodes AATags; 968 LI->getAAMetadata(AATags); 969 970 SmallPtrSet<BasicBlock*, 8> PredsScanned; 971 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy; 972 AvailablePredsTy AvailablePreds; 973 BasicBlock *OneUnavailablePred = nullptr; 974 SmallVector<LoadInst*, 8> CSELoads; 975 976 // If we got here, the loaded value is transparent through to the start of the 977 // block. Check to see if it is available in any of the predecessor blocks. 978 for (BasicBlock *PredBB : predecessors(LoadBB)) { 979 // If we already scanned this predecessor, skip it. 980 if (!PredsScanned.insert(PredBB).second) 981 continue; 982 983 // Scan the predecessor to see if the value is available in the pred. 984 BBIt = PredBB->end(); 985 Value *PredAvailable = FindAvailableLoadedValue(LI, PredBB, BBIt, 986 DefMaxInstsToScan, 987 nullptr, 988 &IsLoadCSE); 989 if (!PredAvailable) { 990 OneUnavailablePred = PredBB; 991 continue; 992 } 993 994 if (IsLoadCSE) 995 CSELoads.push_back(cast<LoadInst>(PredAvailable)); 996 997 // If so, this load is partially redundant. Remember this info so that we 998 // can create a PHI node. 999 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable)); 1000 } 1001 1002 // If the loaded value isn't available in any predecessor, it isn't partially 1003 // redundant. 1004 if (AvailablePreds.empty()) return false; 1005 1006 // Okay, the loaded value is available in at least one (and maybe all!) 1007 // predecessors. If the value is unavailable in more than one unique 1008 // predecessor, we want to insert a merge block for those common predecessors. 1009 // This ensures that we only have to insert one reload, thus not increasing 1010 // code size. 1011 BasicBlock *UnavailablePred = nullptr; 1012 1013 // If there is exactly one predecessor where the value is unavailable, the 1014 // already computed 'OneUnavailablePred' block is it. If it ends in an 1015 // unconditional branch, we know that it isn't a critical edge. 1016 if (PredsScanned.size() == AvailablePreds.size()+1 && 1017 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) { 1018 UnavailablePred = OneUnavailablePred; 1019 } else if (PredsScanned.size() != AvailablePreds.size()) { 1020 // Otherwise, we had multiple unavailable predecessors or we had a critical 1021 // edge from the one. 1022 SmallVector<BasicBlock*, 8> PredsToSplit; 1023 SmallPtrSet<BasicBlock*, 8> AvailablePredSet; 1024 1025 for (const auto &AvailablePred : AvailablePreds) 1026 AvailablePredSet.insert(AvailablePred.first); 1027 1028 // Add all the unavailable predecessors to the PredsToSplit list. 1029 for (BasicBlock *P : predecessors(LoadBB)) { 1030 // If the predecessor is an indirect goto, we can't split the edge. 1031 if (isa<IndirectBrInst>(P->getTerminator())) 1032 return false; 1033 1034 if (!AvailablePredSet.count(P)) 1035 PredsToSplit.push_back(P); 1036 } 1037 1038 // Split them out to their own block. 1039 UnavailablePred = SplitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split"); 1040 } 1041 1042 // If the value isn't available in all predecessors, then there will be 1043 // exactly one where it isn't available. Insert a load on that edge and add 1044 // it to the AvailablePreds list. 1045 if (UnavailablePred) { 1046 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 && 1047 "Can't handle critical edge here!"); 1048 LoadInst *NewVal = 1049 new LoadInst(LoadedPtr, LI->getName() + ".pr", false, 1050 LI->getAlignment(), LI->getOrdering(), LI->getSynchScope(), 1051 UnavailablePred->getTerminator()); 1052 NewVal->setDebugLoc(LI->getDebugLoc()); 1053 if (AATags) 1054 NewVal->setAAMetadata(AATags); 1055 1056 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal)); 1057 } 1058 1059 // Now we know that each predecessor of this block has a value in 1060 // AvailablePreds, sort them for efficient access as we're walking the preds. 1061 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end()); 1062 1063 // Create a PHI node at the start of the block for the PRE'd load value. 1064 pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB); 1065 PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "", 1066 &LoadBB->front()); 1067 PN->takeName(LI); 1068 PN->setDebugLoc(LI->getDebugLoc()); 1069 1070 // Insert new entries into the PHI for each predecessor. A single block may 1071 // have multiple entries here. 1072 for (pred_iterator PI = PB; PI != PE; ++PI) { 1073 BasicBlock *P = *PI; 1074 AvailablePredsTy::iterator I = 1075 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(), 1076 std::make_pair(P, (Value*)nullptr)); 1077 1078 assert(I != AvailablePreds.end() && I->first == P && 1079 "Didn't find entry for predecessor!"); 1080 1081 // If we have an available predecessor but it requires casting, insert the 1082 // cast in the predecessor and use the cast. Note that we have to update the 1083 // AvailablePreds vector as we go so that all of the PHI entries for this 1084 // predecessor use the same bitcast. 1085 Value *&PredV = I->second; 1086 if (PredV->getType() != LI->getType()) 1087 PredV = CastInst::CreateBitOrPointerCast(PredV, LI->getType(), "", 1088 P->getTerminator()); 1089 1090 PN->addIncoming(PredV, I->first); 1091 } 1092 1093 for (LoadInst *PredLI : CSELoads) { 1094 combineMetadataForCSE(PredLI, LI); 1095 } 1096 1097 LI->replaceAllUsesWith(PN); 1098 LI->eraseFromParent(); 1099 1100 return true; 1101 } 1102 1103 /// FindMostPopularDest - The specified list contains multiple possible 1104 /// threadable destinations. Pick the one that occurs the most frequently in 1105 /// the list. 1106 static BasicBlock * 1107 FindMostPopularDest(BasicBlock *BB, 1108 const SmallVectorImpl<std::pair<BasicBlock*, 1109 BasicBlock*> > &PredToDestList) { 1110 assert(!PredToDestList.empty()); 1111 1112 // Determine popularity. If there are multiple possible destinations, we 1113 // explicitly choose to ignore 'undef' destinations. We prefer to thread 1114 // blocks with known and real destinations to threading undef. We'll handle 1115 // them later if interesting. 1116 DenseMap<BasicBlock*, unsigned> DestPopularity; 1117 for (const auto &PredToDest : PredToDestList) 1118 if (PredToDest.second) 1119 DestPopularity[PredToDest.second]++; 1120 1121 // Find the most popular dest. 1122 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin(); 1123 BasicBlock *MostPopularDest = DPI->first; 1124 unsigned Popularity = DPI->second; 1125 SmallVector<BasicBlock*, 4> SamePopularity; 1126 1127 for (++DPI; DPI != DestPopularity.end(); ++DPI) { 1128 // If the popularity of this entry isn't higher than the popularity we've 1129 // seen so far, ignore it. 1130 if (DPI->second < Popularity) 1131 ; // ignore. 1132 else if (DPI->second == Popularity) { 1133 // If it is the same as what we've seen so far, keep track of it. 1134 SamePopularity.push_back(DPI->first); 1135 } else { 1136 // If it is more popular, remember it. 1137 SamePopularity.clear(); 1138 MostPopularDest = DPI->first; 1139 Popularity = DPI->second; 1140 } 1141 } 1142 1143 // Okay, now we know the most popular destination. If there is more than one 1144 // destination, we need to determine one. This is arbitrary, but we need 1145 // to make a deterministic decision. Pick the first one that appears in the 1146 // successor list. 1147 if (!SamePopularity.empty()) { 1148 SamePopularity.push_back(MostPopularDest); 1149 TerminatorInst *TI = BB->getTerminator(); 1150 for (unsigned i = 0; ; ++i) { 1151 assert(i != TI->getNumSuccessors() && "Didn't find any successor!"); 1152 1153 if (!is_contained(SamePopularity, TI->getSuccessor(i))) 1154 continue; 1155 1156 MostPopularDest = TI->getSuccessor(i); 1157 break; 1158 } 1159 } 1160 1161 // Okay, we have finally picked the most popular destination. 1162 return MostPopularDest; 1163 } 1164 1165 bool JumpThreadingPass::ProcessThreadableEdges(Value *Cond, BasicBlock *BB, 1166 ConstantPreference Preference, 1167 Instruction *CxtI) { 1168 // If threading this would thread across a loop header, don't even try to 1169 // thread the edge. 1170 if (LoopHeaders.count(BB)) 1171 return false; 1172 1173 PredValueInfoTy PredValues; 1174 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI)) 1175 return false; 1176 1177 assert(!PredValues.empty() && 1178 "ComputeValueKnownInPredecessors returned true with no values"); 1179 1180 DEBUG(dbgs() << "IN BB: " << *BB; 1181 for (const auto &PredValue : PredValues) { 1182 dbgs() << " BB '" << BB->getName() << "': FOUND condition = " 1183 << *PredValue.first 1184 << " for pred '" << PredValue.second->getName() << "'.\n"; 1185 }); 1186 1187 // Decide what we want to thread through. Convert our list of known values to 1188 // a list of known destinations for each pred. This also discards duplicate 1189 // predecessors and keeps track of the undefined inputs (which are represented 1190 // as a null dest in the PredToDestList). 1191 SmallPtrSet<BasicBlock*, 16> SeenPreds; 1192 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList; 1193 1194 BasicBlock *OnlyDest = nullptr; 1195 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL; 1196 1197 for (const auto &PredValue : PredValues) { 1198 BasicBlock *Pred = PredValue.second; 1199 if (!SeenPreds.insert(Pred).second) 1200 continue; // Duplicate predecessor entry. 1201 1202 // If the predecessor ends with an indirect goto, we can't change its 1203 // destination. 1204 if (isa<IndirectBrInst>(Pred->getTerminator())) 1205 continue; 1206 1207 Constant *Val = PredValue.first; 1208 1209 BasicBlock *DestBB; 1210 if (isa<UndefValue>(Val)) 1211 DestBB = nullptr; 1212 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) 1213 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero()); 1214 else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 1215 DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor(); 1216 } else { 1217 assert(isa<IndirectBrInst>(BB->getTerminator()) 1218 && "Unexpected terminator"); 1219 DestBB = cast<BlockAddress>(Val)->getBasicBlock(); 1220 } 1221 1222 // If we have exactly one destination, remember it for efficiency below. 1223 if (PredToDestList.empty()) 1224 OnlyDest = DestBB; 1225 else if (OnlyDest != DestBB) 1226 OnlyDest = MultipleDestSentinel; 1227 1228 PredToDestList.push_back(std::make_pair(Pred, DestBB)); 1229 } 1230 1231 // If all edges were unthreadable, we fail. 1232 if (PredToDestList.empty()) 1233 return false; 1234 1235 // Determine which is the most common successor. If we have many inputs and 1236 // this block is a switch, we want to start by threading the batch that goes 1237 // to the most popular destination first. If we only know about one 1238 // threadable destination (the common case) we can avoid this. 1239 BasicBlock *MostPopularDest = OnlyDest; 1240 1241 if (MostPopularDest == MultipleDestSentinel) 1242 MostPopularDest = FindMostPopularDest(BB, PredToDestList); 1243 1244 // Now that we know what the most popular destination is, factor all 1245 // predecessors that will jump to it into a single predecessor. 1246 SmallVector<BasicBlock*, 16> PredsToFactor; 1247 for (const auto &PredToDest : PredToDestList) 1248 if (PredToDest.second == MostPopularDest) { 1249 BasicBlock *Pred = PredToDest.first; 1250 1251 // This predecessor may be a switch or something else that has multiple 1252 // edges to the block. Factor each of these edges by listing them 1253 // according to # occurrences in PredsToFactor. 1254 for (BasicBlock *Succ : successors(Pred)) 1255 if (Succ == BB) 1256 PredsToFactor.push_back(Pred); 1257 } 1258 1259 // If the threadable edges are branching on an undefined value, we get to pick 1260 // the destination that these predecessors should get to. 1261 if (!MostPopularDest) 1262 MostPopularDest = BB->getTerminator()-> 1263 getSuccessor(GetBestDestForJumpOnUndef(BB)); 1264 1265 // Ok, try to thread it! 1266 return ThreadEdge(BB, PredsToFactor, MostPopularDest); 1267 } 1268 1269 /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on 1270 /// a PHI node in the current block. See if there are any simplifications we 1271 /// can do based on inputs to the phi node. 1272 /// 1273 bool JumpThreadingPass::ProcessBranchOnPHI(PHINode *PN) { 1274 BasicBlock *BB = PN->getParent(); 1275 1276 // TODO: We could make use of this to do it once for blocks with common PHI 1277 // values. 1278 SmallVector<BasicBlock*, 1> PredBBs; 1279 PredBBs.resize(1); 1280 1281 // If any of the predecessor blocks end in an unconditional branch, we can 1282 // *duplicate* the conditional branch into that block in order to further 1283 // encourage jump threading and to eliminate cases where we have branch on a 1284 // phi of an icmp (branch on icmp is much better). 1285 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1286 BasicBlock *PredBB = PN->getIncomingBlock(i); 1287 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator())) 1288 if (PredBr->isUnconditional()) { 1289 PredBBs[0] = PredBB; 1290 // Try to duplicate BB into PredBB. 1291 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs)) 1292 return true; 1293 } 1294 } 1295 1296 return false; 1297 } 1298 1299 /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on 1300 /// a xor instruction in the current block. See if there are any 1301 /// simplifications we can do based on inputs to the xor. 1302 /// 1303 bool JumpThreadingPass::ProcessBranchOnXOR(BinaryOperator *BO) { 1304 BasicBlock *BB = BO->getParent(); 1305 1306 // If either the LHS or RHS of the xor is a constant, don't do this 1307 // optimization. 1308 if (isa<ConstantInt>(BO->getOperand(0)) || 1309 isa<ConstantInt>(BO->getOperand(1))) 1310 return false; 1311 1312 // If the first instruction in BB isn't a phi, we won't be able to infer 1313 // anything special about any particular predecessor. 1314 if (!isa<PHINode>(BB->front())) 1315 return false; 1316 1317 // If this BB is a landing pad, we won't be able to split the edge into it. 1318 if (BB->isEHPad()) 1319 return false; 1320 1321 // If we have a xor as the branch input to this block, and we know that the 1322 // LHS or RHS of the xor in any predecessor is true/false, then we can clone 1323 // the condition into the predecessor and fix that value to true, saving some 1324 // logical ops on that path and encouraging other paths to simplify. 1325 // 1326 // This copies something like this: 1327 // 1328 // BB: 1329 // %X = phi i1 [1], [%X'] 1330 // %Y = icmp eq i32 %A, %B 1331 // %Z = xor i1 %X, %Y 1332 // br i1 %Z, ... 1333 // 1334 // Into: 1335 // BB': 1336 // %Y = icmp ne i32 %A, %B 1337 // br i1 %Y, ... 1338 1339 PredValueInfoTy XorOpValues; 1340 bool isLHS = true; 1341 if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues, 1342 WantInteger, BO)) { 1343 assert(XorOpValues.empty()); 1344 if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues, 1345 WantInteger, BO)) 1346 return false; 1347 isLHS = false; 1348 } 1349 1350 assert(!XorOpValues.empty() && 1351 "ComputeValueKnownInPredecessors returned true with no values"); 1352 1353 // Scan the information to see which is most popular: true or false. The 1354 // predecessors can be of the set true, false, or undef. 1355 unsigned NumTrue = 0, NumFalse = 0; 1356 for (const auto &XorOpValue : XorOpValues) { 1357 if (isa<UndefValue>(XorOpValue.first)) 1358 // Ignore undefs for the count. 1359 continue; 1360 if (cast<ConstantInt>(XorOpValue.first)->isZero()) 1361 ++NumFalse; 1362 else 1363 ++NumTrue; 1364 } 1365 1366 // Determine which value to split on, true, false, or undef if neither. 1367 ConstantInt *SplitVal = nullptr; 1368 if (NumTrue > NumFalse) 1369 SplitVal = ConstantInt::getTrue(BB->getContext()); 1370 else if (NumTrue != 0 || NumFalse != 0) 1371 SplitVal = ConstantInt::getFalse(BB->getContext()); 1372 1373 // Collect all of the blocks that this can be folded into so that we can 1374 // factor this once and clone it once. 1375 SmallVector<BasicBlock*, 8> BlocksToFoldInto; 1376 for (const auto &XorOpValue : XorOpValues) { 1377 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first)) 1378 continue; 1379 1380 BlocksToFoldInto.push_back(XorOpValue.second); 1381 } 1382 1383 // If we inferred a value for all of the predecessors, then duplication won't 1384 // help us. However, we can just replace the LHS or RHS with the constant. 1385 if (BlocksToFoldInto.size() == 1386 cast<PHINode>(BB->front()).getNumIncomingValues()) { 1387 if (!SplitVal) { 1388 // If all preds provide undef, just nuke the xor, because it is undef too. 1389 BO->replaceAllUsesWith(UndefValue::get(BO->getType())); 1390 BO->eraseFromParent(); 1391 } else if (SplitVal->isZero()) { 1392 // If all preds provide 0, replace the xor with the other input. 1393 BO->replaceAllUsesWith(BO->getOperand(isLHS)); 1394 BO->eraseFromParent(); 1395 } else { 1396 // If all preds provide 1, set the computed value to 1. 1397 BO->setOperand(!isLHS, SplitVal); 1398 } 1399 1400 return true; 1401 } 1402 1403 // Try to duplicate BB into PredBB. 1404 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto); 1405 } 1406 1407 1408 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new 1409 /// predecessor to the PHIBB block. If it has PHI nodes, add entries for 1410 /// NewPred using the entries from OldPred (suitably mapped). 1411 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, 1412 BasicBlock *OldPred, 1413 BasicBlock *NewPred, 1414 DenseMap<Instruction*, Value*> &ValueMap) { 1415 for (BasicBlock::iterator PNI = PHIBB->begin(); 1416 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) { 1417 // Ok, we have a PHI node. Figure out what the incoming value was for the 1418 // DestBlock. 1419 Value *IV = PN->getIncomingValueForBlock(OldPred); 1420 1421 // Remap the value if necessary. 1422 if (Instruction *Inst = dyn_cast<Instruction>(IV)) { 1423 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst); 1424 if (I != ValueMap.end()) 1425 IV = I->second; 1426 } 1427 1428 PN->addIncoming(IV, NewPred); 1429 } 1430 } 1431 1432 /// ThreadEdge - We have decided that it is safe and profitable to factor the 1433 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB 1434 /// across BB. Transform the IR to reflect this change. 1435 bool JumpThreadingPass::ThreadEdge(BasicBlock *BB, 1436 const SmallVectorImpl<BasicBlock *> &PredBBs, 1437 BasicBlock *SuccBB) { 1438 // If threading to the same block as we come from, we would infinite loop. 1439 if (SuccBB == BB) { 1440 DEBUG(dbgs() << " Not threading across BB '" << BB->getName() 1441 << "' - would thread to self!\n"); 1442 return false; 1443 } 1444 1445 // If threading this would thread across a loop header, don't thread the edge. 1446 // See the comments above FindLoopHeaders for justifications and caveats. 1447 if (LoopHeaders.count(BB)) { 1448 DEBUG(dbgs() << " Not threading across loop header BB '" << BB->getName() 1449 << "' to dest BB '" << SuccBB->getName() 1450 << "' - it might create an irreducible loop!\n"); 1451 return false; 1452 } 1453 1454 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, BBDupThreshold); 1455 if (JumpThreadCost > BBDupThreshold) { 1456 DEBUG(dbgs() << " Not threading BB '" << BB->getName() 1457 << "' - Cost is too high: " << JumpThreadCost << "\n"); 1458 return false; 1459 } 1460 1461 // And finally, do it! Start by factoring the predecessors if needed. 1462 BasicBlock *PredBB; 1463 if (PredBBs.size() == 1) 1464 PredBB = PredBBs[0]; 1465 else { 1466 DEBUG(dbgs() << " Factoring out " << PredBBs.size() 1467 << " common predecessors.\n"); 1468 PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm"); 1469 } 1470 1471 // And finally, do it! 1472 DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() << "' to '" 1473 << SuccBB->getName() << "' with cost: " << JumpThreadCost 1474 << ", across block:\n " 1475 << *BB << "\n"); 1476 1477 LVI->threadEdge(PredBB, BB, SuccBB); 1478 1479 // We are going to have to map operands from the original BB block to the new 1480 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to 1481 // account for entry from PredBB. 1482 DenseMap<Instruction*, Value*> ValueMapping; 1483 1484 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), 1485 BB->getName()+".thread", 1486 BB->getParent(), BB); 1487 NewBB->moveAfter(PredBB); 1488 1489 // Set the block frequency of NewBB. 1490 if (HasProfileData) { 1491 auto NewBBFreq = 1492 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB); 1493 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency()); 1494 } 1495 1496 BasicBlock::iterator BI = BB->begin(); 1497 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 1498 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 1499 1500 // Clone the non-phi instructions of BB into NewBB, keeping track of the 1501 // mapping and using it to remap operands in the cloned instructions. 1502 for (; !isa<TerminatorInst>(BI); ++BI) { 1503 Instruction *New = BI->clone(); 1504 New->setName(BI->getName()); 1505 NewBB->getInstList().push_back(New); 1506 ValueMapping[&*BI] = New; 1507 1508 // Remap operands to patch up intra-block references. 1509 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 1510 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 1511 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 1512 if (I != ValueMapping.end()) 1513 New->setOperand(i, I->second); 1514 } 1515 } 1516 1517 // We didn't copy the terminator from BB over to NewBB, because there is now 1518 // an unconditional jump to SuccBB. Insert the unconditional jump. 1519 BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB); 1520 NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc()); 1521 1522 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the 1523 // PHI nodes for NewBB now. 1524 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping); 1525 1526 // If there were values defined in BB that are used outside the block, then we 1527 // now have to update all uses of the value to use either the original value, 1528 // the cloned value, or some PHI derived value. This can require arbitrary 1529 // PHI insertion, of which we are prepared to do, clean these up now. 1530 SSAUpdater SSAUpdate; 1531 SmallVector<Use*, 16> UsesToRename; 1532 for (Instruction &I : *BB) { 1533 // Scan all uses of this instruction to see if it is used outside of its 1534 // block, and if so, record them in UsesToRename. 1535 for (Use &U : I.uses()) { 1536 Instruction *User = cast<Instruction>(U.getUser()); 1537 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 1538 if (UserPN->getIncomingBlock(U) == BB) 1539 continue; 1540 } else if (User->getParent() == BB) 1541 continue; 1542 1543 UsesToRename.push_back(&U); 1544 } 1545 1546 // If there are no uses outside the block, we're done with this instruction. 1547 if (UsesToRename.empty()) 1548 continue; 1549 1550 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n"); 1551 1552 // We found a use of I outside of BB. Rename all uses of I that are outside 1553 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 1554 // with the two values we know. 1555 SSAUpdate.Initialize(I.getType(), I.getName()); 1556 SSAUpdate.AddAvailableValue(BB, &I); 1557 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]); 1558 1559 while (!UsesToRename.empty()) 1560 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 1561 DEBUG(dbgs() << "\n"); 1562 } 1563 1564 1565 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to 1566 // NewBB instead of BB. This eliminates predecessors from BB, which requires 1567 // us to simplify any PHI nodes in BB. 1568 TerminatorInst *PredTerm = PredBB->getTerminator(); 1569 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) 1570 if (PredTerm->getSuccessor(i) == BB) { 1571 BB->removePredecessor(PredBB, true); 1572 PredTerm->setSuccessor(i, NewBB); 1573 } 1574 1575 // At this point, the IR is fully up to date and consistent. Do a quick scan 1576 // over the new instructions and zap any that are constants or dead. This 1577 // frequently happens because of phi translation. 1578 SimplifyInstructionsInBlock(NewBB, TLI); 1579 1580 // Update the edge weight from BB to SuccBB, which should be less than before. 1581 UpdateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB); 1582 1583 // Threaded an edge! 1584 ++NumThreads; 1585 return true; 1586 } 1587 1588 /// Create a new basic block that will be the predecessor of BB and successor of 1589 /// all blocks in Preds. When profile data is available, update the frequency of 1590 /// this new block. 1591 BasicBlock *JumpThreadingPass::SplitBlockPreds(BasicBlock *BB, 1592 ArrayRef<BasicBlock *> Preds, 1593 const char *Suffix) { 1594 // Collect the frequencies of all predecessors of BB, which will be used to 1595 // update the edge weight on BB->SuccBB. 1596 BlockFrequency PredBBFreq(0); 1597 if (HasProfileData) 1598 for (auto Pred : Preds) 1599 PredBBFreq += BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB); 1600 1601 BasicBlock *PredBB = SplitBlockPredecessors(BB, Preds, Suffix); 1602 1603 // Set the block frequency of the newly created PredBB, which is the sum of 1604 // frequencies of Preds. 1605 if (HasProfileData) 1606 BFI->setBlockFreq(PredBB, PredBBFreq.getFrequency()); 1607 return PredBB; 1608 } 1609 1610 bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) { 1611 const TerminatorInst *TI = BB->getTerminator(); 1612 assert(TI->getNumSuccessors() > 1 && "not a split"); 1613 1614 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof); 1615 if (!WeightsNode) 1616 return false; 1617 1618 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0)); 1619 if (MDName->getString() != "branch_weights") 1620 return false; 1621 1622 // Ensure there are weights for all of the successors. Note that the first 1623 // operand to the metadata node is a name, not a weight. 1624 return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1; 1625 } 1626 1627 /// Update the block frequency of BB and branch weight and the metadata on the 1628 /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 - 1629 /// Freq(PredBB->BB) / Freq(BB->SuccBB). 1630 void JumpThreadingPass::UpdateBlockFreqAndEdgeWeight(BasicBlock *PredBB, 1631 BasicBlock *BB, 1632 BasicBlock *NewBB, 1633 BasicBlock *SuccBB) { 1634 if (!HasProfileData) 1635 return; 1636 1637 assert(BFI && BPI && "BFI & BPI should have been created here"); 1638 1639 // As the edge from PredBB to BB is deleted, we have to update the block 1640 // frequency of BB. 1641 auto BBOrigFreq = BFI->getBlockFreq(BB); 1642 auto NewBBFreq = BFI->getBlockFreq(NewBB); 1643 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB); 1644 auto BBNewFreq = BBOrigFreq - NewBBFreq; 1645 BFI->setBlockFreq(BB, BBNewFreq.getFrequency()); 1646 1647 // Collect updated outgoing edges' frequencies from BB and use them to update 1648 // edge probabilities. 1649 SmallVector<uint64_t, 4> BBSuccFreq; 1650 for (BasicBlock *Succ : successors(BB)) { 1651 auto SuccFreq = (Succ == SuccBB) 1652 ? BB2SuccBBFreq - NewBBFreq 1653 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ); 1654 BBSuccFreq.push_back(SuccFreq.getFrequency()); 1655 } 1656 1657 uint64_t MaxBBSuccFreq = 1658 *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end()); 1659 1660 SmallVector<BranchProbability, 4> BBSuccProbs; 1661 if (MaxBBSuccFreq == 0) 1662 BBSuccProbs.assign(BBSuccFreq.size(), 1663 {1, static_cast<unsigned>(BBSuccFreq.size())}); 1664 else { 1665 for (uint64_t Freq : BBSuccFreq) 1666 BBSuccProbs.push_back( 1667 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq)); 1668 // Normalize edge probabilities so that they sum up to one. 1669 BranchProbability::normalizeProbabilities(BBSuccProbs.begin(), 1670 BBSuccProbs.end()); 1671 } 1672 1673 // Update edge probabilities in BPI. 1674 for (int I = 0, E = BBSuccProbs.size(); I < E; I++) 1675 BPI->setEdgeProbability(BB, I, BBSuccProbs[I]); 1676 1677 // Update the profile metadata as well. 1678 // 1679 // Don't do this if the profile of the transformed blocks was statically 1680 // estimated. (This could occur despite the function having an entry 1681 // frequency in completely cold parts of the CFG.) 1682 // 1683 // In this case we don't want to suggest to subsequent passes that the 1684 // calculated weights are fully consistent. Consider this graph: 1685 // 1686 // check_1 1687 // 50% / | 1688 // eq_1 | 50% 1689 // \ | 1690 // check_2 1691 // 50% / | 1692 // eq_2 | 50% 1693 // \ | 1694 // check_3 1695 // 50% / | 1696 // eq_3 | 50% 1697 // \ | 1698 // 1699 // Assuming the blocks check_* all compare the same value against 1, 2 and 3, 1700 // the overall probabilities are inconsistent; the total probability that the 1701 // value is either 1, 2 or 3 is 150%. 1702 // 1703 // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3 1704 // becomes 0%. This is even worse if the edge whose probability becomes 0% is 1705 // the loop exit edge. Then based solely on static estimation we would assume 1706 // the loop was extremely hot. 1707 // 1708 // FIXME this locally as well so that BPI and BFI are consistent as well. We 1709 // shouldn't make edges extremely likely or unlikely based solely on static 1710 // estimation. 1711 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) { 1712 SmallVector<uint32_t, 4> Weights; 1713 for (auto Prob : BBSuccProbs) 1714 Weights.push_back(Prob.getNumerator()); 1715 1716 auto TI = BB->getTerminator(); 1717 TI->setMetadata( 1718 LLVMContext::MD_prof, 1719 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights)); 1720 } 1721 } 1722 1723 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch 1724 /// to BB which contains an i1 PHI node and a conditional branch on that PHI. 1725 /// If we can duplicate the contents of BB up into PredBB do so now, this 1726 /// improves the odds that the branch will be on an analyzable instruction like 1727 /// a compare. 1728 bool JumpThreadingPass::DuplicateCondBranchOnPHIIntoPred( 1729 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) { 1730 assert(!PredBBs.empty() && "Can't handle an empty set"); 1731 1732 // If BB is a loop header, then duplicating this block outside the loop would 1733 // cause us to transform this into an irreducible loop, don't do this. 1734 // See the comments above FindLoopHeaders for justifications and caveats. 1735 if (LoopHeaders.count(BB)) { 1736 DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName() 1737 << "' into predecessor block '" << PredBBs[0]->getName() 1738 << "' - it might create an irreducible loop!\n"); 1739 return false; 1740 } 1741 1742 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, BBDupThreshold); 1743 if (DuplicationCost > BBDupThreshold) { 1744 DEBUG(dbgs() << " Not duplicating BB '" << BB->getName() 1745 << "' - Cost is too high: " << DuplicationCost << "\n"); 1746 return false; 1747 } 1748 1749 // And finally, do it! Start by factoring the predecessors if needed. 1750 BasicBlock *PredBB; 1751 if (PredBBs.size() == 1) 1752 PredBB = PredBBs[0]; 1753 else { 1754 DEBUG(dbgs() << " Factoring out " << PredBBs.size() 1755 << " common predecessors.\n"); 1756 PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm"); 1757 } 1758 1759 // Okay, we decided to do this! Clone all the instructions in BB onto the end 1760 // of PredBB. 1761 DEBUG(dbgs() << " Duplicating block '" << BB->getName() << "' into end of '" 1762 << PredBB->getName() << "' to eliminate branch on phi. Cost: " 1763 << DuplicationCost << " block is:" << *BB << "\n"); 1764 1765 // Unless PredBB ends with an unconditional branch, split the edge so that we 1766 // can just clone the bits from BB into the end of the new PredBB. 1767 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator()); 1768 1769 if (!OldPredBranch || !OldPredBranch->isUnconditional()) { 1770 PredBB = SplitEdge(PredBB, BB); 1771 OldPredBranch = cast<BranchInst>(PredBB->getTerminator()); 1772 } 1773 1774 // We are going to have to map operands from the original BB block into the 1775 // PredBB block. Evaluate PHI nodes in BB. 1776 DenseMap<Instruction*, Value*> ValueMapping; 1777 1778 BasicBlock::iterator BI = BB->begin(); 1779 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 1780 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 1781 // Clone the non-phi instructions of BB into PredBB, keeping track of the 1782 // mapping and using it to remap operands in the cloned instructions. 1783 for (; BI != BB->end(); ++BI) { 1784 Instruction *New = BI->clone(); 1785 1786 // Remap operands to patch up intra-block references. 1787 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 1788 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 1789 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 1790 if (I != ValueMapping.end()) 1791 New->setOperand(i, I->second); 1792 } 1793 1794 // If this instruction can be simplified after the operands are updated, 1795 // just use the simplified value instead. This frequently happens due to 1796 // phi translation. 1797 if (Value *IV = 1798 SimplifyInstruction(New, BB->getModule()->getDataLayout())) { 1799 ValueMapping[&*BI] = IV; 1800 if (!New->mayHaveSideEffects()) { 1801 delete New; 1802 New = nullptr; 1803 } 1804 } else { 1805 ValueMapping[&*BI] = New; 1806 } 1807 if (New) { 1808 // Otherwise, insert the new instruction into the block. 1809 New->setName(BI->getName()); 1810 PredBB->getInstList().insert(OldPredBranch->getIterator(), New); 1811 } 1812 } 1813 1814 // Check to see if the targets of the branch had PHI nodes. If so, we need to 1815 // add entries to the PHI nodes for branch from PredBB now. 1816 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator()); 1817 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB, 1818 ValueMapping); 1819 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB, 1820 ValueMapping); 1821 1822 // If there were values defined in BB that are used outside the block, then we 1823 // now have to update all uses of the value to use either the original value, 1824 // the cloned value, or some PHI derived value. This can require arbitrary 1825 // PHI insertion, of which we are prepared to do, clean these up now. 1826 SSAUpdater SSAUpdate; 1827 SmallVector<Use*, 16> UsesToRename; 1828 for (Instruction &I : *BB) { 1829 // Scan all uses of this instruction to see if it is used outside of its 1830 // block, and if so, record them in UsesToRename. 1831 for (Use &U : I.uses()) { 1832 Instruction *User = cast<Instruction>(U.getUser()); 1833 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 1834 if (UserPN->getIncomingBlock(U) == BB) 1835 continue; 1836 } else if (User->getParent() == BB) 1837 continue; 1838 1839 UsesToRename.push_back(&U); 1840 } 1841 1842 // If there are no uses outside the block, we're done with this instruction. 1843 if (UsesToRename.empty()) 1844 continue; 1845 1846 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n"); 1847 1848 // We found a use of I outside of BB. Rename all uses of I that are outside 1849 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 1850 // with the two values we know. 1851 SSAUpdate.Initialize(I.getType(), I.getName()); 1852 SSAUpdate.AddAvailableValue(BB, &I); 1853 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[&I]); 1854 1855 while (!UsesToRename.empty()) 1856 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 1857 DEBUG(dbgs() << "\n"); 1858 } 1859 1860 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge 1861 // that we nuked. 1862 BB->removePredecessor(PredBB, true); 1863 1864 // Remove the unconditional branch at the end of the PredBB block. 1865 OldPredBranch->eraseFromParent(); 1866 1867 ++NumDupes; 1868 return true; 1869 } 1870 1871 /// TryToUnfoldSelect - Look for blocks of the form 1872 /// bb1: 1873 /// %a = select 1874 /// br bb 1875 /// 1876 /// bb2: 1877 /// %p = phi [%a, %bb] ... 1878 /// %c = icmp %p 1879 /// br i1 %c 1880 /// 1881 /// And expand the select into a branch structure if one of its arms allows %c 1882 /// to be folded. This later enables threading from bb1 over bb2. 1883 bool JumpThreadingPass::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) { 1884 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 1885 PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0)); 1886 Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1)); 1887 1888 if (!CondBr || !CondBr->isConditional() || !CondLHS || 1889 CondLHS->getParent() != BB) 1890 return false; 1891 1892 for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) { 1893 BasicBlock *Pred = CondLHS->getIncomingBlock(I); 1894 SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I)); 1895 1896 // Look if one of the incoming values is a select in the corresponding 1897 // predecessor. 1898 if (!SI || SI->getParent() != Pred || !SI->hasOneUse()) 1899 continue; 1900 1901 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator()); 1902 if (!PredTerm || !PredTerm->isUnconditional()) 1903 continue; 1904 1905 // Now check if one of the select values would allow us to constant fold the 1906 // terminator in BB. We don't do the transform if both sides fold, those 1907 // cases will be threaded in any case. 1908 LazyValueInfo::Tristate LHSFolds = 1909 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1), 1910 CondRHS, Pred, BB, CondCmp); 1911 LazyValueInfo::Tristate RHSFolds = 1912 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2), 1913 CondRHS, Pred, BB, CondCmp); 1914 if ((LHSFolds != LazyValueInfo::Unknown || 1915 RHSFolds != LazyValueInfo::Unknown) && 1916 LHSFolds != RHSFolds) { 1917 // Expand the select. 1918 // 1919 // Pred -- 1920 // | v 1921 // | NewBB 1922 // | | 1923 // |----- 1924 // v 1925 // BB 1926 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold", 1927 BB->getParent(), BB); 1928 // Move the unconditional branch to NewBB. 1929 PredTerm->removeFromParent(); 1930 NewBB->getInstList().insert(NewBB->end(), PredTerm); 1931 // Create a conditional branch and update PHI nodes. 1932 BranchInst::Create(NewBB, BB, SI->getCondition(), Pred); 1933 CondLHS->setIncomingValue(I, SI->getFalseValue()); 1934 CondLHS->addIncoming(SI->getTrueValue(), NewBB); 1935 // The select is now dead. 1936 SI->eraseFromParent(); 1937 1938 // Update any other PHI nodes in BB. 1939 for (BasicBlock::iterator BI = BB->begin(); 1940 PHINode *Phi = dyn_cast<PHINode>(BI); ++BI) 1941 if (Phi != CondLHS) 1942 Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB); 1943 return true; 1944 } 1945 } 1946 return false; 1947 } 1948 1949 /// TryToUnfoldSelectInCurrBB - Look for PHI/Select in the same BB of the form 1950 /// bb: 1951 /// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ... 1952 /// %s = select p, trueval, falseval 1953 /// 1954 /// And expand the select into a branch structure. This later enables 1955 /// jump-threading over bb in this pass. 1956 /// 1957 /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold 1958 /// select if the associated PHI has at least one constant. If the unfolded 1959 /// select is not jump-threaded, it will be folded again in the later 1960 /// optimizations. 1961 bool JumpThreadingPass::TryToUnfoldSelectInCurrBB(BasicBlock *BB) { 1962 // If threading this would thread across a loop header, don't thread the edge. 1963 // See the comments above FindLoopHeaders for justifications and caveats. 1964 if (LoopHeaders.count(BB)) 1965 return false; 1966 1967 // Look for a Phi/Select pair in the same basic block. The Phi feeds the 1968 // condition of the Select and at least one of the incoming values is a 1969 // constant. 1970 for (BasicBlock::iterator BI = BB->begin(); 1971 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) { 1972 unsigned NumPHIValues = PN->getNumIncomingValues(); 1973 if (NumPHIValues == 0 || !PN->hasOneUse()) 1974 continue; 1975 1976 SelectInst *SI = dyn_cast<SelectInst>(PN->user_back()); 1977 if (!SI || SI->getParent() != BB) 1978 continue; 1979 1980 Value *Cond = SI->getCondition(); 1981 if (!Cond || Cond != PN || !Cond->getType()->isIntegerTy(1)) 1982 continue; 1983 1984 bool HasConst = false; 1985 for (unsigned i = 0; i != NumPHIValues; ++i) { 1986 if (PN->getIncomingBlock(i) == BB) 1987 return false; 1988 if (isa<ConstantInt>(PN->getIncomingValue(i))) 1989 HasConst = true; 1990 } 1991 1992 if (HasConst) { 1993 // Expand the select. 1994 TerminatorInst *Term = 1995 SplitBlockAndInsertIfThen(SI->getCondition(), SI, false); 1996 PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI); 1997 NewPN->addIncoming(SI->getTrueValue(), Term->getParent()); 1998 NewPN->addIncoming(SI->getFalseValue(), BB); 1999 SI->replaceAllUsesWith(NewPN); 2000 SI->eraseFromParent(); 2001 return true; 2002 } 2003 } 2004 2005 return false; 2006 } 2007