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