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