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