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