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