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