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