1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Jump Threading pass.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Scalar/JumpThreading.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
21 #include "llvm/Analysis/CFG.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/GlobalsModRef.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/ConstantRange.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/MDBuilder.h"
33 #include "llvm/IR/Metadata.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Transforms/Scalar.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/Cloning.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/SSAUpdater.h"
47 using namespace jumpthreading;
49 #define DEBUG_TYPE "jump-threading"
51 STATISTIC(NumThreads, "Number of jumps threaded");
52 STATISTIC(NumFolds, "Number of terminators folded");
53 STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
55 static cl::opt<unsigned>
56 BBDuplicateThreshold("jump-threading-threshold",
57 cl::desc("Max block size to duplicate for jump threading"),
58 cl::init(6), cl::Hidden);
60 static cl::opt<unsigned>
61 ImplicationSearchThreshold(
62 "jump-threading-implication-search-threshold",
63 cl::desc("The number of predecessors to search for a stronger "
64 "condition to use to thread over a weaker condition"),
65 cl::init(3), cl::Hidden);
67 static cl::opt<bool> PrintLVIAfterJumpThreading(
68 "print-lvi-after-jump-threading",
69 cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false),
73 /// This pass performs 'jump threading', which looks at blocks that have
74 /// multiple predecessors and multiple successors. If one or more of the
75 /// predecessors of the block can be proven to always jump to one of the
76 /// successors, we forward the edge from the predecessor to the successor by
77 /// duplicating the contents of this block.
79 /// An example of when this can occur is code like this:
86 /// In this case, the unconditional branch at the end of the first if can be
87 /// revectored to the false side of the second if.
89 class JumpThreading : public FunctionPass {
90 JumpThreadingPass Impl;
93 static char ID; // Pass identification
94 JumpThreading(int T = -1) : FunctionPass(ID), Impl(T) {
95 initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
98 bool runOnFunction(Function &F) override;
100 void getAnalysisUsage(AnalysisUsage &AU) const override {
101 if (PrintLVIAfterJumpThreading)
102 AU.addRequired<DominatorTreeWrapperPass>();
103 AU.addRequired<AAResultsWrapperPass>();
104 AU.addRequired<LazyValueInfoWrapperPass>();
105 AU.addPreserved<GlobalsAAWrapperPass>();
106 AU.addRequired<TargetLibraryInfoWrapperPass>();
109 void releaseMemory() override { Impl.releaseMemory(); }
113 char JumpThreading::ID = 0;
114 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
115 "Jump Threading", false, false)
116 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
117 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
118 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
119 INITIALIZE_PASS_END(JumpThreading, "jump-threading",
120 "Jump Threading", false, false)
122 // Public interface to the Jump Threading pass
123 FunctionPass *llvm::createJumpThreadingPass(int Threshold) { return new JumpThreading(Threshold); }
125 JumpThreadingPass::JumpThreadingPass(int T) {
126 BBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
129 /// runOnFunction - Top level algorithm.
131 bool JumpThreading::runOnFunction(Function &F) {
134 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
135 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
136 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
137 std::unique_ptr<BlockFrequencyInfo> BFI;
138 std::unique_ptr<BranchProbabilityInfo> BPI;
139 bool HasProfileData = F.getEntryCount().hasValue();
140 if (HasProfileData) {
141 LoopInfo LI{DominatorTree(F)};
142 BPI.reset(new BranchProbabilityInfo(F, LI, TLI));
143 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
146 bool Changed = Impl.runImpl(F, TLI, LVI, AA, HasProfileData, std::move(BFI),
148 if (PrintLVIAfterJumpThreading) {
149 dbgs() << "LVI for function '" << F.getName() << "':\n";
150 LVI->printLVI(F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
156 PreservedAnalyses JumpThreadingPass::run(Function &F,
157 FunctionAnalysisManager &AM) {
159 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
160 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
161 auto &AA = AM.getResult<AAManager>(F);
163 std::unique_ptr<BlockFrequencyInfo> BFI;
164 std::unique_ptr<BranchProbabilityInfo> BPI;
165 bool HasProfileData = F.getEntryCount().hasValue();
166 if (HasProfileData) {
167 LoopInfo LI{DominatorTree(F)};
168 BPI.reset(new BranchProbabilityInfo(F, LI, &TLI));
169 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
172 bool Changed = runImpl(F, &TLI, &LVI, &AA, HasProfileData, std::move(BFI),
176 return PreservedAnalyses::all();
177 PreservedAnalyses PA;
178 PA.preserve<GlobalsAA>();
182 bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
183 LazyValueInfo *LVI_, AliasAnalysis *AA_,
184 bool HasProfileData_,
185 std::unique_ptr<BlockFrequencyInfo> BFI_,
186 std::unique_ptr<BranchProbabilityInfo> BPI_) {
188 DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
194 // When profile data is available, we need to update edge weights after
195 // successful jump threading, which requires both BPI and BFI being available.
196 HasProfileData = HasProfileData_;
197 auto *GuardDecl = F.getParent()->getFunction(
198 Intrinsic::getName(Intrinsic::experimental_guard));
199 HasGuards = GuardDecl && !GuardDecl->use_empty();
200 if (HasProfileData) {
201 BPI = std::move(BPI_);
202 BFI = std::move(BFI_);
205 // Remove unreachable blocks from function as they may result in infinite
206 // loop. We do threading if we found something profitable. Jump threading a
207 // branch can create other opportunities. If these opportunities form a cycle
208 // i.e. if any jump threading is undoing previous threading in the path, then
209 // we will loop forever. We take care of this issue by not jump threading for
210 // back edges. This works for normal cases but not for unreachable blocks as
211 // they may have cycle with no back edge.
212 bool EverChanged = false;
213 EverChanged |= removeUnreachableBlocks(F, LVI);
220 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
221 BasicBlock *BB = &*I;
222 // Thread all of the branches we can over this block.
223 while (ProcessBlock(BB))
228 // If the block is trivially dead, zap it. This eliminates the successor
229 // edges which simplifies the CFG.
230 if (pred_empty(BB) &&
231 BB != &BB->getParent()->getEntryBlock()) {
232 DEBUG(dbgs() << " JT: Deleting dead block '" << BB->getName()
233 << "' with terminator: " << *BB->getTerminator() << '\n');
234 LoopHeaders.erase(BB);
241 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
243 // Can't thread an unconditional jump, but if the block is "almost
244 // empty", we can replace uses of it with uses of the successor and make
246 // We should not eliminate the loop header or latch either, because
247 // eliminating a loop header or latch might later prevent LoopSimplify
248 // from transforming nested loops into simplified form. We will rely on
249 // later passes in backend to clean up empty blocks.
250 if (BI && BI->isUnconditional() &&
251 BB != &BB->getParent()->getEntryBlock() &&
252 // If the terminator is the only non-phi instruction, try to nuke it.
253 BB->getFirstNonPHIOrDbg()->isTerminator() && !LoopHeaders.count(BB) &&
254 !LoopHeaders.count(BI->getSuccessor(0))) {
255 // FIXME: It is always conservatively correct to drop the info
256 // for a block even if it doesn't get erased. This isn't totally
257 // awesome, but it allows us to use AssertingVH to prevent nasty
258 // dangling pointer issues within LazyValueInfo.
260 if (TryToSimplifyUncondBranchFromEmptyBlock(BB))
264 EverChanged |= Changed;
271 // Replace uses of Cond with ToVal when safe to do so. If all uses are
272 // replaced, we can remove Cond. We cannot blindly replace all uses of Cond
273 // because we may incorrectly replace uses when guards/assumes are uses of
274 // of `Cond` and we used the guards/assume to reason about the `Cond` value
275 // at the end of block. RAUW unconditionally replaces all uses
276 // including the guards/assumes themselves and the uses before the
278 static void ReplaceFoldableUses(Instruction *Cond, Value *ToVal) {
279 assert(Cond->getType() == ToVal->getType());
280 auto *BB = Cond->getParent();
281 // We can unconditionally replace all uses in non-local blocks (i.e. uses
282 // strictly dominated by BB), since LVI information is true from the
284 replaceNonLocalUsesWith(Cond, ToVal);
285 for (Instruction &I : reverse(*BB)) {
286 // Reached the Cond whose uses we are trying to replace, so there are no
290 // We only replace uses in instructions that are guaranteed to reach the end
291 // of BB, where we know Cond is ToVal.
292 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
294 I.replaceUsesOfWith(Cond, ToVal);
296 if (Cond->use_empty() && !Cond->mayHaveSideEffects())
297 Cond->eraseFromParent();
300 /// Return the cost of duplicating a piece of this block from first non-phi
301 /// and before StopAt instruction to thread across it. Stop scanning the block
302 /// when exceeding the threshold. If duplication is impossible, returns ~0U.
303 static unsigned getJumpThreadDuplicationCost(BasicBlock *BB,
305 unsigned Threshold) {
306 assert(StopAt->getParent() == BB && "Not an instruction from proper BB?");
307 /// Ignore PHI nodes, these will be flattened when duplication happens.
308 BasicBlock::const_iterator I(BB->getFirstNonPHI());
310 // FIXME: THREADING will delete values that are just used to compute the
311 // branch, so they shouldn't count against the duplication cost.
314 if (BB->getTerminator() == StopAt) {
315 // Threading through a switch statement is particularly profitable. If this
316 // block ends in a switch, decrease its cost to make it more likely to
318 if (isa<SwitchInst>(StopAt))
321 // The same holds for indirect branches, but slightly more so.
322 if (isa<IndirectBrInst>(StopAt))
326 // Bump the threshold up so the early exit from the loop doesn't skip the
327 // terminator-based Size adjustment at the end.
330 // Sum up the cost of each instruction until we get to the terminator. Don't
331 // include the terminator because the copy won't include it.
333 for (; &*I != StopAt; ++I) {
335 // Stop scanning the block if we've reached the threshold.
336 if (Size > Threshold)
339 // Debugger intrinsics don't incur code size.
340 if (isa<DbgInfoIntrinsic>(I)) continue;
342 // If this is a pointer->pointer bitcast, it is free.
343 if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
346 // Bail out if this instruction gives back a token type, it is not possible
347 // to duplicate it if it is used outside this BB.
348 if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
351 // All other instructions count for at least one unit.
354 // Calls are more expensive. If they are non-intrinsic calls, we model them
355 // as having cost of 4. If they are a non-vector intrinsic, we model them
356 // as having cost of 2 total, and if they are a vector intrinsic, we model
357 // them as having cost 1.
358 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
359 if (CI->cannotDuplicate() || CI->isConvergent())
360 // Blocks with NoDuplicate are modelled as having infinite cost, so they
361 // are never duplicated.
363 else if (!isa<IntrinsicInst>(CI))
365 else if (!CI->getType()->isVectorTy())
370 return Size > Bonus ? Size - Bonus : 0;
373 /// FindLoopHeaders - We do not want jump threading to turn proper loop
374 /// structures into irreducible loops. Doing this breaks up the loop nesting
375 /// hierarchy and pessimizes later transformations. To prevent this from
376 /// happening, we first have to find the loop headers. Here we approximate this
377 /// by finding targets of backedges in the CFG.
379 /// Note that there definitely are cases when we want to allow threading of
380 /// edges across a loop header. For example, threading a jump from outside the
381 /// loop (the preheader) to an exit block of the loop is definitely profitable.
382 /// It is also almost always profitable to thread backedges from within the loop
383 /// to exit blocks, and is often profitable to thread backedges to other blocks
384 /// within the loop (forming a nested loop). This simple analysis is not rich
385 /// enough to track all of these properties and keep it up-to-date as the CFG
386 /// mutates, so we don't allow any of these transformations.
388 void JumpThreadingPass::FindLoopHeaders(Function &F) {
389 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
390 FindFunctionBackedges(F, Edges);
392 for (const auto &Edge : Edges)
393 LoopHeaders.insert(Edge.second);
396 /// getKnownConstant - Helper method to determine if we can thread over a
397 /// terminator with the given value as its condition, and if so what value to
398 /// use for that. What kind of value this is depends on whether we want an
399 /// integer or a block address, but an undef is always accepted.
400 /// Returns null if Val is null or not an appropriate constant.
401 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
405 // Undef is "known" enough.
406 if (UndefValue *U = dyn_cast<UndefValue>(Val))
409 if (Preference == WantBlockAddress)
410 return dyn_cast<BlockAddress>(Val->stripPointerCasts());
412 return dyn_cast<ConstantInt>(Val);
415 /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
416 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
417 /// in any of our predecessors. If so, return the known list of value and pred
418 /// BB in the result vector.
420 /// This returns true if there were any known values.
422 bool JumpThreadingPass::ComputeValueKnownInPredecessors(
423 Value *V, BasicBlock *BB, PredValueInfo &Result,
424 ConstantPreference Preference, Instruction *CxtI) {
425 // This method walks up use-def chains recursively. Because of this, we could
426 // get into an infinite loop going around loops in the use-def chain. To
427 // prevent this, keep track of what (value, block) pairs we've already visited
428 // and terminate the search if we loop back to them
429 if (!RecursionSet.insert(std::make_pair(V, BB)).second)
432 // An RAII help to remove this pair from the recursion set once the recursion
433 // stack pops back out again.
434 RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
436 // If V is a constant, then it is known in all predecessors.
437 if (Constant *KC = getKnownConstant(V, Preference)) {
438 for (BasicBlock *Pred : predecessors(BB))
439 Result.push_back(std::make_pair(KC, Pred));
441 return !Result.empty();
444 // If V is a non-instruction value, or an instruction in a different block,
445 // then it can't be derived from a PHI.
446 Instruction *I = dyn_cast<Instruction>(V);
447 if (!I || I->getParent() != BB) {
449 // Okay, if this is a live-in value, see if it has a known value at the end
450 // of any of our predecessors.
452 // FIXME: This should be an edge property, not a block end property.
453 /// TODO: Per PR2563, we could infer value range information about a
454 /// predecessor based on its terminator.
456 // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
457 // "I" is a non-local compare-with-a-constant instruction. This would be
458 // able to handle value inequalities better, for example if the compare is
459 // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
460 // Perhaps getConstantOnEdge should be smart enough to do this?
462 for (BasicBlock *P : predecessors(BB)) {
463 // If the value is known by LazyValueInfo to be a constant in a
464 // predecessor, use that information to try to thread this block.
465 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
466 if (Constant *KC = getKnownConstant(PredCst, Preference))
467 Result.push_back(std::make_pair(KC, P));
470 return !Result.empty();
473 /// If I is a PHI node, then we know the incoming values for any constants.
474 if (PHINode *PN = dyn_cast<PHINode>(I)) {
475 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
476 Value *InVal = PN->getIncomingValue(i);
477 if (Constant *KC = getKnownConstant(InVal, Preference)) {
478 Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
480 Constant *CI = LVI->getConstantOnEdge(InVal,
481 PN->getIncomingBlock(i),
483 if (Constant *KC = getKnownConstant(CI, Preference))
484 Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
488 return !Result.empty();
491 // Handle Cast instructions. Only see through Cast when the source operand is
492 // PHI or Cmp and the source type is i1 to save the compilation time.
493 if (CastInst *CI = dyn_cast<CastInst>(I)) {
494 Value *Source = CI->getOperand(0);
495 if (!Source->getType()->isIntegerTy(1))
497 if (!isa<PHINode>(Source) && !isa<CmpInst>(Source))
499 ComputeValueKnownInPredecessors(Source, BB, Result, Preference, CxtI);
503 // Convert the known values.
504 for (auto &R : Result)
505 R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType());
510 PredValueInfoTy LHSVals, RHSVals;
512 // Handle some boolean conditions.
513 if (I->getType()->getPrimitiveSizeInBits() == 1) {
514 assert(Preference == WantInteger && "One-bit non-integer type?");
516 // X & false -> false
517 if (I->getOpcode() == Instruction::Or ||
518 I->getOpcode() == Instruction::And) {
519 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
521 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals,
524 if (LHSVals.empty() && RHSVals.empty())
527 ConstantInt *InterestingVal;
528 if (I->getOpcode() == Instruction::Or)
529 InterestingVal = ConstantInt::getTrue(I->getContext());
531 InterestingVal = ConstantInt::getFalse(I->getContext());
533 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
535 // Scan for the sentinel. If we find an undef, force it to the
536 // interesting value: x|undef -> true and x&undef -> false.
537 for (const auto &LHSVal : LHSVals)
538 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
539 Result.emplace_back(InterestingVal, LHSVal.second);
540 LHSKnownBBs.insert(LHSVal.second);
542 for (const auto &RHSVal : RHSVals)
543 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
544 // If we already inferred a value for this block on the LHS, don't
546 if (!LHSKnownBBs.count(RHSVal.second))
547 Result.emplace_back(InterestingVal, RHSVal.second);
550 return !Result.empty();
553 // Handle the NOT form of XOR.
554 if (I->getOpcode() == Instruction::Xor &&
555 isa<ConstantInt>(I->getOperand(1)) &&
556 cast<ConstantInt>(I->getOperand(1))->isOne()) {
557 ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result,
562 // Invert the known values.
563 for (auto &R : Result)
564 R.first = ConstantExpr::getNot(R.first);
569 // Try to simplify some other binary operator values.
570 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
571 assert(Preference != WantBlockAddress
572 && "A binary operator creating a block address?");
573 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
574 PredValueInfoTy LHSVals;
575 ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
578 // Try to use constant folding to simplify the binary operator.
579 for (const auto &LHSVal : LHSVals) {
580 Constant *V = LHSVal.first;
581 Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
583 if (Constant *KC = getKnownConstant(Folded, WantInteger))
584 Result.push_back(std::make_pair(KC, LHSVal.second));
588 return !Result.empty();
591 // Handle compare with phi operand, where the PHI is defined in this block.
592 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
593 assert(Preference == WantInteger && "Compares only produce integers");
594 Type *CmpType = Cmp->getType();
595 Value *CmpLHS = Cmp->getOperand(0);
596 Value *CmpRHS = Cmp->getOperand(1);
597 CmpInst::Predicate Pred = Cmp->getPredicate();
599 PHINode *PN = dyn_cast<PHINode>(CmpLHS);
600 if (PN && PN->getParent() == BB) {
601 const DataLayout &DL = PN->getModule()->getDataLayout();
602 // We can do this simplification if any comparisons fold to true or false.
604 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
605 BasicBlock *PredBB = PN->getIncomingBlock(i);
606 Value *LHS = PN->getIncomingValue(i);
607 Value *RHS = CmpRHS->DoPHITranslation(BB, PredBB);
609 Value *Res = SimplifyCmpInst(Pred, LHS, RHS, {DL});
611 if (!isa<Constant>(RHS))
614 LazyValueInfo::Tristate
615 ResT = LVI->getPredicateOnEdge(Pred, LHS,
616 cast<Constant>(RHS), PredBB, BB,
618 if (ResT == LazyValueInfo::Unknown)
620 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
623 if (Constant *KC = getKnownConstant(Res, WantInteger))
624 Result.push_back(std::make_pair(KC, PredBB));
627 return !Result.empty();
630 // If comparing a live-in value against a constant, see if we know the
631 // live-in value on any predecessors.
632 if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) {
633 Constant *CmpConst = cast<Constant>(CmpRHS);
635 if (!isa<Instruction>(CmpLHS) ||
636 cast<Instruction>(CmpLHS)->getParent() != BB) {
637 for (BasicBlock *P : predecessors(BB)) {
638 // If the value is known by LazyValueInfo to be a constant in a
639 // predecessor, use that information to try to thread this block.
640 LazyValueInfo::Tristate Res =
641 LVI->getPredicateOnEdge(Pred, CmpLHS,
642 CmpConst, P, BB, CxtI ? CxtI : Cmp);
643 if (Res == LazyValueInfo::Unknown)
646 Constant *ResC = ConstantInt::get(CmpType, Res);
647 Result.push_back(std::make_pair(ResC, P));
650 return !Result.empty();
653 // InstCombine can fold some forms of constant range checks into
654 // (icmp (add (x, C1)), C2). See if we have we have such a thing with
657 using namespace PatternMatch;
659 ConstantInt *AddConst;
660 if (isa<ConstantInt>(CmpConst) &&
661 match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) {
662 if (!isa<Instruction>(AddLHS) ||
663 cast<Instruction>(AddLHS)->getParent() != BB) {
664 for (BasicBlock *P : predecessors(BB)) {
665 // If the value is known by LazyValueInfo to be a ConstantRange in
666 // a predecessor, use that information to try to thread this
668 ConstantRange CR = LVI->getConstantRangeOnEdge(
669 AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
670 // Propagate the range through the addition.
671 CR = CR.add(AddConst->getValue());
673 // Get the range where the compare returns true.
674 ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(
675 Pred, cast<ConstantInt>(CmpConst)->getValue());
678 if (CmpRange.contains(CR))
679 ResC = ConstantInt::getTrue(CmpType);
680 else if (CmpRange.inverse().contains(CR))
681 ResC = ConstantInt::getFalse(CmpType);
685 Result.push_back(std::make_pair(ResC, P));
688 return !Result.empty();
693 // Try to find a constant value for the LHS of a comparison,
694 // and evaluate it statically if we can.
695 PredValueInfoTy LHSVals;
696 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
699 for (const auto &LHSVal : LHSVals) {
700 Constant *V = LHSVal.first;
701 Constant *Folded = ConstantExpr::getCompare(Pred, V, CmpConst);
702 if (Constant *KC = getKnownConstant(Folded, WantInteger))
703 Result.push_back(std::make_pair(KC, LHSVal.second));
706 return !Result.empty();
710 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
711 // Handle select instructions where at least one operand is a known constant
712 // and we can figure out the condition value for any predecessor block.
713 Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
714 Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
715 PredValueInfoTy Conds;
716 if ((TrueVal || FalseVal) &&
717 ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds,
718 WantInteger, CxtI)) {
719 for (auto &C : Conds) {
720 Constant *Cond = C.first;
722 // Figure out what value to use for the condition.
724 if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
726 KnownCond = CI->isOne();
728 assert(isa<UndefValue>(Cond) && "Unexpected condition value");
729 // Either operand will do, so be sure to pick the one that's a known
731 // FIXME: Do this more cleverly if both values are known constants?
732 KnownCond = (TrueVal != nullptr);
735 // See if the select has a known constant value for this predecessor.
736 if (Constant *Val = KnownCond ? TrueVal : FalseVal)
737 Result.push_back(std::make_pair(Val, C.second));
740 return !Result.empty();
744 // If all else fails, see if LVI can figure out a constant value for us.
745 Constant *CI = LVI->getConstant(V, BB, CxtI);
746 if (Constant *KC = getKnownConstant(CI, Preference)) {
747 for (BasicBlock *Pred : predecessors(BB))
748 Result.push_back(std::make_pair(KC, Pred));
751 return !Result.empty();
756 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
757 /// in an undefined jump, decide which block is best to revector to.
759 /// Since we can pick an arbitrary destination, we pick the successor with the
760 /// fewest predecessors. This should reduce the in-degree of the others.
762 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
763 TerminatorInst *BBTerm = BB->getTerminator();
764 unsigned MinSucc = 0;
765 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
766 // Compute the successor with the minimum number of predecessors.
767 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
768 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
769 TestBB = BBTerm->getSuccessor(i);
770 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
771 if (NumPreds < MinNumPreds) {
773 MinNumPreds = NumPreds;
780 static bool hasAddressTakenAndUsed(BasicBlock *BB) {
781 if (!BB->hasAddressTaken()) return false;
783 // If the block has its address taken, it may be a tree of dead constants
784 // hanging off of it. These shouldn't keep the block alive.
785 BlockAddress *BA = BlockAddress::get(BB);
786 BA->removeDeadConstantUsers();
787 return !BA->use_empty();
790 /// ProcessBlock - If there are any predecessors whose control can be threaded
791 /// through to a successor, transform them now.
792 bool JumpThreadingPass::ProcessBlock(BasicBlock *BB) {
793 // If the block is trivially dead, just return and let the caller nuke it.
794 // This simplifies other transformations.
795 if (pred_empty(BB) &&
796 BB != &BB->getParent()->getEntryBlock())
799 // If this block has a single predecessor, and if that pred has a single
800 // successor, merge the blocks. This encourages recursive jump threading
801 // because now the condition in this block can be threaded through
802 // predecessors of our predecessor block.
803 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
804 const TerminatorInst *TI = SinglePred->getTerminator();
805 if (!TI->isExceptional() && TI->getNumSuccessors() == 1 &&
806 SinglePred != BB && !hasAddressTakenAndUsed(BB)) {
807 // If SinglePred was a loop header, BB becomes one.
808 if (LoopHeaders.erase(SinglePred))
809 LoopHeaders.insert(BB);
811 LVI->eraseBlock(SinglePred);
812 MergeBasicBlockIntoOnlyPred(BB);
814 // Now that BB is merged into SinglePred (i.e. SinglePred Code followed by
815 // BB code within one basic block `BB`), we need to invalidate the LVI
816 // information associated with BB, because the LVI information need not be
817 // true for all of BB after the merge. For example,
818 // Before the merge, LVI info and code is as follows:
819 // SinglePred: <LVI info1 for %p val>
821 // call @exit() // need not transfer execution to successor.
822 // assume(%p) // from this point on %p is true
824 // BB: <LVI info2 for %p val, i.e. %p is true>
828 // Note that this LVI info for blocks BB and SinglPred is correct for %p
829 // (info2 and info1 respectively). After the merge and the deletion of the
830 // LVI info1 for SinglePred. We have the following code:
831 // BB: <LVI info2 for %p val>
835 // %x = use of %p <-- LVI info2 is correct from here onwards.
837 // LVI info2 for BB is incorrect at the beginning of BB.
839 // Invalidate LVI information for BB if the LVI is not provably true for
841 if (any_of(*BB, [](Instruction &I) {
842 return !isGuaranteedToTransferExecutionToSuccessor(&I);
849 if (TryToUnfoldSelectInCurrBB(BB))
852 // Look if we can propagate guards to predecessors.
853 if (HasGuards && ProcessGuards(BB))
856 // What kind of constant we're looking for.
857 ConstantPreference Preference = WantInteger;
859 // Look to see if the terminator is a conditional branch, switch or indirect
860 // branch, if not we can't thread it.
862 Instruction *Terminator = BB->getTerminator();
863 if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
864 // Can't thread an unconditional jump.
865 if (BI->isUnconditional()) return false;
866 Condition = BI->getCondition();
867 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
868 Condition = SI->getCondition();
869 } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
870 // Can't thread indirect branch with no successors.
871 if (IB->getNumSuccessors() == 0) return false;
872 Condition = IB->getAddress()->stripPointerCasts();
873 Preference = WantBlockAddress;
875 return false; // Must be an invoke.
878 // Run constant folding to see if we can reduce the condition to a simple
880 if (Instruction *I = dyn_cast<Instruction>(Condition)) {
882 ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
884 I->replaceAllUsesWith(SimpleVal);
885 if (isInstructionTriviallyDead(I, TLI))
886 I->eraseFromParent();
887 Condition = SimpleVal;
891 // If the terminator is branching on an undef, we can pick any of the
892 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
893 if (isa<UndefValue>(Condition)) {
894 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
896 // Fold the branch/switch.
897 TerminatorInst *BBTerm = BB->getTerminator();
898 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
899 if (i == BestSucc) continue;
900 BBTerm->getSuccessor(i)->removePredecessor(BB, true);
903 DEBUG(dbgs() << " In block '" << BB->getName()
904 << "' folding undef terminator: " << *BBTerm << '\n');
905 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
906 BBTerm->eraseFromParent();
910 // If the terminator of this block is branching on a constant, simplify the
911 // terminator to an unconditional branch. This can occur due to threading in
913 if (getKnownConstant(Condition, Preference)) {
914 DEBUG(dbgs() << " In block '" << BB->getName()
915 << "' folding terminator: " << *BB->getTerminator() << '\n');
917 ConstantFoldTerminator(BB, true);
921 Instruction *CondInst = dyn_cast<Instruction>(Condition);
923 // All the rest of our checks depend on the condition being an instruction.
925 // FIXME: Unify this with code below.
926 if (ProcessThreadableEdges(Condition, BB, Preference, Terminator))
931 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
932 // If we're branching on a conditional, LVI might be able to determine
933 // it's value at the branch instruction. We only handle comparisons
934 // against a constant at this time.
935 // TODO: This should be extended to handle switches as well.
936 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
937 Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
938 if (CondBr && CondConst) {
939 // We should have returned as soon as we turn a conditional branch to
940 // unconditional. Because its no longer interesting as far as jump
941 // threading is concerned.
942 assert(CondBr->isConditional() && "Threading on unconditional terminator");
944 LazyValueInfo::Tristate Ret =
945 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
947 if (Ret != LazyValueInfo::Unknown) {
948 unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0;
949 unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1;
950 CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
951 BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
952 CondBr->eraseFromParent();
953 if (CondCmp->use_empty())
954 CondCmp->eraseFromParent();
955 // We can safely replace *some* uses of the CondInst if it has
956 // exactly one value as returned by LVI. RAUW is incorrect in the
957 // presence of guards and assumes, that have the `Cond` as the use. This
958 // is because we use the guards/assume to reason about the `Cond` value
959 // at the end of block, but RAUW unconditionally replaces all uses
960 // including the guards/assumes themselves and the uses before the
962 else if (CondCmp->getParent() == BB) {
963 auto *CI = Ret == LazyValueInfo::True ?
964 ConstantInt::getTrue(CondCmp->getType()) :
965 ConstantInt::getFalse(CondCmp->getType());
966 ReplaceFoldableUses(CondCmp, CI);
971 // We did not manage to simplify this branch, try to see whether
972 // CondCmp depends on a known phi-select pattern.
973 if (TryToUnfoldSelect(CondCmp, BB))
978 // Check for some cases that are worth simplifying. Right now we want to look
979 // for loads that are used by a switch or by the condition for the branch. If
980 // we see one, check to see if it's partially redundant. If so, insert a PHI
981 // which can then be used to thread the values.
983 Value *SimplifyValue = CondInst;
984 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
985 if (isa<Constant>(CondCmp->getOperand(1)))
986 SimplifyValue = CondCmp->getOperand(0);
988 // TODO: There are other places where load PRE would be profitable, such as
989 // more complex comparisons.
990 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
991 if (SimplifyPartiallyRedundantLoad(LI))
994 // Handle a variety of cases where we are branching on something derived from
995 // a PHI node in the current block. If we can prove that any predecessors
996 // compute a predictable value based on a PHI node, thread those predecessors.
998 if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
1001 // If this is an otherwise-unfoldable branch on a phi node in the current
1002 // block, see if we can simplify.
1003 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
1004 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1005 return ProcessBranchOnPHI(PN);
1007 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
1008 if (CondInst->getOpcode() == Instruction::Xor &&
1009 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1010 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
1012 // Search for a stronger dominating condition that can be used to simplify a
1013 // conditional branch leaving BB.
1014 if (ProcessImpliedCondition(BB))
1020 bool JumpThreadingPass::ProcessImpliedCondition(BasicBlock *BB) {
1021 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
1022 if (!BI || !BI->isConditional())
1025 Value *Cond = BI->getCondition();
1026 BasicBlock *CurrentBB = BB;
1027 BasicBlock *CurrentPred = BB->getSinglePredecessor();
1030 auto &DL = BB->getModule()->getDataLayout();
1032 while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
1033 auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
1034 if (!PBI || !PBI->isConditional())
1036 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1039 bool FalseDest = PBI->getSuccessor(1) == CurrentBB;
1040 Optional<bool> Implication =
1041 isImpliedCondition(PBI->getCondition(), Cond, DL, FalseDest);
1043 BI->getSuccessor(*Implication ? 1 : 0)->removePredecessor(BB);
1044 BranchInst::Create(BI->getSuccessor(*Implication ? 0 : 1), BI);
1045 BI->eraseFromParent();
1048 CurrentBB = CurrentPred;
1049 CurrentPred = CurrentBB->getSinglePredecessor();
1055 /// Return true if Op is an instruction defined in the given block.
1056 static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
1057 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1058 if (OpInst->getParent() == BB)
1063 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
1064 /// load instruction, eliminate it by replacing it with a PHI node. This is an
1065 /// important optimization that encourages jump threading, and needs to be run
1066 /// interlaced with other jump threading tasks.
1067 bool JumpThreadingPass::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
1068 // Don't hack volatile and ordered loads.
1069 if (!LI->isUnordered()) return false;
1071 // If the load is defined in a block with exactly one predecessor, it can't be
1072 // partially redundant.
1073 BasicBlock *LoadBB = LI->getParent();
1074 if (LoadBB->getSinglePredecessor())
1077 // If the load is defined in an EH pad, it can't be partially redundant,
1078 // because the edges between the invoke and the EH pad cannot have other
1079 // instructions between them.
1080 if (LoadBB->isEHPad())
1083 Value *LoadedPtr = LI->getOperand(0);
1085 // If the loaded operand is defined in the LoadBB and its not a phi,
1086 // it can't be available in predecessors.
1087 if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr))
1090 // Scan a few instructions up from the load, to see if it is obviously live at
1091 // the entry to its block.
1092 BasicBlock::iterator BBIt(LI);
1094 if (Value *AvailableVal = FindAvailableLoadedValue(
1095 LI, LoadBB, BBIt, DefMaxInstsToScan, AA, &IsLoadCSE)) {
1096 // If the value of the load is locally available within the block, just use
1097 // it. This frequently occurs for reg2mem'd allocas.
1100 LoadInst *NLI = cast<LoadInst>(AvailableVal);
1101 combineMetadataForCSE(NLI, LI);
1104 // If the returned value is the load itself, replace with an undef. This can
1105 // only happen in dead loops.
1106 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
1107 if (AvailableVal->getType() != LI->getType())
1109 CastInst::CreateBitOrPointerCast(AvailableVal, LI->getType(), "", LI);
1110 LI->replaceAllUsesWith(AvailableVal);
1111 LI->eraseFromParent();
1115 // Otherwise, if we scanned the whole block and got to the top of the block,
1116 // we know the block is locally transparent to the load. If not, something
1117 // might clobber its value.
1118 if (BBIt != LoadBB->begin())
1121 // If all of the loads and stores that feed the value have the same AA tags,
1122 // then we can propagate them onto any newly inserted loads.
1124 LI->getAAMetadata(AATags);
1126 SmallPtrSet<BasicBlock*, 8> PredsScanned;
1127 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
1128 AvailablePredsTy AvailablePreds;
1129 BasicBlock *OneUnavailablePred = nullptr;
1130 SmallVector<LoadInst*, 8> CSELoads;
1132 // If we got here, the loaded value is transparent through to the start of the
1133 // block. Check to see if it is available in any of the predecessor blocks.
1134 for (BasicBlock *PredBB : predecessors(LoadBB)) {
1135 // If we already scanned this predecessor, skip it.
1136 if (!PredsScanned.insert(PredBB).second)
1139 BBIt = PredBB->end();
1140 unsigned NumScanedInst = 0;
1141 Value *PredAvailable = nullptr;
1142 // NOTE: We don't CSE load that is volatile or anything stronger than
1143 // unordered, that should have been checked when we entered the function.
1144 assert(LI->isUnordered() && "Attempting to CSE volatile or atomic loads");
1145 // If this is a load on a phi pointer, phi-translate it and search
1146 // for available load/store to the pointer in predecessors.
1147 Value *Ptr = LoadedPtr->DoPHITranslation(LoadBB, PredBB);
1148 PredAvailable = FindAvailablePtrLoadStore(
1149 Ptr, LI->getType(), LI->isAtomic(), PredBB, BBIt, DefMaxInstsToScan,
1150 AA, &IsLoadCSE, &NumScanedInst);
1152 // If PredBB has a single predecessor, continue scanning through the
1153 // single precessor.
1154 BasicBlock *SinglePredBB = PredBB;
1155 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
1156 NumScanedInst < DefMaxInstsToScan) {
1157 SinglePredBB = SinglePredBB->getSinglePredecessor();
1159 BBIt = SinglePredBB->end();
1160 PredAvailable = FindAvailablePtrLoadStore(
1161 Ptr, LI->getType(), LI->isAtomic(), SinglePredBB, BBIt,
1162 (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
1167 if (!PredAvailable) {
1168 OneUnavailablePred = PredBB;
1173 CSELoads.push_back(cast<LoadInst>(PredAvailable));
1175 // If so, this load is partially redundant. Remember this info so that we
1176 // can create a PHI node.
1177 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
1180 // If the loaded value isn't available in any predecessor, it isn't partially
1182 if (AvailablePreds.empty()) return false;
1184 // Okay, the loaded value is available in at least one (and maybe all!)
1185 // predecessors. If the value is unavailable in more than one unique
1186 // predecessor, we want to insert a merge block for those common predecessors.
1187 // This ensures that we only have to insert one reload, thus not increasing
1189 BasicBlock *UnavailablePred = nullptr;
1191 // If there is exactly one predecessor where the value is unavailable, the
1192 // already computed 'OneUnavailablePred' block is it. If it ends in an
1193 // unconditional branch, we know that it isn't a critical edge.
1194 if (PredsScanned.size() == AvailablePreds.size()+1 &&
1195 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
1196 UnavailablePred = OneUnavailablePred;
1197 } else if (PredsScanned.size() != AvailablePreds.size()) {
1198 // Otherwise, we had multiple unavailable predecessors or we had a critical
1199 // edge from the one.
1200 SmallVector<BasicBlock*, 8> PredsToSplit;
1201 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
1203 for (const auto &AvailablePred : AvailablePreds)
1204 AvailablePredSet.insert(AvailablePred.first);
1206 // Add all the unavailable predecessors to the PredsToSplit list.
1207 for (BasicBlock *P : predecessors(LoadBB)) {
1208 // If the predecessor is an indirect goto, we can't split the edge.
1209 if (isa<IndirectBrInst>(P->getTerminator()))
1212 if (!AvailablePredSet.count(P))
1213 PredsToSplit.push_back(P);
1216 // Split them out to their own block.
1217 UnavailablePred = SplitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
1220 // If the value isn't available in all predecessors, then there will be
1221 // exactly one where it isn't available. Insert a load on that edge and add
1222 // it to the AvailablePreds list.
1223 if (UnavailablePred) {
1224 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
1225 "Can't handle critical edge here!");
1226 LoadInst *NewVal = new LoadInst(
1227 LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred),
1228 LI->getName() + ".pr", false, LI->getAlignment(), LI->getOrdering(),
1229 LI->getSyncScopeID(), UnavailablePred->getTerminator());
1230 NewVal->setDebugLoc(LI->getDebugLoc());
1232 NewVal->setAAMetadata(AATags);
1234 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
1237 // Now we know that each predecessor of this block has a value in
1238 // AvailablePreds, sort them for efficient access as we're walking the preds.
1239 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
1241 // Create a PHI node at the start of the block for the PRE'd load value.
1242 pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
1243 PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
1246 PN->setDebugLoc(LI->getDebugLoc());
1248 // Insert new entries into the PHI for each predecessor. A single block may
1249 // have multiple entries here.
1250 for (pred_iterator PI = PB; PI != PE; ++PI) {
1251 BasicBlock *P = *PI;
1252 AvailablePredsTy::iterator I =
1253 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
1254 std::make_pair(P, (Value*)nullptr));
1256 assert(I != AvailablePreds.end() && I->first == P &&
1257 "Didn't find entry for predecessor!");
1259 // If we have an available predecessor but it requires casting, insert the
1260 // cast in the predecessor and use the cast. Note that we have to update the
1261 // AvailablePreds vector as we go so that all of the PHI entries for this
1262 // predecessor use the same bitcast.
1263 Value *&PredV = I->second;
1264 if (PredV->getType() != LI->getType())
1265 PredV = CastInst::CreateBitOrPointerCast(PredV, LI->getType(), "",
1266 P->getTerminator());
1268 PN->addIncoming(PredV, I->first);
1271 for (LoadInst *PredLI : CSELoads) {
1272 combineMetadataForCSE(PredLI, LI);
1275 LI->replaceAllUsesWith(PN);
1276 LI->eraseFromParent();
1281 /// FindMostPopularDest - The specified list contains multiple possible
1282 /// threadable destinations. Pick the one that occurs the most frequently in
1285 FindMostPopularDest(BasicBlock *BB,
1286 const SmallVectorImpl<std::pair<BasicBlock*,
1287 BasicBlock*> > &PredToDestList) {
1288 assert(!PredToDestList.empty());
1290 // Determine popularity. If there are multiple possible destinations, we
1291 // explicitly choose to ignore 'undef' destinations. We prefer to thread
1292 // blocks with known and real destinations to threading undef. We'll handle
1293 // them later if interesting.
1294 DenseMap<BasicBlock*, unsigned> DestPopularity;
1295 for (const auto &PredToDest : PredToDestList)
1296 if (PredToDest.second)
1297 DestPopularity[PredToDest.second]++;
1299 // Find the most popular dest.
1300 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
1301 BasicBlock *MostPopularDest = DPI->first;
1302 unsigned Popularity = DPI->second;
1303 SmallVector<BasicBlock*, 4> SamePopularity;
1305 for (++DPI; DPI != DestPopularity.end(); ++DPI) {
1306 // If the popularity of this entry isn't higher than the popularity we've
1307 // seen so far, ignore it.
1308 if (DPI->second < Popularity)
1310 else if (DPI->second == Popularity) {
1311 // If it is the same as what we've seen so far, keep track of it.
1312 SamePopularity.push_back(DPI->first);
1314 // If it is more popular, remember it.
1315 SamePopularity.clear();
1316 MostPopularDest = DPI->first;
1317 Popularity = DPI->second;
1321 // Okay, now we know the most popular destination. If there is more than one
1322 // destination, we need to determine one. This is arbitrary, but we need
1323 // to make a deterministic decision. Pick the first one that appears in the
1325 if (!SamePopularity.empty()) {
1326 SamePopularity.push_back(MostPopularDest);
1327 TerminatorInst *TI = BB->getTerminator();
1328 for (unsigned i = 0; ; ++i) {
1329 assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
1331 if (!is_contained(SamePopularity, TI->getSuccessor(i)))
1334 MostPopularDest = TI->getSuccessor(i);
1339 // Okay, we have finally picked the most popular destination.
1340 return MostPopularDest;
1343 bool JumpThreadingPass::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
1344 ConstantPreference Preference,
1345 Instruction *CxtI) {
1346 // If threading this would thread across a loop header, don't even try to
1348 if (LoopHeaders.count(BB))
1351 PredValueInfoTy PredValues;
1352 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI))
1355 assert(!PredValues.empty() &&
1356 "ComputeValueKnownInPredecessors returned true with no values");
1358 DEBUG(dbgs() << "IN BB: " << *BB;
1359 for (const auto &PredValue : PredValues) {
1360 dbgs() << " BB '" << BB->getName() << "': FOUND condition = "
1362 << " for pred '" << PredValue.second->getName() << "'.\n";
1365 // Decide what we want to thread through. Convert our list of known values to
1366 // a list of known destinations for each pred. This also discards duplicate
1367 // predecessors and keeps track of the undefined inputs (which are represented
1368 // as a null dest in the PredToDestList).
1369 SmallPtrSet<BasicBlock*, 16> SeenPreds;
1370 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1372 BasicBlock *OnlyDest = nullptr;
1373 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1374 Constant *OnlyVal = nullptr;
1375 Constant *MultipleVal = (Constant *)(intptr_t)~0ULL;
1377 unsigned PredWithKnownDest = 0;
1378 for (const auto &PredValue : PredValues) {
1379 BasicBlock *Pred = PredValue.second;
1380 if (!SeenPreds.insert(Pred).second)
1381 continue; // Duplicate predecessor entry.
1383 Constant *Val = PredValue.first;
1386 if (isa<UndefValue>(Val))
1388 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1389 assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1390 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
1391 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1392 assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1393 DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
1395 assert(isa<IndirectBrInst>(BB->getTerminator())
1396 && "Unexpected terminator");
1397 assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress");
1398 DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1401 // If we have exactly one destination, remember it for efficiency below.
1402 if (PredToDestList.empty()) {
1406 if (OnlyDest != DestBB)
1407 OnlyDest = MultipleDestSentinel;
1408 // It possible we have same destination, but different value, e.g. default
1409 // case in switchinst.
1411 OnlyVal = MultipleVal;
1414 // We know where this predecessor is going.
1415 ++PredWithKnownDest;
1417 // If the predecessor ends with an indirect goto, we can't change its
1419 if (isa<IndirectBrInst>(Pred->getTerminator()))
1422 PredToDestList.push_back(std::make_pair(Pred, DestBB));
1425 // If all edges were unthreadable, we fail.
1426 if (PredToDestList.empty())
1429 // If all the predecessors go to a single known successor, we want to fold,
1430 // not thread. By doing so, we do not need to duplicate the current block and
1431 // also miss potential opportunities in case we dont/cant duplicate.
1432 if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1433 if (PredWithKnownDest ==
1434 (size_t)std::distance(pred_begin(BB), pred_end(BB))) {
1435 bool SeenFirstBranchToOnlyDest = false;
1436 for (BasicBlock *SuccBB : successors(BB)) {
1437 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest)
1438 SeenFirstBranchToOnlyDest = true; // Don't modify the first branch.
1440 SuccBB->removePredecessor(BB, true); // This is unreachable successor.
1443 // Finally update the terminator.
1444 TerminatorInst *Term = BB->getTerminator();
1445 BranchInst::Create(OnlyDest, Term);
1446 Term->eraseFromParent();
1448 // If the condition is now dead due to the removal of the old terminator,
1450 if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
1451 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
1452 CondInst->eraseFromParent();
1453 // We can safely replace *some* uses of the CondInst if it has
1454 // exactly one value as returned by LVI. RAUW is incorrect in the
1455 // presence of guards and assumes, that have the `Cond` as the use. This
1456 // is because we use the guards/assume to reason about the `Cond` value
1457 // at the end of block, but RAUW unconditionally replaces all uses
1458 // including the guards/assumes themselves and the uses before the
1460 else if (OnlyVal && OnlyVal != MultipleVal &&
1461 CondInst->getParent() == BB)
1462 ReplaceFoldableUses(CondInst, OnlyVal);
1468 // Determine which is the most common successor. If we have many inputs and
1469 // this block is a switch, we want to start by threading the batch that goes
1470 // to the most popular destination first. If we only know about one
1471 // threadable destination (the common case) we can avoid this.
1472 BasicBlock *MostPopularDest = OnlyDest;
1474 if (MostPopularDest == MultipleDestSentinel)
1475 MostPopularDest = FindMostPopularDest(BB, PredToDestList);
1477 // Now that we know what the most popular destination is, factor all
1478 // predecessors that will jump to it into a single predecessor.
1479 SmallVector<BasicBlock*, 16> PredsToFactor;
1480 for (const auto &PredToDest : PredToDestList)
1481 if (PredToDest.second == MostPopularDest) {
1482 BasicBlock *Pred = PredToDest.first;
1484 // This predecessor may be a switch or something else that has multiple
1485 // edges to the block. Factor each of these edges by listing them
1486 // according to # occurrences in PredsToFactor.
1487 for (BasicBlock *Succ : successors(Pred))
1489 PredsToFactor.push_back(Pred);
1492 // If the threadable edges are branching on an undefined value, we get to pick
1493 // the destination that these predecessors should get to.
1494 if (!MostPopularDest)
1495 MostPopularDest = BB->getTerminator()->
1496 getSuccessor(GetBestDestForJumpOnUndef(BB));
1498 // Ok, try to thread it!
1499 return ThreadEdge(BB, PredsToFactor, MostPopularDest);
1502 /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
1503 /// a PHI node in the current block. See if there are any simplifications we
1504 /// can do based on inputs to the phi node.
1506 bool JumpThreadingPass::ProcessBranchOnPHI(PHINode *PN) {
1507 BasicBlock *BB = PN->getParent();
1509 // TODO: We could make use of this to do it once for blocks with common PHI
1511 SmallVector<BasicBlock*, 1> PredBBs;
1514 // If any of the predecessor blocks end in an unconditional branch, we can
1515 // *duplicate* the conditional branch into that block in order to further
1516 // encourage jump threading and to eliminate cases where we have branch on a
1517 // phi of an icmp (branch on icmp is much better).
1518 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1519 BasicBlock *PredBB = PN->getIncomingBlock(i);
1520 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1521 if (PredBr->isUnconditional()) {
1522 PredBBs[0] = PredBB;
1523 // Try to duplicate BB into PredBB.
1524 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1532 /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
1533 /// a xor instruction in the current block. See if there are any
1534 /// simplifications we can do based on inputs to the xor.
1536 bool JumpThreadingPass::ProcessBranchOnXOR(BinaryOperator *BO) {
1537 BasicBlock *BB = BO->getParent();
1539 // If either the LHS or RHS of the xor is a constant, don't do this
1541 if (isa<ConstantInt>(BO->getOperand(0)) ||
1542 isa<ConstantInt>(BO->getOperand(1)))
1545 // If the first instruction in BB isn't a phi, we won't be able to infer
1546 // anything special about any particular predecessor.
1547 if (!isa<PHINode>(BB->front()))
1550 // If this BB is a landing pad, we won't be able to split the edge into it.
1554 // If we have a xor as the branch input to this block, and we know that the
1555 // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1556 // the condition into the predecessor and fix that value to true, saving some
1557 // logical ops on that path and encouraging other paths to simplify.
1559 // This copies something like this:
1562 // %X = phi i1 [1], [%X']
1563 // %Y = icmp eq i32 %A, %B
1564 // %Z = xor i1 %X, %Y
1569 // %Y = icmp ne i32 %A, %B
1572 PredValueInfoTy XorOpValues;
1574 if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
1576 assert(XorOpValues.empty());
1577 if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
1583 assert(!XorOpValues.empty() &&
1584 "ComputeValueKnownInPredecessors returned true with no values");
1586 // Scan the information to see which is most popular: true or false. The
1587 // predecessors can be of the set true, false, or undef.
1588 unsigned NumTrue = 0, NumFalse = 0;
1589 for (const auto &XorOpValue : XorOpValues) {
1590 if (isa<UndefValue>(XorOpValue.first))
1591 // Ignore undefs for the count.
1593 if (cast<ConstantInt>(XorOpValue.first)->isZero())
1599 // Determine which value to split on, true, false, or undef if neither.
1600 ConstantInt *SplitVal = nullptr;
1601 if (NumTrue > NumFalse)
1602 SplitVal = ConstantInt::getTrue(BB->getContext());
1603 else if (NumTrue != 0 || NumFalse != 0)
1604 SplitVal = ConstantInt::getFalse(BB->getContext());
1606 // Collect all of the blocks that this can be folded into so that we can
1607 // factor this once and clone it once.
1608 SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1609 for (const auto &XorOpValue : XorOpValues) {
1610 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1613 BlocksToFoldInto.push_back(XorOpValue.second);
1616 // If we inferred a value for all of the predecessors, then duplication won't
1617 // help us. However, we can just replace the LHS or RHS with the constant.
1618 if (BlocksToFoldInto.size() ==
1619 cast<PHINode>(BB->front()).getNumIncomingValues()) {
1621 // If all preds provide undef, just nuke the xor, because it is undef too.
1622 BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1623 BO->eraseFromParent();
1624 } else if (SplitVal->isZero()) {
1625 // If all preds provide 0, replace the xor with the other input.
1626 BO->replaceAllUsesWith(BO->getOperand(isLHS));
1627 BO->eraseFromParent();
1629 // If all preds provide 1, set the computed value to 1.
1630 BO->setOperand(!isLHS, SplitVal);
1636 // Try to duplicate BB into PredBB.
1637 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1641 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1642 /// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1643 /// NewPred using the entries from OldPred (suitably mapped).
1644 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1645 BasicBlock *OldPred,
1646 BasicBlock *NewPred,
1647 DenseMap<Instruction*, Value*> &ValueMap) {
1648 for (BasicBlock::iterator PNI = PHIBB->begin();
1649 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1650 // Ok, we have a PHI node. Figure out what the incoming value was for the
1652 Value *IV = PN->getIncomingValueForBlock(OldPred);
1654 // Remap the value if necessary.
1655 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1656 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1657 if (I != ValueMap.end())
1661 PN->addIncoming(IV, NewPred);
1665 /// ThreadEdge - We have decided that it is safe and profitable to factor the
1666 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
1667 /// across BB. Transform the IR to reflect this change.
1668 bool JumpThreadingPass::ThreadEdge(BasicBlock *BB,
1669 const SmallVectorImpl<BasicBlock *> &PredBBs,
1670 BasicBlock *SuccBB) {
1671 // If threading to the same block as we come from, we would infinite loop.
1673 DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
1674 << "' - would thread to self!\n");
1678 // If threading this would thread across a loop header, don't thread the edge.
1679 // See the comments above FindLoopHeaders for justifications and caveats.
1680 if (LoopHeaders.count(BB)) {
1681 DEBUG(dbgs() << " Not threading across loop header BB '" << BB->getName()
1682 << "' to dest BB '" << SuccBB->getName()
1683 << "' - it might create an irreducible loop!\n");
1687 unsigned JumpThreadCost =
1688 getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold);
1689 if (JumpThreadCost > BBDupThreshold) {
1690 DEBUG(dbgs() << " Not threading BB '" << BB->getName()
1691 << "' - Cost is too high: " << JumpThreadCost << "\n");
1695 // And finally, do it! Start by factoring the predecessors if needed.
1697 if (PredBBs.size() == 1)
1698 PredBB = PredBBs[0];
1700 DEBUG(dbgs() << " Factoring out " << PredBBs.size()
1701 << " common predecessors.\n");
1702 PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm");
1705 // And finally, do it!
1706 DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() << "' to '"
1707 << SuccBB->getName() << "' with cost: " << JumpThreadCost
1708 << ", across block:\n "
1711 LVI->threadEdge(PredBB, BB, SuccBB);
1713 // We are going to have to map operands from the original BB block to the new
1714 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1715 // account for entry from PredBB.
1716 DenseMap<Instruction*, Value*> ValueMapping;
1718 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
1719 BB->getName()+".thread",
1720 BB->getParent(), BB);
1721 NewBB->moveAfter(PredBB);
1723 // Set the block frequency of NewBB.
1724 if (HasProfileData) {
1726 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
1727 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
1730 BasicBlock::iterator BI = BB->begin();
1731 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1732 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1734 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1735 // mapping and using it to remap operands in the cloned instructions.
1736 for (; !isa<TerminatorInst>(BI); ++BI) {
1737 Instruction *New = BI->clone();
1738 New->setName(BI->getName());
1739 NewBB->getInstList().push_back(New);
1740 ValueMapping[&*BI] = New;
1742 // Remap operands to patch up intra-block references.
1743 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1744 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1745 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1746 if (I != ValueMapping.end())
1747 New->setOperand(i, I->second);
1751 // We didn't copy the terminator from BB over to NewBB, because there is now
1752 // an unconditional jump to SuccBB. Insert the unconditional jump.
1753 BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
1754 NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
1756 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1757 // PHI nodes for NewBB now.
1758 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
1760 // If there were values defined in BB that are used outside the block, then we
1761 // now have to update all uses of the value to use either the original value,
1762 // the cloned value, or some PHI derived value. This can require arbitrary
1763 // PHI insertion, of which we are prepared to do, clean these up now.
1764 SSAUpdater SSAUpdate;
1765 SmallVector<Use*, 16> UsesToRename;
1766 for (Instruction &I : *BB) {
1767 // Scan all uses of this instruction to see if it is used outside of its
1768 // block, and if so, record them in UsesToRename.
1769 for (Use &U : I.uses()) {
1770 Instruction *User = cast<Instruction>(U.getUser());
1771 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1772 if (UserPN->getIncomingBlock(U) == BB)
1774 } else if (User->getParent() == BB)
1777 UsesToRename.push_back(&U);
1780 // If there are no uses outside the block, we're done with this instruction.
1781 if (UsesToRename.empty())
1784 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
1786 // We found a use of I outside of BB. Rename all uses of I that are outside
1787 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1788 // with the two values we know.
1789 SSAUpdate.Initialize(I.getType(), I.getName());
1790 SSAUpdate.AddAvailableValue(BB, &I);
1791 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
1793 while (!UsesToRename.empty())
1794 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1795 DEBUG(dbgs() << "\n");
1799 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
1800 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1801 // us to simplify any PHI nodes in BB.
1802 TerminatorInst *PredTerm = PredBB->getTerminator();
1803 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1804 if (PredTerm->getSuccessor(i) == BB) {
1805 BB->removePredecessor(PredBB, true);
1806 PredTerm->setSuccessor(i, NewBB);
1809 // At this point, the IR is fully up to date and consistent. Do a quick scan
1810 // over the new instructions and zap any that are constants or dead. This
1811 // frequently happens because of phi translation.
1812 SimplifyInstructionsInBlock(NewBB, TLI);
1814 // Update the edge weight from BB to SuccBB, which should be less than before.
1815 UpdateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
1817 // Threaded an edge!
1822 /// Create a new basic block that will be the predecessor of BB and successor of
1823 /// all blocks in Preds. When profile data is available, update the frequency of
1825 BasicBlock *JumpThreadingPass::SplitBlockPreds(BasicBlock *BB,
1826 ArrayRef<BasicBlock *> Preds,
1827 const char *Suffix) {
1828 // Collect the frequencies of all predecessors of BB, which will be used to
1829 // update the edge weight on BB->SuccBB.
1830 BlockFrequency PredBBFreq(0);
1832 for (auto Pred : Preds)
1833 PredBBFreq += BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB);
1835 BasicBlock *PredBB = SplitBlockPredecessors(BB, Preds, Suffix);
1837 // Set the block frequency of the newly created PredBB, which is the sum of
1838 // frequencies of Preds.
1840 BFI->setBlockFreq(PredBB, PredBBFreq.getFrequency());
1844 bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
1845 const TerminatorInst *TI = BB->getTerminator();
1846 assert(TI->getNumSuccessors() > 1 && "not a split");
1848 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
1852 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
1853 if (MDName->getString() != "branch_weights")
1856 // Ensure there are weights for all of the successors. Note that the first
1857 // operand to the metadata node is a name, not a weight.
1858 return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1;
1861 /// Update the block frequency of BB and branch weight and the metadata on the
1862 /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
1863 /// Freq(PredBB->BB) / Freq(BB->SuccBB).
1864 void JumpThreadingPass::UpdateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
1867 BasicBlock *SuccBB) {
1868 if (!HasProfileData)
1871 assert(BFI && BPI && "BFI & BPI should have been created here");
1873 // As the edge from PredBB to BB is deleted, we have to update the block
1875 auto BBOrigFreq = BFI->getBlockFreq(BB);
1876 auto NewBBFreq = BFI->getBlockFreq(NewBB);
1877 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
1878 auto BBNewFreq = BBOrigFreq - NewBBFreq;
1879 BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
1881 // Collect updated outgoing edges' frequencies from BB and use them to update
1882 // edge probabilities.
1883 SmallVector<uint64_t, 4> BBSuccFreq;
1884 for (BasicBlock *Succ : successors(BB)) {
1885 auto SuccFreq = (Succ == SuccBB)
1886 ? BB2SuccBBFreq - NewBBFreq
1887 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
1888 BBSuccFreq.push_back(SuccFreq.getFrequency());
1891 uint64_t MaxBBSuccFreq =
1892 *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
1894 SmallVector<BranchProbability, 4> BBSuccProbs;
1895 if (MaxBBSuccFreq == 0)
1896 BBSuccProbs.assign(BBSuccFreq.size(),
1897 {1, static_cast<unsigned>(BBSuccFreq.size())});
1899 for (uint64_t Freq : BBSuccFreq)
1900 BBSuccProbs.push_back(
1901 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
1902 // Normalize edge probabilities so that they sum up to one.
1903 BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
1907 // Update edge probabilities in BPI.
1908 for (int I = 0, E = BBSuccProbs.size(); I < E; I++)
1909 BPI->setEdgeProbability(BB, I, BBSuccProbs[I]);
1911 // Update the profile metadata as well.
1913 // Don't do this if the profile of the transformed blocks was statically
1914 // estimated. (This could occur despite the function having an entry
1915 // frequency in completely cold parts of the CFG.)
1917 // In this case we don't want to suggest to subsequent passes that the
1918 // calculated weights are fully consistent. Consider this graph:
1933 // Assuming the blocks check_* all compare the same value against 1, 2 and 3,
1934 // the overall probabilities are inconsistent; the total probability that the
1935 // value is either 1, 2 or 3 is 150%.
1937 // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3
1938 // becomes 0%. This is even worse if the edge whose probability becomes 0% is
1939 // the loop exit edge. Then based solely on static estimation we would assume
1940 // the loop was extremely hot.
1942 // FIXME this locally as well so that BPI and BFI are consistent as well. We
1943 // shouldn't make edges extremely likely or unlikely based solely on static
1945 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) {
1946 SmallVector<uint32_t, 4> Weights;
1947 for (auto Prob : BBSuccProbs)
1948 Weights.push_back(Prob.getNumerator());
1950 auto TI = BB->getTerminator();
1952 LLVMContext::MD_prof,
1953 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
1957 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1958 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1959 /// If we can duplicate the contents of BB up into PredBB do so now, this
1960 /// improves the odds that the branch will be on an analyzable instruction like
1962 bool JumpThreadingPass::DuplicateCondBranchOnPHIIntoPred(
1963 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
1964 assert(!PredBBs.empty() && "Can't handle an empty set");
1966 // If BB is a loop header, then duplicating this block outside the loop would
1967 // cause us to transform this into an irreducible loop, don't do this.
1968 // See the comments above FindLoopHeaders for justifications and caveats.
1969 if (LoopHeaders.count(BB)) {
1970 DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
1971 << "' into predecessor block '" << PredBBs[0]->getName()
1972 << "' - it might create an irreducible loop!\n");
1976 unsigned DuplicationCost =
1977 getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold);
1978 if (DuplicationCost > BBDupThreshold) {
1979 DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
1980 << "' - Cost is too high: " << DuplicationCost << "\n");
1984 // And finally, do it! Start by factoring the predecessors if needed.
1986 if (PredBBs.size() == 1)
1987 PredBB = PredBBs[0];
1989 DEBUG(dbgs() << " Factoring out " << PredBBs.size()
1990 << " common predecessors.\n");
1991 PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm");
1994 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1996 DEBUG(dbgs() << " Duplicating block '" << BB->getName() << "' into end of '"
1997 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1998 << DuplicationCost << " block is:" << *BB << "\n");
2000 // Unless PredBB ends with an unconditional branch, split the edge so that we
2001 // can just clone the bits from BB into the end of the new PredBB.
2002 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2004 if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
2005 PredBB = SplitEdge(PredBB, BB);
2006 OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
2009 // We are going to have to map operands from the original BB block into the
2010 // PredBB block. Evaluate PHI nodes in BB.
2011 DenseMap<Instruction*, Value*> ValueMapping;
2013 BasicBlock::iterator BI = BB->begin();
2014 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
2015 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
2016 // Clone the non-phi instructions of BB into PredBB, keeping track of the
2017 // mapping and using it to remap operands in the cloned instructions.
2018 for (; BI != BB->end(); ++BI) {
2019 Instruction *New = BI->clone();
2021 // Remap operands to patch up intra-block references.
2022 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2023 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2024 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
2025 if (I != ValueMapping.end())
2026 New->setOperand(i, I->second);
2029 // If this instruction can be simplified after the operands are updated,
2030 // just use the simplified value instead. This frequently happens due to
2032 if (Value *IV = SimplifyInstruction(
2034 {BB->getModule()->getDataLayout(), TLI, nullptr, nullptr, New})) {
2035 ValueMapping[&*BI] = IV;
2036 if (!New->mayHaveSideEffects()) {
2041 ValueMapping[&*BI] = New;
2044 // Otherwise, insert the new instruction into the block.
2045 New->setName(BI->getName());
2046 PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
2050 // Check to see if the targets of the branch had PHI nodes. If so, we need to
2051 // add entries to the PHI nodes for branch from PredBB now.
2052 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
2053 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
2055 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
2058 // If there were values defined in BB that are used outside the block, then we
2059 // now have to update all uses of the value to use either the original value,
2060 // the cloned value, or some PHI derived value. This can require arbitrary
2061 // PHI insertion, of which we are prepared to do, clean these up now.
2062 SSAUpdater SSAUpdate;
2063 SmallVector<Use*, 16> UsesToRename;
2064 for (Instruction &I : *BB) {
2065 // Scan all uses of this instruction to see if it is used outside of its
2066 // block, and if so, record them in UsesToRename.
2067 for (Use &U : I.uses()) {
2068 Instruction *User = cast<Instruction>(U.getUser());
2069 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
2070 if (UserPN->getIncomingBlock(U) == BB)
2072 } else if (User->getParent() == BB)
2075 UsesToRename.push_back(&U);
2078 // If there are no uses outside the block, we're done with this instruction.
2079 if (UsesToRename.empty())
2082 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
2084 // We found a use of I outside of BB. Rename all uses of I that are outside
2085 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
2086 // with the two values we know.
2087 SSAUpdate.Initialize(I.getType(), I.getName());
2088 SSAUpdate.AddAvailableValue(BB, &I);
2089 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[&I]);
2091 while (!UsesToRename.empty())
2092 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
2093 DEBUG(dbgs() << "\n");
2096 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
2098 BB->removePredecessor(PredBB, true);
2100 // Remove the unconditional branch at the end of the PredBB block.
2101 OldPredBranch->eraseFromParent();
2107 /// TryToUnfoldSelect - Look for blocks of the form
2113 /// %p = phi [%a, %bb1] ...
2117 /// And expand the select into a branch structure if one of its arms allows %c
2118 /// to be folded. This later enables threading from bb1 over bb2.
2119 bool JumpThreadingPass::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
2120 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2121 PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
2122 Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
2124 if (!CondBr || !CondBr->isConditional() || !CondLHS ||
2125 CondLHS->getParent() != BB)
2128 for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
2129 BasicBlock *Pred = CondLHS->getIncomingBlock(I);
2130 SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
2132 // Look if one of the incoming values is a select in the corresponding
2134 if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
2137 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2138 if (!PredTerm || !PredTerm->isUnconditional())
2141 // Now check if one of the select values would allow us to constant fold the
2142 // terminator in BB. We don't do the transform if both sides fold, those
2143 // cases will be threaded in any case.
2144 LazyValueInfo::Tristate LHSFolds =
2145 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
2146 CondRHS, Pred, BB, CondCmp);
2147 LazyValueInfo::Tristate RHSFolds =
2148 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
2149 CondRHS, Pred, BB, CondCmp);
2150 if ((LHSFolds != LazyValueInfo::Unknown ||
2151 RHSFolds != LazyValueInfo::Unknown) &&
2152 LHSFolds != RHSFolds) {
2153 // Expand the select.
2162 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
2163 BB->getParent(), BB);
2164 // Move the unconditional branch to NewBB.
2165 PredTerm->removeFromParent();
2166 NewBB->getInstList().insert(NewBB->end(), PredTerm);
2167 // Create a conditional branch and update PHI nodes.
2168 BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
2169 CondLHS->setIncomingValue(I, SI->getFalseValue());
2170 CondLHS->addIncoming(SI->getTrueValue(), NewBB);
2171 // The select is now dead.
2172 SI->eraseFromParent();
2174 // Update any other PHI nodes in BB.
2175 for (BasicBlock::iterator BI = BB->begin();
2176 PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
2178 Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
2185 /// TryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the
2186 /// same BB in the form
2188 /// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
2189 /// %s = select %p, trueval, falseval
2194 /// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ...
2196 /// %s = select %c, trueval, falseval
2198 /// And expand the select into a branch structure. This later enables
2199 /// jump-threading over bb in this pass.
2201 /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
2202 /// select if the associated PHI has at least one constant. If the unfolded
2203 /// select is not jump-threaded, it will be folded again in the later
2205 bool JumpThreadingPass::TryToUnfoldSelectInCurrBB(BasicBlock *BB) {
2206 // If threading this would thread across a loop header, don't thread the edge.
2207 // See the comments above FindLoopHeaders for justifications and caveats.
2208 if (LoopHeaders.count(BB))
2211 for (BasicBlock::iterator BI = BB->begin();
2212 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2213 // Look for a Phi having at least one constant incoming value.
2214 if (llvm::all_of(PN->incoming_values(),
2215 [](Value *V) { return !isa<ConstantInt>(V); }))
2218 auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) {
2219 // Check if SI is in BB and use V as condition.
2220 if (SI->getParent() != BB)
2222 Value *Cond = SI->getCondition();
2223 return (Cond && Cond == V && Cond->getType()->isIntegerTy(1));
2226 SelectInst *SI = nullptr;
2227 for (Use &U : PN->uses()) {
2228 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
2229 // Look for a ICmp in BB that compares PN with a constant and is the
2230 // condition of a Select.
2231 if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
2232 isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
2233 if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
2234 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
2238 } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
2239 // Look for a Select in BB that uses PN as condtion.
2240 if (isUnfoldCandidate(SelectI, U.get())) {
2249 // Expand the select.
2250 TerminatorInst *Term =
2251 SplitBlockAndInsertIfThen(SI->getCondition(), SI, false);
2252 PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI);
2253 NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
2254 NewPN->addIncoming(SI->getFalseValue(), BB);
2255 SI->replaceAllUsesWith(NewPN);
2256 SI->eraseFromParent();
2262 /// Try to propagate a guard from the current BB into one of its predecessors
2263 /// in case if another branch of execution implies that the condition of this
2264 /// guard is always true. Currently we only process the simplest case that
2269 /// br i1 %cond, label %T1, label %F1
2275 /// %condGuard = ...
2276 /// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ]
2278 /// And cond either implies condGuard or !condGuard. In this case all the
2279 /// instructions before the guard can be duplicated in both branches, and the
2280 /// guard is then threaded to one of them.
2281 bool JumpThreadingPass::ProcessGuards(BasicBlock *BB) {
2282 using namespace PatternMatch;
2283 // We only want to deal with two predecessors.
2284 BasicBlock *Pred1, *Pred2;
2285 auto PI = pred_begin(BB), PE = pred_end(BB);
2297 // Try to thread one of the guards of the block.
2298 // TODO: Look up deeper than to immediate predecessor?
2299 auto *Parent = Pred1->getSinglePredecessor();
2300 if (!Parent || Parent != Pred2->getSinglePredecessor())
2303 if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
2305 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>()))
2306 if (ThreadGuard(BB, cast<IntrinsicInst>(&I), BI))
2312 /// Try to propagate the guard from BB which is the lower block of a diamond
2313 /// to one of its branches, in case if diamond's condition implies guard's
2315 bool JumpThreadingPass::ThreadGuard(BasicBlock *BB, IntrinsicInst *Guard,
2317 assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?");
2318 assert(BI->isConditional() && "Unconditional branch has 2 successors?");
2319 Value *GuardCond = Guard->getArgOperand(0);
2320 Value *BranchCond = BI->getCondition();
2321 BasicBlock *TrueDest = BI->getSuccessor(0);
2322 BasicBlock *FalseDest = BI->getSuccessor(1);
2324 auto &DL = BB->getModule()->getDataLayout();
2325 bool TrueDestIsSafe = false;
2326 bool FalseDestIsSafe = false;
2328 // True dest is safe if BranchCond => GuardCond.
2329 auto Impl = isImpliedCondition(BranchCond, GuardCond, DL);
2331 TrueDestIsSafe = true;
2333 // False dest is safe if !BranchCond => GuardCond.
2335 isImpliedCondition(BranchCond, GuardCond, DL, /* InvertAPred */ true);
2337 FalseDestIsSafe = true;
2340 if (!TrueDestIsSafe && !FalseDestIsSafe)
2343 BasicBlock *UnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
2344 BasicBlock *GuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
2346 ValueToValueMapTy UnguardedMapping, GuardedMapping;
2347 Instruction *AfterGuard = Guard->getNextNode();
2348 unsigned Cost = getJumpThreadDuplicationCost(BB, AfterGuard, BBDupThreshold);
2349 if (Cost > BBDupThreshold)
2351 // Duplicate all instructions before the guard and the guard itself to the
2352 // branch where implication is not proved.
2353 GuardedBlock = DuplicateInstructionsInSplitBetween(
2354 BB, GuardedBlock, AfterGuard, GuardedMapping);
2355 assert(GuardedBlock && "Could not create the guarded block?");
2356 // Duplicate all instructions before the guard in the unguarded branch.
2357 // Since we have successfully duplicated the guarded block and this block
2358 // has fewer instructions, we expect it to succeed.
2359 UnguardedBlock = DuplicateInstructionsInSplitBetween(BB, UnguardedBlock,
2360 Guard, UnguardedMapping);
2361 assert(UnguardedBlock && "Could not create the unguarded block?");
2362 DEBUG(dbgs() << "Moved guard " << *Guard << " to block "
2363 << GuardedBlock->getName() << "\n");
2365 // Some instructions before the guard may still have uses. For them, we need
2366 // to create Phi nodes merging their copies in both guarded and unguarded
2367 // branches. Those instructions that have no uses can be just removed.
2368 SmallVector<Instruction *, 4> ToRemove;
2369 for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
2370 if (!isa<PHINode>(&*BI))
2371 ToRemove.push_back(&*BI);
2373 Instruction *InsertionPoint = &*BB->getFirstInsertionPt();
2374 assert(InsertionPoint && "Empty block?");
2375 // Substitute with Phis & remove.
2376 for (auto *Inst : reverse(ToRemove)) {
2377 if (!Inst->use_empty()) {
2378 PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
2379 NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
2380 NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
2381 NewPN->insertBefore(InsertionPoint);
2382 Inst->replaceAllUsesWith(NewPN);
2384 Inst->eraseFromParent();