1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
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 // Peephole optimize the CFG.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/MapVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/ScopeExit.h"
20 #include "llvm/ADT/Sequence.h"
21 #include "llvm/ADT/SetOperations.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Analysis/AssumptionCache.h"
28 #include "llvm/Analysis/CaptureTracking.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/DomTreeUpdater.h"
31 #include "llvm/Analysis/GuardUtils.h"
32 #include "llvm/Analysis/InstructionSimplify.h"
33 #include "llvm/Analysis/MemorySSA.h"
34 #include "llvm/Analysis/MemorySSAUpdater.h"
35 #include "llvm/Analysis/TargetTransformInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/CFG.h"
40 #include "llvm/IR/Constant.h"
41 #include "llvm/IR/ConstantRange.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/IRBuilder.h"
49 #include "llvm/IR/InstrTypes.h"
50 #include "llvm/IR/Instruction.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/IntrinsicInst.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/MDBuilder.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/IR/NoFolder.h"
58 #include "llvm/IR/Operator.h"
59 #include "llvm/IR/PatternMatch.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Use.h"
62 #include "llvm/IR/User.h"
63 #include "llvm/IR/Value.h"
64 #include "llvm/IR/ValueHandle.h"
65 #include "llvm/Support/BranchProbability.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Debug.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/KnownBits.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
74 #include "llvm/Transforms/Utils/Local.h"
75 #include "llvm/Transforms/Utils/ValueMapper.h"
76 #include <algorithm>
77 #include <cassert>
78 #include <climits>
79 #include <cstddef>
80 #include <cstdint>
81 #include <iterator>
82 #include <map>
83 #include <set>
84 #include <tuple>
85 #include <utility>
86 #include <vector>
87 
88 using namespace llvm;
89 using namespace PatternMatch;
90 
91 #define DEBUG_TYPE "simplifycfg"
92 
93 cl::opt<bool> llvm::RequireAndPreserveDomTree(
94     "simplifycfg-require-and-preserve-domtree", cl::Hidden, cl::ZeroOrMore,
95     cl::init(false),
96     cl::desc("Temorary development switch used to gradually uplift SimplifyCFG "
97              "into preserving DomTree,"));
98 
99 // Chosen as 2 so as to be cheap, but still to have enough power to fold
100 // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
101 // To catch this, we need to fold a compare and a select, hence '2' being the
102 // minimum reasonable default.
103 static cl::opt<unsigned> PHINodeFoldingThreshold(
104     "phi-node-folding-threshold", cl::Hidden, cl::init(2),
105     cl::desc(
106         "Control the amount of phi node folding to perform (default = 2)"));
107 
108 static cl::opt<unsigned> TwoEntryPHINodeFoldingThreshold(
109     "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
110     cl::desc("Control the maximal total instruction cost that we are willing "
111              "to speculatively execute to fold a 2-entry PHI node into a "
112              "select (default = 4)"));
113 
114 static cl::opt<bool>
115     HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
116                 cl::desc("Hoist common instructions up to the parent block"));
117 
118 static cl::opt<bool>
119     SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
120                cl::desc("Sink common instructions down to the end block"));
121 
122 static cl::opt<bool> HoistCondStores(
123     "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
124     cl::desc("Hoist conditional stores if an unconditional store precedes"));
125 
126 static cl::opt<bool> MergeCondStores(
127     "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
128     cl::desc("Hoist conditional stores even if an unconditional store does not "
129              "precede - hoist multiple conditional stores into a single "
130              "predicated store"));
131 
132 static cl::opt<bool> MergeCondStoresAggressively(
133     "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
134     cl::desc("When merging conditional stores, do so even if the resultant "
135              "basic blocks are unlikely to be if-converted as a result"));
136 
137 static cl::opt<bool> SpeculateOneExpensiveInst(
138     "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
139     cl::desc("Allow exactly one expensive instruction to be speculatively "
140              "executed"));
141 
142 static cl::opt<unsigned> MaxSpeculationDepth(
143     "max-speculation-depth", cl::Hidden, cl::init(10),
144     cl::desc("Limit maximum recursion depth when calculating costs of "
145              "speculatively executed instructions"));
146 
147 static cl::opt<int>
148     MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
149                       cl::init(10),
150                       cl::desc("Max size of a block which is still considered "
151                                "small enough to thread through"));
152 
153 // Two is chosen to allow one negation and a logical combine.
154 static cl::opt<unsigned>
155     BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
156                         cl::init(2),
157                         cl::desc("Maximum cost of combining conditions when "
158                                  "folding branches"));
159 
160 static cl::opt<unsigned> BranchFoldToCommonDestVectorMultiplier(
161     "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
162     cl::init(2),
163     cl::desc("Multiplier to apply to threshold when determining whether or not "
164              "to fold branch to common destination when vector operations are "
165              "present"));
166 
167 static cl::opt<bool> EnableMergeCompatibleInvokes(
168     "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
169     cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
170 
171 static cl::opt<unsigned> MaxSwitchCasesPerResult(
172     "max-switch-cases-per-result", cl::Hidden, cl::init(16),
173     cl::desc("Limit cases to analyze when converting a switch to select"));
174 
175 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
176 STATISTIC(NumLinearMaps,
177           "Number of switch instructions turned into linear mapping");
178 STATISTIC(NumLookupTables,
179           "Number of switch instructions turned into lookup tables");
180 STATISTIC(
181     NumLookupTablesHoles,
182     "Number of switch instructions turned into lookup tables (holes checked)");
183 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
184 STATISTIC(NumFoldValueComparisonIntoPredecessors,
185           "Number of value comparisons folded into predecessor basic blocks");
186 STATISTIC(NumFoldBranchToCommonDest,
187           "Number of branches folded into predecessor basic block");
188 STATISTIC(
189     NumHoistCommonCode,
190     "Number of common instruction 'blocks' hoisted up to the begin block");
191 STATISTIC(NumHoistCommonInstrs,
192           "Number of common instructions hoisted up to the begin block");
193 STATISTIC(NumSinkCommonCode,
194           "Number of common instruction 'blocks' sunk down to the end block");
195 STATISTIC(NumSinkCommonInstrs,
196           "Number of common instructions sunk down to the end block");
197 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
198 STATISTIC(NumInvokes,
199           "Number of invokes with empty resume blocks simplified into calls");
200 STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
201 STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
202 
203 namespace {
204 
205 // The first field contains the value that the switch produces when a certain
206 // case group is selected, and the second field is a vector containing the
207 // cases composing the case group.
208 using SwitchCaseResultVectorTy =
209     SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>;
210 
211 // The first field contains the phi node that generates a result of the switch
212 // and the second field contains the value generated for a certain case in the
213 // switch for that PHI.
214 using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
215 
216 /// ValueEqualityComparisonCase - Represents a case of a switch.
217 struct ValueEqualityComparisonCase {
218   ConstantInt *Value;
219   BasicBlock *Dest;
220 
221   ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
222       : Value(Value), Dest(Dest) {}
223 
224   bool operator<(ValueEqualityComparisonCase RHS) const {
225     // Comparing pointers is ok as we only rely on the order for uniquing.
226     return Value < RHS.Value;
227   }
228 
229   bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
230 };
231 
232 class SimplifyCFGOpt {
233   const TargetTransformInfo &TTI;
234   DomTreeUpdater *DTU;
235   const DataLayout &DL;
236   ArrayRef<WeakVH> LoopHeaders;
237   const SimplifyCFGOptions &Options;
238   bool Resimplify;
239 
240   Value *isValueEqualityComparison(Instruction *TI);
241   BasicBlock *GetValueEqualityComparisonCases(
242       Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
243   bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
244                                                      BasicBlock *Pred,
245                                                      IRBuilder<> &Builder);
246   bool PerformValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
247                                                     Instruction *PTI,
248                                                     IRBuilder<> &Builder);
249   bool FoldValueComparisonIntoPredecessors(Instruction *TI,
250                                            IRBuilder<> &Builder);
251 
252   bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
253   bool simplifySingleResume(ResumeInst *RI);
254   bool simplifyCommonResume(ResumeInst *RI);
255   bool simplifyCleanupReturn(CleanupReturnInst *RI);
256   bool simplifyUnreachable(UnreachableInst *UI);
257   bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
258   bool simplifyIndirectBr(IndirectBrInst *IBI);
259   bool simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder);
260   bool simplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
261   bool simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
262 
263   bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
264                                              IRBuilder<> &Builder);
265 
266   bool HoistThenElseCodeToIf(BranchInst *BI, const TargetTransformInfo &TTI,
267                              bool EqTermsOnly);
268   bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
269                               const TargetTransformInfo &TTI);
270   bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
271                                   BasicBlock *TrueBB, BasicBlock *FalseBB,
272                                   uint32_t TrueWeight, uint32_t FalseWeight);
273   bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
274                                  const DataLayout &DL);
275   bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
276   bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
277   bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
278 
279 public:
280   SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
281                  const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
282                  const SimplifyCFGOptions &Opts)
283       : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
284     assert((!DTU || !DTU->hasPostDomTree()) &&
285            "SimplifyCFG is not yet capable of maintaining validity of a "
286            "PostDomTree, so don't ask for it.");
287   }
288 
289   bool simplifyOnce(BasicBlock *BB);
290   bool run(BasicBlock *BB);
291 
292   // Helper to set Resimplify and return change indication.
293   bool requestResimplify() {
294     Resimplify = true;
295     return true;
296   }
297 };
298 
299 } // end anonymous namespace
300 
301 /// Return true if all the PHI nodes in the basic block \p BB
302 /// receive compatible (identical) incoming values when coming from
303 /// all of the predecessor blocks that are specified in \p IncomingBlocks.
304 ///
305 /// Note that if the values aren't exactly identical, but \p EquivalenceSet
306 /// is provided, and *both* of the values are present in the set,
307 /// then they are considered equal.
308 static bool IncomingValuesAreCompatible(
309     BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
310     SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
311   assert(IncomingBlocks.size() == 2 &&
312          "Only for a pair of incoming blocks at the time!");
313 
314   // FIXME: it is okay if one of the incoming values is an `undef` value,
315   //        iff the other incoming value is guaranteed to be a non-poison value.
316   // FIXME: it is okay if one of the incoming values is a `poison` value.
317   return all_of(BB->phis(), [IncomingBlocks, EquivalenceSet](PHINode &PN) {
318     Value *IV0 = PN.getIncomingValueForBlock(IncomingBlocks[0]);
319     Value *IV1 = PN.getIncomingValueForBlock(IncomingBlocks[1]);
320     if (IV0 == IV1)
321       return true;
322     if (EquivalenceSet && EquivalenceSet->contains(IV0) &&
323         EquivalenceSet->contains(IV1))
324       return true;
325     return false;
326   });
327 }
328 
329 /// Return true if it is safe to merge these two
330 /// terminator instructions together.
331 static bool
332 SafeToMergeTerminators(Instruction *SI1, Instruction *SI2,
333                        SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
334   if (SI1 == SI2)
335     return false; // Can't merge with self!
336 
337   // It is not safe to merge these two switch instructions if they have a common
338   // successor, and if that successor has a PHI node, and if *that* PHI node has
339   // conflicting incoming values from the two switch blocks.
340   BasicBlock *SI1BB = SI1->getParent();
341   BasicBlock *SI2BB = SI2->getParent();
342 
343   SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
344   bool Fail = false;
345   for (BasicBlock *Succ : successors(SI2BB)) {
346     if (!SI1Succs.count(Succ))
347       continue;
348     if (IncomingValuesAreCompatible(Succ, {SI1BB, SI2BB}))
349       continue;
350     Fail = true;
351     if (FailBlocks)
352       FailBlocks->insert(Succ);
353     else
354       break;
355   }
356 
357   return !Fail;
358 }
359 
360 /// Update PHI nodes in Succ to indicate that there will now be entries in it
361 /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
362 /// will be the same as those coming in from ExistPred, an existing predecessor
363 /// of Succ.
364 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
365                                   BasicBlock *ExistPred,
366                                   MemorySSAUpdater *MSSAU = nullptr) {
367   for (PHINode &PN : Succ->phis())
368     PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
369   if (MSSAU)
370     if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
371       MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
372 }
373 
374 /// Compute an abstract "cost" of speculating the given instruction,
375 /// which is assumed to be safe to speculate. TCC_Free means cheap,
376 /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
377 /// expensive.
378 static InstructionCost computeSpeculationCost(const User *I,
379                                               const TargetTransformInfo &TTI) {
380   assert(isSafeToSpeculativelyExecute(I) &&
381          "Instruction is not safe to speculatively execute!");
382   return TTI.getUserCost(I, TargetTransformInfo::TCK_SizeAndLatency);
383 }
384 
385 /// If we have a merge point of an "if condition" as accepted above,
386 /// return true if the specified value dominates the block.  We
387 /// don't handle the true generality of domination here, just a special case
388 /// which works well enough for us.
389 ///
390 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
391 /// see if V (which must be an instruction) and its recursive operands
392 /// that do not dominate BB have a combined cost lower than Budget and
393 /// are non-trapping.  If both are true, the instruction is inserted into the
394 /// set and true is returned.
395 ///
396 /// The cost for most non-trapping instructions is defined as 1 except for
397 /// Select whose cost is 2.
398 ///
399 /// After this function returns, Cost is increased by the cost of
400 /// V plus its non-dominating operands.  If that cost is greater than
401 /// Budget, false is returned and Cost is undefined.
402 static bool dominatesMergePoint(Value *V, BasicBlock *BB,
403                                 SmallPtrSetImpl<Instruction *> &AggressiveInsts,
404                                 InstructionCost &Cost,
405                                 InstructionCost Budget,
406                                 const TargetTransformInfo &TTI,
407                                 unsigned Depth = 0) {
408   // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
409   // so limit the recursion depth.
410   // TODO: While this recursion limit does prevent pathological behavior, it
411   // would be better to track visited instructions to avoid cycles.
412   if (Depth == MaxSpeculationDepth)
413     return false;
414 
415   Instruction *I = dyn_cast<Instruction>(V);
416   if (!I) {
417     // Non-instructions all dominate instructions, but not all constantexprs
418     // can be executed unconditionally.
419     if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
420       if (C->canTrap())
421         return false;
422     return true;
423   }
424   BasicBlock *PBB = I->getParent();
425 
426   // We don't want to allow weird loops that might have the "if condition" in
427   // the bottom of this block.
428   if (PBB == BB)
429     return false;
430 
431   // If this instruction is defined in a block that contains an unconditional
432   // branch to BB, then it must be in the 'conditional' part of the "if
433   // statement".  If not, it definitely dominates the region.
434   BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
435   if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
436     return true;
437 
438   // If we have seen this instruction before, don't count it again.
439   if (AggressiveInsts.count(I))
440     return true;
441 
442   // Okay, it looks like the instruction IS in the "condition".  Check to
443   // see if it's a cheap instruction to unconditionally compute, and if it
444   // only uses stuff defined outside of the condition.  If so, hoist it out.
445   if (!isSafeToSpeculativelyExecute(I))
446     return false;
447 
448   Cost += computeSpeculationCost(I, TTI);
449 
450   // Allow exactly one instruction to be speculated regardless of its cost
451   // (as long as it is safe to do so).
452   // This is intended to flatten the CFG even if the instruction is a division
453   // or other expensive operation. The speculation of an expensive instruction
454   // is expected to be undone in CodeGenPrepare if the speculation has not
455   // enabled further IR optimizations.
456   if (Cost > Budget &&
457       (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
458        !Cost.isValid()))
459     return false;
460 
461   // Okay, we can only really hoist these out if their operands do
462   // not take us over the cost threshold.
463   for (Use &Op : I->operands())
464     if (!dominatesMergePoint(Op, BB, AggressiveInsts, Cost, Budget, TTI,
465                              Depth + 1))
466       return false;
467   // Okay, it's safe to do this!  Remember this instruction.
468   AggressiveInsts.insert(I);
469   return true;
470 }
471 
472 /// Extract ConstantInt from value, looking through IntToPtr
473 /// and PointerNullValue. Return NULL if value is not a constant int.
474 static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
475   // Normal constant int.
476   ConstantInt *CI = dyn_cast<ConstantInt>(V);
477   if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
478     return CI;
479 
480   // This is some kind of pointer constant. Turn it into a pointer-sized
481   // ConstantInt if possible.
482   IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
483 
484   // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
485   if (isa<ConstantPointerNull>(V))
486     return ConstantInt::get(PtrTy, 0);
487 
488   // IntToPtr const int.
489   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
490     if (CE->getOpcode() == Instruction::IntToPtr)
491       if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
492         // The constant is very likely to have the right type already.
493         if (CI->getType() == PtrTy)
494           return CI;
495         else
496           return cast<ConstantInt>(
497               ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
498       }
499   return nullptr;
500 }
501 
502 namespace {
503 
504 /// Given a chain of or (||) or and (&&) comparison of a value against a
505 /// constant, this will try to recover the information required for a switch
506 /// structure.
507 /// It will depth-first traverse the chain of comparison, seeking for patterns
508 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
509 /// representing the different cases for the switch.
510 /// Note that if the chain is composed of '||' it will build the set of elements
511 /// that matches the comparisons (i.e. any of this value validate the chain)
512 /// while for a chain of '&&' it will build the set elements that make the test
513 /// fail.
514 struct ConstantComparesGatherer {
515   const DataLayout &DL;
516 
517   /// Value found for the switch comparison
518   Value *CompValue = nullptr;
519 
520   /// Extra clause to be checked before the switch
521   Value *Extra = nullptr;
522 
523   /// Set of integers to match in switch
524   SmallVector<ConstantInt *, 8> Vals;
525 
526   /// Number of comparisons matched in the and/or chain
527   unsigned UsedICmps = 0;
528 
529   /// Construct and compute the result for the comparison instruction Cond
530   ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
531     gather(Cond);
532   }
533 
534   ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
535   ConstantComparesGatherer &
536   operator=(const ConstantComparesGatherer &) = delete;
537 
538 private:
539   /// Try to set the current value used for the comparison, it succeeds only if
540   /// it wasn't set before or if the new value is the same as the old one
541   bool setValueOnce(Value *NewVal) {
542     if (CompValue && CompValue != NewVal)
543       return false;
544     CompValue = NewVal;
545     return (CompValue != nullptr);
546   }
547 
548   /// Try to match Instruction "I" as a comparison against a constant and
549   /// populates the array Vals with the set of values that match (or do not
550   /// match depending on isEQ).
551   /// Return false on failure. On success, the Value the comparison matched
552   /// against is placed in CompValue.
553   /// If CompValue is already set, the function is expected to fail if a match
554   /// is found but the value compared to is different.
555   bool matchInstruction(Instruction *I, bool isEQ) {
556     // If this is an icmp against a constant, handle this as one of the cases.
557     ICmpInst *ICI;
558     ConstantInt *C;
559     if (!((ICI = dyn_cast<ICmpInst>(I)) &&
560           (C = GetConstantInt(I->getOperand(1), DL)))) {
561       return false;
562     }
563 
564     Value *RHSVal;
565     const APInt *RHSC;
566 
567     // Pattern match a special case
568     // (x & ~2^z) == y --> x == y || x == y|2^z
569     // This undoes a transformation done by instcombine to fuse 2 compares.
570     if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
571       // It's a little bit hard to see why the following transformations are
572       // correct. Here is a CVC3 program to verify them for 64-bit values:
573 
574       /*
575          ONE  : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
576          x    : BITVECTOR(64);
577          y    : BITVECTOR(64);
578          z    : BITVECTOR(64);
579          mask : BITVECTOR(64) = BVSHL(ONE, z);
580          QUERY( (y & ~mask = y) =>
581                 ((x & ~mask = y) <=> (x = y OR x = (y |  mask)))
582          );
583          QUERY( (y |  mask = y) =>
584                 ((x |  mask = y) <=> (x = y OR x = (y & ~mask)))
585          );
586       */
587 
588       // Please note that each pattern must be a dual implication (<--> or
589       // iff). One directional implication can create spurious matches. If the
590       // implication is only one-way, an unsatisfiable condition on the left
591       // side can imply a satisfiable condition on the right side. Dual
592       // implication ensures that satisfiable conditions are transformed to
593       // other satisfiable conditions and unsatisfiable conditions are
594       // transformed to other unsatisfiable conditions.
595 
596       // Here is a concrete example of a unsatisfiable condition on the left
597       // implying a satisfiable condition on the right:
598       //
599       // mask = (1 << z)
600       // (x & ~mask) == y  --> (x == y || x == (y | mask))
601       //
602       // Substituting y = 3, z = 0 yields:
603       // (x & -2) == 3 --> (x == 3 || x == 2)
604 
605       // Pattern match a special case:
606       /*
607         QUERY( (y & ~mask = y) =>
608                ((x & ~mask = y) <=> (x = y OR x = (y |  mask)))
609         );
610       */
611       if (match(ICI->getOperand(0),
612                 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
613         APInt Mask = ~*RHSC;
614         if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
615           // If we already have a value for the switch, it has to match!
616           if (!setValueOnce(RHSVal))
617             return false;
618 
619           Vals.push_back(C);
620           Vals.push_back(
621               ConstantInt::get(C->getContext(),
622                                C->getValue() | Mask));
623           UsedICmps++;
624           return true;
625         }
626       }
627 
628       // Pattern match a special case:
629       /*
630         QUERY( (y |  mask = y) =>
631                ((x |  mask = y) <=> (x = y OR x = (y & ~mask)))
632         );
633       */
634       if (match(ICI->getOperand(0),
635                 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
636         APInt Mask = *RHSC;
637         if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
638           // If we already have a value for the switch, it has to match!
639           if (!setValueOnce(RHSVal))
640             return false;
641 
642           Vals.push_back(C);
643           Vals.push_back(ConstantInt::get(C->getContext(),
644                                           C->getValue() & ~Mask));
645           UsedICmps++;
646           return true;
647         }
648       }
649 
650       // If we already have a value for the switch, it has to match!
651       if (!setValueOnce(ICI->getOperand(0)))
652         return false;
653 
654       UsedICmps++;
655       Vals.push_back(C);
656       return ICI->getOperand(0);
657     }
658 
659     // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
660     ConstantRange Span =
661         ConstantRange::makeExactICmpRegion(ICI->getPredicate(), C->getValue());
662 
663     // Shift the range if the compare is fed by an add. This is the range
664     // compare idiom as emitted by instcombine.
665     Value *CandidateVal = I->getOperand(0);
666     if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
667       Span = Span.subtract(*RHSC);
668       CandidateVal = RHSVal;
669     }
670 
671     // If this is an and/!= check, then we are looking to build the set of
672     // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
673     // x != 0 && x != 1.
674     if (!isEQ)
675       Span = Span.inverse();
676 
677     // If there are a ton of values, we don't want to make a ginormous switch.
678     if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
679       return false;
680     }
681 
682     // If we already have a value for the switch, it has to match!
683     if (!setValueOnce(CandidateVal))
684       return false;
685 
686     // Add all values from the range to the set
687     for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
688       Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
689 
690     UsedICmps++;
691     return true;
692   }
693 
694   /// Given a potentially 'or'd or 'and'd together collection of icmp
695   /// eq/ne/lt/gt instructions that compare a value against a constant, extract
696   /// the value being compared, and stick the list constants into the Vals
697   /// vector.
698   /// One "Extra" case is allowed to differ from the other.
699   void gather(Value *V) {
700     bool isEQ = match(V, m_LogicalOr(m_Value(), m_Value()));
701 
702     // Keep a stack (SmallVector for efficiency) for depth-first traversal
703     SmallVector<Value *, 8> DFT;
704     SmallPtrSet<Value *, 8> Visited;
705 
706     // Initialize
707     Visited.insert(V);
708     DFT.push_back(V);
709 
710     while (!DFT.empty()) {
711       V = DFT.pop_back_val();
712 
713       if (Instruction *I = dyn_cast<Instruction>(V)) {
714         // If it is a || (or && depending on isEQ), process the operands.
715         Value *Op0, *Op1;
716         if (isEQ ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
717                  : match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
718           if (Visited.insert(Op1).second)
719             DFT.push_back(Op1);
720           if (Visited.insert(Op0).second)
721             DFT.push_back(Op0);
722 
723           continue;
724         }
725 
726         // Try to match the current instruction
727         if (matchInstruction(I, isEQ))
728           // Match succeed, continue the loop
729           continue;
730       }
731 
732       // One element of the sequence of || (or &&) could not be match as a
733       // comparison against the same value as the others.
734       // We allow only one "Extra" case to be checked before the switch
735       if (!Extra) {
736         Extra = V;
737         continue;
738       }
739       // Failed to parse a proper sequence, abort now
740       CompValue = nullptr;
741       break;
742     }
743   }
744 };
745 
746 } // end anonymous namespace
747 
748 static void EraseTerminatorAndDCECond(Instruction *TI,
749                                       MemorySSAUpdater *MSSAU = nullptr) {
750   Instruction *Cond = nullptr;
751   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
752     Cond = dyn_cast<Instruction>(SI->getCondition());
753   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
754     if (BI->isConditional())
755       Cond = dyn_cast<Instruction>(BI->getCondition());
756   } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
757     Cond = dyn_cast<Instruction>(IBI->getAddress());
758   }
759 
760   TI->eraseFromParent();
761   if (Cond)
762     RecursivelyDeleteTriviallyDeadInstructions(Cond, nullptr, MSSAU);
763 }
764 
765 /// Return true if the specified terminator checks
766 /// to see if a value is equal to constant integer value.
767 Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
768   Value *CV = nullptr;
769   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
770     // Do not permit merging of large switch instructions into their
771     // predecessors unless there is only one predecessor.
772     if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
773       CV = SI->getCondition();
774   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
775     if (BI->isConditional() && BI->getCondition()->hasOneUse())
776       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
777         if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
778           CV = ICI->getOperand(0);
779       }
780 
781   // Unwrap any lossless ptrtoint cast.
782   if (CV) {
783     if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
784       Value *Ptr = PTII->getPointerOperand();
785       if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
786         CV = Ptr;
787     }
788   }
789   return CV;
790 }
791 
792 /// Given a value comparison instruction,
793 /// decode all of the 'cases' that it represents and return the 'default' block.
794 BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
795     Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
796   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
797     Cases.reserve(SI->getNumCases());
798     for (auto Case : SI->cases())
799       Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
800                                                   Case.getCaseSuccessor()));
801     return SI->getDefaultDest();
802   }
803 
804   BranchInst *BI = cast<BranchInst>(TI);
805   ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
806   BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
807   Cases.push_back(ValueEqualityComparisonCase(
808       GetConstantInt(ICI->getOperand(1), DL), Succ));
809   return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
810 }
811 
812 /// Given a vector of bb/value pairs, remove any entries
813 /// in the list that match the specified block.
814 static void
815 EliminateBlockCases(BasicBlock *BB,
816                     std::vector<ValueEqualityComparisonCase> &Cases) {
817   llvm::erase_value(Cases, BB);
818 }
819 
820 /// Return true if there are any keys in C1 that exist in C2 as well.
821 static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
822                           std::vector<ValueEqualityComparisonCase> &C2) {
823   std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
824 
825   // Make V1 be smaller than V2.
826   if (V1->size() > V2->size())
827     std::swap(V1, V2);
828 
829   if (V1->empty())
830     return false;
831   if (V1->size() == 1) {
832     // Just scan V2.
833     ConstantInt *TheVal = (*V1)[0].Value;
834     for (unsigned i = 0, e = V2->size(); i != e; ++i)
835       if (TheVal == (*V2)[i].Value)
836         return true;
837   }
838 
839   // Otherwise, just sort both lists and compare element by element.
840   array_pod_sort(V1->begin(), V1->end());
841   array_pod_sort(V2->begin(), V2->end());
842   unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
843   while (i1 != e1 && i2 != e2) {
844     if ((*V1)[i1].Value == (*V2)[i2].Value)
845       return true;
846     if ((*V1)[i1].Value < (*V2)[i2].Value)
847       ++i1;
848     else
849       ++i2;
850   }
851   return false;
852 }
853 
854 // Set branch weights on SwitchInst. This sets the metadata if there is at
855 // least one non-zero weight.
856 static void setBranchWeights(SwitchInst *SI, ArrayRef<uint32_t> Weights) {
857   // Check that there is at least one non-zero weight. Otherwise, pass
858   // nullptr to setMetadata which will erase the existing metadata.
859   MDNode *N = nullptr;
860   if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; }))
861     N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights);
862   SI->setMetadata(LLVMContext::MD_prof, N);
863 }
864 
865 // Similar to the above, but for branch and select instructions that take
866 // exactly 2 weights.
867 static void setBranchWeights(Instruction *I, uint32_t TrueWeight,
868                              uint32_t FalseWeight) {
869   assert(isa<BranchInst>(I) || isa<SelectInst>(I));
870   // Check that there is at least one non-zero weight. Otherwise, pass
871   // nullptr to setMetadata which will erase the existing metadata.
872   MDNode *N = nullptr;
873   if (TrueWeight || FalseWeight)
874     N = MDBuilder(I->getParent()->getContext())
875             .createBranchWeights(TrueWeight, FalseWeight);
876   I->setMetadata(LLVMContext::MD_prof, N);
877 }
878 
879 /// If TI is known to be a terminator instruction and its block is known to
880 /// only have a single predecessor block, check to see if that predecessor is
881 /// also a value comparison with the same value, and if that comparison
882 /// determines the outcome of this comparison. If so, simplify TI. This does a
883 /// very limited form of jump threading.
884 bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
885     Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
886   Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
887   if (!PredVal)
888     return false; // Not a value comparison in predecessor.
889 
890   Value *ThisVal = isValueEqualityComparison(TI);
891   assert(ThisVal && "This isn't a value comparison!!");
892   if (ThisVal != PredVal)
893     return false; // Different predicates.
894 
895   // TODO: Preserve branch weight metadata, similarly to how
896   // FoldValueComparisonIntoPredecessors preserves it.
897 
898   // Find out information about when control will move from Pred to TI's block.
899   std::vector<ValueEqualityComparisonCase> PredCases;
900   BasicBlock *PredDef =
901       GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
902   EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
903 
904   // Find information about how control leaves this block.
905   std::vector<ValueEqualityComparisonCase> ThisCases;
906   BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
907   EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
908 
909   // If TI's block is the default block from Pred's comparison, potentially
910   // simplify TI based on this knowledge.
911   if (PredDef == TI->getParent()) {
912     // If we are here, we know that the value is none of those cases listed in
913     // PredCases.  If there are any cases in ThisCases that are in PredCases, we
914     // can simplify TI.
915     if (!ValuesOverlap(PredCases, ThisCases))
916       return false;
917 
918     if (isa<BranchInst>(TI)) {
919       // Okay, one of the successors of this condbr is dead.  Convert it to a
920       // uncond br.
921       assert(ThisCases.size() == 1 && "Branch can only have one case!");
922       // Insert the new branch.
923       Instruction *NI = Builder.CreateBr(ThisDef);
924       (void)NI;
925 
926       // Remove PHI node entries for the dead edge.
927       ThisCases[0].Dest->removePredecessor(PredDef);
928 
929       LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
930                         << "Through successor TI: " << *TI << "Leaving: " << *NI
931                         << "\n");
932 
933       EraseTerminatorAndDCECond(TI);
934 
935       if (DTU)
936         DTU->applyUpdates(
937             {{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
938 
939       return true;
940     }
941 
942     SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
943     // Okay, TI has cases that are statically dead, prune them away.
944     SmallPtrSet<Constant *, 16> DeadCases;
945     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
946       DeadCases.insert(PredCases[i].Value);
947 
948     LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
949                       << "Through successor TI: " << *TI);
950 
951     SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
952     for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
953       --i;
954       auto *Successor = i->getCaseSuccessor();
955       if (DTU)
956         ++NumPerSuccessorCases[Successor];
957       if (DeadCases.count(i->getCaseValue())) {
958         Successor->removePredecessor(PredDef);
959         SI.removeCase(i);
960         if (DTU)
961           --NumPerSuccessorCases[Successor];
962       }
963     }
964 
965     if (DTU) {
966       std::vector<DominatorTree::UpdateType> Updates;
967       for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
968         if (I.second == 0)
969           Updates.push_back({DominatorTree::Delete, PredDef, I.first});
970       DTU->applyUpdates(Updates);
971     }
972 
973     LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
974     return true;
975   }
976 
977   // Otherwise, TI's block must correspond to some matched value.  Find out
978   // which value (or set of values) this is.
979   ConstantInt *TIV = nullptr;
980   BasicBlock *TIBB = TI->getParent();
981   for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
982     if (PredCases[i].Dest == TIBB) {
983       if (TIV)
984         return false; // Cannot handle multiple values coming to this block.
985       TIV = PredCases[i].Value;
986     }
987   assert(TIV && "No edge from pred to succ?");
988 
989   // Okay, we found the one constant that our value can be if we get into TI's
990   // BB.  Find out which successor will unconditionally be branched to.
991   BasicBlock *TheRealDest = nullptr;
992   for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
993     if (ThisCases[i].Value == TIV) {
994       TheRealDest = ThisCases[i].Dest;
995       break;
996     }
997 
998   // If not handled by any explicit cases, it is handled by the default case.
999   if (!TheRealDest)
1000     TheRealDest = ThisDef;
1001 
1002   SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
1003 
1004   // Remove PHI node entries for dead edges.
1005   BasicBlock *CheckEdge = TheRealDest;
1006   for (BasicBlock *Succ : successors(TIBB))
1007     if (Succ != CheckEdge) {
1008       if (Succ != TheRealDest)
1009         RemovedSuccs.insert(Succ);
1010       Succ->removePredecessor(TIBB);
1011     } else
1012       CheckEdge = nullptr;
1013 
1014   // Insert the new branch.
1015   Instruction *NI = Builder.CreateBr(TheRealDest);
1016   (void)NI;
1017 
1018   LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1019                     << "Through successor TI: " << *TI << "Leaving: " << *NI
1020                     << "\n");
1021 
1022   EraseTerminatorAndDCECond(TI);
1023   if (DTU) {
1024     SmallVector<DominatorTree::UpdateType, 2> Updates;
1025     Updates.reserve(RemovedSuccs.size());
1026     for (auto *RemovedSucc : RemovedSuccs)
1027       Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
1028     DTU->applyUpdates(Updates);
1029   }
1030   return true;
1031 }
1032 
1033 namespace {
1034 
1035 /// This class implements a stable ordering of constant
1036 /// integers that does not depend on their address.  This is important for
1037 /// applications that sort ConstantInt's to ensure uniqueness.
1038 struct ConstantIntOrdering {
1039   bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1040     return LHS->getValue().ult(RHS->getValue());
1041   }
1042 };
1043 
1044 } // end anonymous namespace
1045 
1046 static int ConstantIntSortPredicate(ConstantInt *const *P1,
1047                                     ConstantInt *const *P2) {
1048   const ConstantInt *LHS = *P1;
1049   const ConstantInt *RHS = *P2;
1050   if (LHS == RHS)
1051     return 0;
1052   return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
1053 }
1054 
1055 static inline bool HasBranchWeights(const Instruction *I) {
1056   MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
1057   if (ProfMD && ProfMD->getOperand(0))
1058     if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
1059       return MDS->getString().equals("branch_weights");
1060 
1061   return false;
1062 }
1063 
1064 /// Get Weights of a given terminator, the default weight is at the front
1065 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1066 /// metadata.
1067 static void GetBranchWeights(Instruction *TI,
1068                              SmallVectorImpl<uint64_t> &Weights) {
1069   MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
1070   assert(MD);
1071   for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
1072     ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
1073     Weights.push_back(CI->getValue().getZExtValue());
1074   }
1075 
1076   // If TI is a conditional eq, the default case is the false case,
1077   // and the corresponding branch-weight data is at index 2. We swap the
1078   // default weight to be the first entry.
1079   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1080     assert(Weights.size() == 2);
1081     ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
1082     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1083       std::swap(Weights.front(), Weights.back());
1084   }
1085 }
1086 
1087 /// Keep halving the weights until all can fit in uint32_t.
1088 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
1089   uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
1090   if (Max > UINT_MAX) {
1091     unsigned Offset = 32 - countLeadingZeros(Max);
1092     for (uint64_t &I : Weights)
1093       I >>= Offset;
1094   }
1095 }
1096 
1097 static void CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(
1098     BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1099   Instruction *PTI = PredBlock->getTerminator();
1100 
1101   // If we have bonus instructions, clone them into the predecessor block.
1102   // Note that there may be multiple predecessor blocks, so we cannot move
1103   // bonus instructions to a predecessor block.
1104   for (Instruction &BonusInst : *BB) {
1105     if (isa<DbgInfoIntrinsic>(BonusInst) || BonusInst.isTerminator())
1106       continue;
1107 
1108     Instruction *NewBonusInst = BonusInst.clone();
1109 
1110     if (PTI->getDebugLoc() != NewBonusInst->getDebugLoc()) {
1111       // Unless the instruction has the same !dbg location as the original
1112       // branch, drop it. When we fold the bonus instructions we want to make
1113       // sure we reset their debug locations in order to avoid stepping on
1114       // dead code caused by folding dead branches.
1115       NewBonusInst->setDebugLoc(DebugLoc());
1116     }
1117 
1118     RemapInstruction(NewBonusInst, VMap,
1119                      RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1120     VMap[&BonusInst] = NewBonusInst;
1121 
1122     // If we moved a load, we cannot any longer claim any knowledge about
1123     // its potential value. The previous information might have been valid
1124     // only given the branch precondition.
1125     // For an analogous reason, we must also drop all the metadata whose
1126     // semantics we don't understand. We *can* preserve !annotation, because
1127     // it is tied to the instruction itself, not the value or position.
1128     // Similarly strip attributes on call parameters that may cause UB in
1129     // location the call is moved to.
1130     NewBonusInst->dropUndefImplyingAttrsAndUnknownMetadata(
1131         LLVMContext::MD_annotation);
1132 
1133     PredBlock->getInstList().insert(PTI->getIterator(), NewBonusInst);
1134     NewBonusInst->takeName(&BonusInst);
1135     BonusInst.setName(NewBonusInst->getName() + ".old");
1136 
1137     // Update (liveout) uses of bonus instructions,
1138     // now that the bonus instruction has been cloned into predecessor.
1139     // Note that we expect to be in a block-closed SSA form for this to work!
1140     for (Use &U : make_early_inc_range(BonusInst.uses())) {
1141       auto *UI = cast<Instruction>(U.getUser());
1142       auto *PN = dyn_cast<PHINode>(UI);
1143       if (!PN) {
1144         assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1145                "If the user is not a PHI node, then it should be in the same "
1146                "block as, and come after, the original bonus instruction.");
1147         continue; // Keep using the original bonus instruction.
1148       }
1149       // Is this the block-closed SSA form PHI node?
1150       if (PN->getIncomingBlock(U) == BB)
1151         continue; // Great, keep using the original bonus instruction.
1152       // The only other alternative is an "use" when coming from
1153       // the predecessor block - here we should refer to the cloned bonus instr.
1154       assert(PN->getIncomingBlock(U) == PredBlock &&
1155              "Not in block-closed SSA form?");
1156       U.set(NewBonusInst);
1157     }
1158   }
1159 }
1160 
1161 bool SimplifyCFGOpt::PerformValueComparisonIntoPredecessorFolding(
1162     Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1163   BasicBlock *BB = TI->getParent();
1164   BasicBlock *Pred = PTI->getParent();
1165 
1166   SmallVector<DominatorTree::UpdateType, 32> Updates;
1167 
1168   // Figure out which 'cases' to copy from SI to PSI.
1169   std::vector<ValueEqualityComparisonCase> BBCases;
1170   BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1171 
1172   std::vector<ValueEqualityComparisonCase> PredCases;
1173   BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1174 
1175   // Based on whether the default edge from PTI goes to BB or not, fill in
1176   // PredCases and PredDefault with the new switch cases we would like to
1177   // build.
1178   SmallMapVector<BasicBlock *, int, 8> NewSuccessors;
1179 
1180   // Update the branch weight metadata along the way
1181   SmallVector<uint64_t, 8> Weights;
1182   bool PredHasWeights = HasBranchWeights(PTI);
1183   bool SuccHasWeights = HasBranchWeights(TI);
1184 
1185   if (PredHasWeights) {
1186     GetBranchWeights(PTI, Weights);
1187     // branch-weight metadata is inconsistent here.
1188     if (Weights.size() != 1 + PredCases.size())
1189       PredHasWeights = SuccHasWeights = false;
1190   } else if (SuccHasWeights)
1191     // If there are no predecessor weights but there are successor weights,
1192     // populate Weights with 1, which will later be scaled to the sum of
1193     // successor's weights
1194     Weights.assign(1 + PredCases.size(), 1);
1195 
1196   SmallVector<uint64_t, 8> SuccWeights;
1197   if (SuccHasWeights) {
1198     GetBranchWeights(TI, SuccWeights);
1199     // branch-weight metadata is inconsistent here.
1200     if (SuccWeights.size() != 1 + BBCases.size())
1201       PredHasWeights = SuccHasWeights = false;
1202   } else if (PredHasWeights)
1203     SuccWeights.assign(1 + BBCases.size(), 1);
1204 
1205   if (PredDefault == BB) {
1206     // If this is the default destination from PTI, only the edges in TI
1207     // that don't occur in PTI, or that branch to BB will be activated.
1208     std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1209     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1210       if (PredCases[i].Dest != BB)
1211         PTIHandled.insert(PredCases[i].Value);
1212       else {
1213         // The default destination is BB, we don't need explicit targets.
1214         std::swap(PredCases[i], PredCases.back());
1215 
1216         if (PredHasWeights || SuccHasWeights) {
1217           // Increase weight for the default case.
1218           Weights[0] += Weights[i + 1];
1219           std::swap(Weights[i + 1], Weights.back());
1220           Weights.pop_back();
1221         }
1222 
1223         PredCases.pop_back();
1224         --i;
1225         --e;
1226       }
1227 
1228     // Reconstruct the new switch statement we will be building.
1229     if (PredDefault != BBDefault) {
1230       PredDefault->removePredecessor(Pred);
1231       if (DTU && PredDefault != BB)
1232         Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1233       PredDefault = BBDefault;
1234       ++NewSuccessors[BBDefault];
1235     }
1236 
1237     unsigned CasesFromPred = Weights.size();
1238     uint64_t ValidTotalSuccWeight = 0;
1239     for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1240       if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1241         PredCases.push_back(BBCases[i]);
1242         ++NewSuccessors[BBCases[i].Dest];
1243         if (SuccHasWeights || PredHasWeights) {
1244           // The default weight is at index 0, so weight for the ith case
1245           // should be at index i+1. Scale the cases from successor by
1246           // PredDefaultWeight (Weights[0]).
1247           Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1248           ValidTotalSuccWeight += SuccWeights[i + 1];
1249         }
1250       }
1251 
1252     if (SuccHasWeights || PredHasWeights) {
1253       ValidTotalSuccWeight += SuccWeights[0];
1254       // Scale the cases from predecessor by ValidTotalSuccWeight.
1255       for (unsigned i = 1; i < CasesFromPred; ++i)
1256         Weights[i] *= ValidTotalSuccWeight;
1257       // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1258       Weights[0] *= SuccWeights[0];
1259     }
1260   } else {
1261     // If this is not the default destination from PSI, only the edges
1262     // in SI that occur in PSI with a destination of BB will be
1263     // activated.
1264     std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1265     std::map<ConstantInt *, uint64_t> WeightsForHandled;
1266     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1267       if (PredCases[i].Dest == BB) {
1268         PTIHandled.insert(PredCases[i].Value);
1269 
1270         if (PredHasWeights || SuccHasWeights) {
1271           WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1272           std::swap(Weights[i + 1], Weights.back());
1273           Weights.pop_back();
1274         }
1275 
1276         std::swap(PredCases[i], PredCases.back());
1277         PredCases.pop_back();
1278         --i;
1279         --e;
1280       }
1281 
1282     // Okay, now we know which constants were sent to BB from the
1283     // predecessor.  Figure out where they will all go now.
1284     for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1285       if (PTIHandled.count(BBCases[i].Value)) {
1286         // If this is one we are capable of getting...
1287         if (PredHasWeights || SuccHasWeights)
1288           Weights.push_back(WeightsForHandled[BBCases[i].Value]);
1289         PredCases.push_back(BBCases[i]);
1290         ++NewSuccessors[BBCases[i].Dest];
1291         PTIHandled.erase(BBCases[i].Value); // This constant is taken care of
1292       }
1293 
1294     // If there are any constants vectored to BB that TI doesn't handle,
1295     // they must go to the default destination of TI.
1296     for (ConstantInt *I : PTIHandled) {
1297       if (PredHasWeights || SuccHasWeights)
1298         Weights.push_back(WeightsForHandled[I]);
1299       PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1300       ++NewSuccessors[BBDefault];
1301     }
1302   }
1303 
1304   // Okay, at this point, we know which new successor Pred will get.  Make
1305   // sure we update the number of entries in the PHI nodes for these
1306   // successors.
1307   SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1308   if (DTU) {
1309     SuccsOfPred = {succ_begin(Pred), succ_end(Pred)};
1310     Updates.reserve(Updates.size() + NewSuccessors.size());
1311   }
1312   for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1313        NewSuccessors) {
1314     for (auto I : seq(0, NewSuccessor.second)) {
1315       (void)I;
1316       AddPredecessorToBlock(NewSuccessor.first, Pred, BB);
1317     }
1318     if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1319       Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1320   }
1321 
1322   Builder.SetInsertPoint(PTI);
1323   // Convert pointer to int before we switch.
1324   if (CV->getType()->isPointerTy()) {
1325     CV =
1326         Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1327   }
1328 
1329   // Now that the successors are updated, create the new Switch instruction.
1330   SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1331   NewSI->setDebugLoc(PTI->getDebugLoc());
1332   for (ValueEqualityComparisonCase &V : PredCases)
1333     NewSI->addCase(V.Value, V.Dest);
1334 
1335   if (PredHasWeights || SuccHasWeights) {
1336     // Halve the weights if any of them cannot fit in an uint32_t
1337     FitWeights(Weights);
1338 
1339     SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1340 
1341     setBranchWeights(NewSI, MDWeights);
1342   }
1343 
1344   EraseTerminatorAndDCECond(PTI);
1345 
1346   // Okay, last check.  If BB is still a successor of PSI, then we must
1347   // have an infinite loop case.  If so, add an infinitely looping block
1348   // to handle the case to preserve the behavior of the code.
1349   BasicBlock *InfLoopBlock = nullptr;
1350   for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1351     if (NewSI->getSuccessor(i) == BB) {
1352       if (!InfLoopBlock) {
1353         // Insert it at the end of the function, because it's either code,
1354         // or it won't matter if it's hot. :)
1355         InfLoopBlock =
1356             BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1357         BranchInst::Create(InfLoopBlock, InfLoopBlock);
1358         if (DTU)
1359           Updates.push_back(
1360               {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1361       }
1362       NewSI->setSuccessor(i, InfLoopBlock);
1363     }
1364 
1365   if (DTU) {
1366     if (InfLoopBlock)
1367       Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1368 
1369     Updates.push_back({DominatorTree::Delete, Pred, BB});
1370 
1371     DTU->applyUpdates(Updates);
1372   }
1373 
1374   ++NumFoldValueComparisonIntoPredecessors;
1375   return true;
1376 }
1377 
1378 /// The specified terminator is a value equality comparison instruction
1379 /// (either a switch or a branch on "X == c").
1380 /// See if any of the predecessors of the terminator block are value comparisons
1381 /// on the same value.  If so, and if safe to do so, fold them together.
1382 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
1383                                                          IRBuilder<> &Builder) {
1384   BasicBlock *BB = TI->getParent();
1385   Value *CV = isValueEqualityComparison(TI); // CondVal
1386   assert(CV && "Not a comparison?");
1387 
1388   bool Changed = false;
1389 
1390   SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1391   while (!Preds.empty()) {
1392     BasicBlock *Pred = Preds.pop_back_val();
1393     Instruction *PTI = Pred->getTerminator();
1394 
1395     // Don't try to fold into itself.
1396     if (Pred == BB)
1397       continue;
1398 
1399     // See if the predecessor is a comparison with the same value.
1400     Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1401     if (PCV != CV)
1402       continue;
1403 
1404     SmallSetVector<BasicBlock *, 4> FailBlocks;
1405     if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
1406       for (auto *Succ : FailBlocks) {
1407         if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1408           return false;
1409       }
1410     }
1411 
1412     PerformValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1413     Changed = true;
1414   }
1415   return Changed;
1416 }
1417 
1418 // If we would need to insert a select that uses the value of this invoke
1419 // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1420 // can't hoist the invoke, as there is nowhere to put the select in this case.
1421 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1422                                 Instruction *I1, Instruction *I2) {
1423   for (BasicBlock *Succ : successors(BB1)) {
1424     for (const PHINode &PN : Succ->phis()) {
1425       Value *BB1V = PN.getIncomingValueForBlock(BB1);
1426       Value *BB2V = PN.getIncomingValueForBlock(BB2);
1427       if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1428         return false;
1429       }
1430     }
1431   }
1432   return true;
1433 }
1434 
1435 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1436 
1437 /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1438 /// in the two blocks up into the branch block. The caller of this function
1439 /// guarantees that BI's block dominates BB1 and BB2. If EqTermsOnly is given,
1440 /// only perform hoisting in case both blocks only contain a terminator. In that
1441 /// case, only the original BI will be replaced and selects for PHIs are added.
1442 bool SimplifyCFGOpt::HoistThenElseCodeToIf(BranchInst *BI,
1443                                            const TargetTransformInfo &TTI,
1444                                            bool EqTermsOnly) {
1445   // This does very trivial matching, with limited scanning, to find identical
1446   // instructions in the two blocks.  In particular, we don't want to get into
1447   // O(M*N) situations here where M and N are the sizes of BB1 and BB2.  As
1448   // such, we currently just scan for obviously identical instructions in an
1449   // identical order.
1450   BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1451   BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1452 
1453   // If either of the blocks has it's address taken, then we can't do this fold,
1454   // because the code we'd hoist would no longer run when we jump into the block
1455   // by it's address.
1456   if (BB1->hasAddressTaken() || BB2->hasAddressTaken())
1457     return false;
1458 
1459   BasicBlock::iterator BB1_Itr = BB1->begin();
1460   BasicBlock::iterator BB2_Itr = BB2->begin();
1461 
1462   Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
1463   // Skip debug info if it is not identical.
1464   DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1465   DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1466   if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1467     while (isa<DbgInfoIntrinsic>(I1))
1468       I1 = &*BB1_Itr++;
1469     while (isa<DbgInfoIntrinsic>(I2))
1470       I2 = &*BB2_Itr++;
1471   }
1472   // FIXME: Can we define a safety predicate for CallBr?
1473   if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1474       (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) ||
1475       isa<CallBrInst>(I1))
1476     return false;
1477 
1478   BasicBlock *BIParent = BI->getParent();
1479 
1480   bool Changed = false;
1481 
1482   auto _ = make_scope_exit([&]() {
1483     if (Changed)
1484       ++NumHoistCommonCode;
1485   });
1486 
1487   // Check if only hoisting terminators is allowed. This does not add new
1488   // instructions to the hoist location.
1489   if (EqTermsOnly) {
1490     // Skip any debug intrinsics, as they are free to hoist.
1491     auto *I1NonDbg = &*skipDebugIntrinsics(I1->getIterator());
1492     auto *I2NonDbg = &*skipDebugIntrinsics(I2->getIterator());
1493     if (!I1NonDbg->isIdenticalToWhenDefined(I2NonDbg))
1494       return false;
1495     if (!I1NonDbg->isTerminator())
1496       return false;
1497     // Now we know that we only need to hoist debug intrinsics and the
1498     // terminator. Let the loop below handle those 2 cases.
1499   }
1500 
1501   do {
1502     // If we are hoisting the terminator instruction, don't move one (making a
1503     // broken BB), instead clone it, and remove BI.
1504     if (I1->isTerminator())
1505       goto HoistTerminator;
1506 
1507     // If we're going to hoist a call, make sure that the two instructions we're
1508     // commoning/hoisting are both marked with musttail, or neither of them is
1509     // marked as such. Otherwise, we might end up in a situation where we hoist
1510     // from a block where the terminator is a `ret` to a block where the terminator
1511     // is a `br`, and `musttail` calls expect to be followed by a return.
1512     auto *C1 = dyn_cast<CallInst>(I1);
1513     auto *C2 = dyn_cast<CallInst>(I2);
1514     if (C1 && C2)
1515       if (C1->isMustTailCall() != C2->isMustTailCall())
1516         return Changed;
1517 
1518     if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1519       return Changed;
1520 
1521     // If any of the two call sites has nomerge attribute, stop hoisting.
1522     if (const auto *CB1 = dyn_cast<CallBase>(I1))
1523       if (CB1->cannotMerge())
1524         return Changed;
1525     if (const auto *CB2 = dyn_cast<CallBase>(I2))
1526       if (CB2->cannotMerge())
1527         return Changed;
1528 
1529     if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
1530       assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
1531       // The debug location is an integral part of a debug info intrinsic
1532       // and can't be separated from it or replaced.  Instead of attempting
1533       // to merge locations, simply hoist both copies of the intrinsic.
1534       BIParent->getInstList().splice(BI->getIterator(),
1535                                      BB1->getInstList(), I1);
1536       BIParent->getInstList().splice(BI->getIterator(),
1537                                      BB2->getInstList(), I2);
1538       Changed = true;
1539     } else {
1540       // For a normal instruction, we just move one to right before the branch,
1541       // then replace all uses of the other with the first.  Finally, we remove
1542       // the now redundant second instruction.
1543       BIParent->getInstList().splice(BI->getIterator(),
1544                                      BB1->getInstList(), I1);
1545       if (!I2->use_empty())
1546         I2->replaceAllUsesWith(I1);
1547       I1->andIRFlags(I2);
1548       unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1549                              LLVMContext::MD_range,
1550                              LLVMContext::MD_fpmath,
1551                              LLVMContext::MD_invariant_load,
1552                              LLVMContext::MD_nonnull,
1553                              LLVMContext::MD_invariant_group,
1554                              LLVMContext::MD_align,
1555                              LLVMContext::MD_dereferenceable,
1556                              LLVMContext::MD_dereferenceable_or_null,
1557                              LLVMContext::MD_mem_parallel_loop_access,
1558                              LLVMContext::MD_access_group,
1559                              LLVMContext::MD_preserve_access_index};
1560       combineMetadata(I1, I2, KnownIDs, true);
1561 
1562       // I1 and I2 are being combined into a single instruction.  Its debug
1563       // location is the merged locations of the original instructions.
1564       I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1565 
1566       I2->eraseFromParent();
1567       Changed = true;
1568     }
1569     ++NumHoistCommonInstrs;
1570 
1571     I1 = &*BB1_Itr++;
1572     I2 = &*BB2_Itr++;
1573     // Skip debug info if it is not identical.
1574     DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1575     DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1576     if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1577       while (isa<DbgInfoIntrinsic>(I1))
1578         I1 = &*BB1_Itr++;
1579       while (isa<DbgInfoIntrinsic>(I2))
1580         I2 = &*BB2_Itr++;
1581     }
1582   } while (I1->isIdenticalToWhenDefined(I2));
1583 
1584   return true;
1585 
1586 HoistTerminator:
1587   // It may not be possible to hoist an invoke.
1588   // FIXME: Can we define a safety predicate for CallBr?
1589   if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1590     return Changed;
1591 
1592   // TODO: callbr hoisting currently disabled pending further study.
1593   if (isa<CallBrInst>(I1))
1594     return Changed;
1595 
1596   for (BasicBlock *Succ : successors(BB1)) {
1597     for (PHINode &PN : Succ->phis()) {
1598       Value *BB1V = PN.getIncomingValueForBlock(BB1);
1599       Value *BB2V = PN.getIncomingValueForBlock(BB2);
1600       if (BB1V == BB2V)
1601         continue;
1602 
1603       // Check for passingValueIsAlwaysUndefined here because we would rather
1604       // eliminate undefined control flow then converting it to a select.
1605       if (passingValueIsAlwaysUndefined(BB1V, &PN) ||
1606           passingValueIsAlwaysUndefined(BB2V, &PN))
1607         return Changed;
1608 
1609       if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
1610         return Changed;
1611       if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
1612         return Changed;
1613     }
1614   }
1615 
1616   // Okay, it is safe to hoist the terminator.
1617   Instruction *NT = I1->clone();
1618   BIParent->getInstList().insert(BI->getIterator(), NT);
1619   if (!NT->getType()->isVoidTy()) {
1620     I1->replaceAllUsesWith(NT);
1621     I2->replaceAllUsesWith(NT);
1622     NT->takeName(I1);
1623   }
1624   Changed = true;
1625   ++NumHoistCommonInstrs;
1626 
1627   // Ensure terminator gets a debug location, even an unknown one, in case
1628   // it involves inlinable calls.
1629   NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1630 
1631   // PHIs created below will adopt NT's merged DebugLoc.
1632   IRBuilder<NoFolder> Builder(NT);
1633 
1634   // Hoisting one of the terminators from our successor is a great thing.
1635   // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1636   // them.  If they do, all PHI entries for BB1/BB2 must agree for all PHI
1637   // nodes, so we insert select instruction to compute the final result.
1638   std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
1639   for (BasicBlock *Succ : successors(BB1)) {
1640     for (PHINode &PN : Succ->phis()) {
1641       Value *BB1V = PN.getIncomingValueForBlock(BB1);
1642       Value *BB2V = PN.getIncomingValueForBlock(BB2);
1643       if (BB1V == BB2V)
1644         continue;
1645 
1646       // These values do not agree.  Insert a select instruction before NT
1647       // that determines the right value.
1648       SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1649       if (!SI) {
1650         // Propagate fast-math-flags from phi node to its replacement select.
1651         IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
1652         if (isa<FPMathOperator>(PN))
1653           Builder.setFastMathFlags(PN.getFastMathFlags());
1654 
1655         SI = cast<SelectInst>(
1656             Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1657                                  BB1V->getName() + "." + BB2V->getName(), BI));
1658       }
1659 
1660       // Make the PHI node use the select for all incoming values for BB1/BB2
1661       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1662         if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1663           PN.setIncomingValue(i, SI);
1664     }
1665   }
1666 
1667   SmallVector<DominatorTree::UpdateType, 4> Updates;
1668 
1669   // Update any PHI nodes in our new successors.
1670   for (BasicBlock *Succ : successors(BB1)) {
1671     AddPredecessorToBlock(Succ, BIParent, BB1);
1672     if (DTU)
1673       Updates.push_back({DominatorTree::Insert, BIParent, Succ});
1674   }
1675 
1676   if (DTU)
1677     for (BasicBlock *Succ : successors(BI))
1678       Updates.push_back({DominatorTree::Delete, BIParent, Succ});
1679 
1680   EraseTerminatorAndDCECond(BI);
1681   if (DTU)
1682     DTU->applyUpdates(Updates);
1683   return Changed;
1684 }
1685 
1686 // Check lifetime markers.
1687 static bool isLifeTimeMarker(const Instruction *I) {
1688   if (auto II = dyn_cast<IntrinsicInst>(I)) {
1689     switch (II->getIntrinsicID()) {
1690     default:
1691       break;
1692     case Intrinsic::lifetime_start:
1693     case Intrinsic::lifetime_end:
1694       return true;
1695     }
1696   }
1697   return false;
1698 }
1699 
1700 // TODO: Refine this. This should avoid cases like turning constant memcpy sizes
1701 // into variables.
1702 static bool replacingOperandWithVariableIsCheap(const Instruction *I,
1703                                                 int OpIdx) {
1704   return !isa<IntrinsicInst>(I);
1705 }
1706 
1707 // All instructions in Insts belong to different blocks that all unconditionally
1708 // branch to a common successor. Analyze each instruction and return true if it
1709 // would be possible to sink them into their successor, creating one common
1710 // instruction instead. For every value that would be required to be provided by
1711 // PHI node (because an operand varies in each input block), add to PHIOperands.
1712 static bool canSinkInstructions(
1713     ArrayRef<Instruction *> Insts,
1714     DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
1715   // Prune out obviously bad instructions to move. Each instruction must have
1716   // exactly zero or one use, and we check later that use is by a single, common
1717   // PHI instruction in the successor.
1718   bool HasUse = !Insts.front()->user_empty();
1719   for (auto *I : Insts) {
1720     // These instructions may change or break semantics if moved.
1721     if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1722         I->getType()->isTokenTy())
1723       return false;
1724 
1725     // Do not try to sink an instruction in an infinite loop - it can cause
1726     // this algorithm to infinite loop.
1727     if (I->getParent()->getSingleSuccessor() == I->getParent())
1728       return false;
1729 
1730     // Conservatively return false if I is an inline-asm instruction. Sinking
1731     // and merging inline-asm instructions can potentially create arguments
1732     // that cannot satisfy the inline-asm constraints.
1733     // If the instruction has nomerge attribute, return false.
1734     if (const auto *C = dyn_cast<CallBase>(I))
1735       if (C->isInlineAsm() || C->cannotMerge())
1736         return false;
1737 
1738     // Each instruction must have zero or one use.
1739     if (HasUse && !I->hasOneUse())
1740       return false;
1741     if (!HasUse && !I->user_empty())
1742       return false;
1743   }
1744 
1745   const Instruction *I0 = Insts.front();
1746   for (auto *I : Insts)
1747     if (!I->isSameOperationAs(I0))
1748       return false;
1749 
1750   // All instructions in Insts are known to be the same opcode. If they have a
1751   // use, check that the only user is a PHI or in the same block as the
1752   // instruction, because if a user is in the same block as an instruction we're
1753   // contemplating sinking, it must already be determined to be sinkable.
1754   if (HasUse) {
1755     auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1756     auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
1757     if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
1758           auto *U = cast<Instruction>(*I->user_begin());
1759           return (PNUse &&
1760                   PNUse->getParent() == Succ &&
1761                   PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1762                  U->getParent() == I->getParent();
1763         }))
1764       return false;
1765   }
1766 
1767   // Because SROA can't handle speculating stores of selects, try not to sink
1768   // loads, stores or lifetime markers of allocas when we'd have to create a
1769   // PHI for the address operand. Also, because it is likely that loads or
1770   // stores of allocas will disappear when Mem2Reg/SROA is run, don't sink
1771   // them.
1772   // This can cause code churn which can have unintended consequences down
1773   // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1774   // FIXME: This is a workaround for a deficiency in SROA - see
1775   // https://llvm.org/bugs/show_bug.cgi?id=30188
1776   if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1777         return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1778       }))
1779     return false;
1780   if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1781         return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts());
1782       }))
1783     return false;
1784   if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) {
1785         return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1786       }))
1787     return false;
1788 
1789   // For calls to be sinkable, they must all be indirect, or have same callee.
1790   // I.e. if we have two direct calls to different callees, we don't want to
1791   // turn that into an indirect call. Likewise, if we have an indirect call,
1792   // and a direct call, we don't actually want to have a single indirect call.
1793   if (isa<CallBase>(I0)) {
1794     auto IsIndirectCall = [](const Instruction *I) {
1795       return cast<CallBase>(I)->isIndirectCall();
1796     };
1797     bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
1798     bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
1799     if (HaveIndirectCalls) {
1800       if (!AllCallsAreIndirect)
1801         return false;
1802     } else {
1803       // All callees must be identical.
1804       Value *Callee = nullptr;
1805       for (const Instruction *I : Insts) {
1806         Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
1807         if (!Callee)
1808           Callee = CurrCallee;
1809         else if (Callee != CurrCallee)
1810           return false;
1811       }
1812     }
1813   }
1814 
1815   for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1816     Value *Op = I0->getOperand(OI);
1817     if (Op->getType()->isTokenTy())
1818       // Don't touch any operand of token type.
1819       return false;
1820 
1821     auto SameAsI0 = [&I0, OI](const Instruction *I) {
1822       assert(I->getNumOperands() == I0->getNumOperands());
1823       return I->getOperand(OI) == I0->getOperand(OI);
1824     };
1825     if (!all_of(Insts, SameAsI0)) {
1826       if ((isa<Constant>(Op) && !replacingOperandWithVariableIsCheap(I0, OI)) ||
1827           !canReplaceOperandWithVariable(I0, OI))
1828         // We can't create a PHI from this GEP.
1829         return false;
1830       for (auto *I : Insts)
1831         PHIOperands[I].push_back(I->getOperand(OI));
1832     }
1833   }
1834   return true;
1835 }
1836 
1837 // Assuming canSinkInstructions(Blocks) has returned true, sink the last
1838 // instruction of every block in Blocks to their common successor, commoning
1839 // into one instruction.
1840 static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
1841   auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1842 
1843   // canSinkInstructions returning true guarantees that every block has at
1844   // least one non-terminator instruction.
1845   SmallVector<Instruction*,4> Insts;
1846   for (auto *BB : Blocks) {
1847     Instruction *I = BB->getTerminator();
1848     do {
1849       I = I->getPrevNode();
1850     } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1851     if (!isa<DbgInfoIntrinsic>(I))
1852       Insts.push_back(I);
1853   }
1854 
1855   // The only checking we need to do now is that all users of all instructions
1856   // are the same PHI node. canSinkInstructions should have checked this but
1857   // it is slightly over-aggressive - it gets confused by commutative
1858   // instructions so double-check it here.
1859   Instruction *I0 = Insts.front();
1860   if (!I0->user_empty()) {
1861     auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1862     if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1863           auto *U = cast<Instruction>(*I->user_begin());
1864           return U == PNUse;
1865         }))
1866       return false;
1867   }
1868 
1869   // We don't need to do any more checking here; canSinkInstructions should
1870   // have done it all for us.
1871   SmallVector<Value*, 4> NewOperands;
1872   for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1873     // This check is different to that in canSinkInstructions. There, we
1874     // cared about the global view once simplifycfg (and instcombine) have
1875     // completed - it takes into account PHIs that become trivially
1876     // simplifiable.  However here we need a more local view; if an operand
1877     // differs we create a PHI and rely on instcombine to clean up the very
1878     // small mess we may make.
1879     bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1880       return I->getOperand(O) != I0->getOperand(O);
1881     });
1882     if (!NeedPHI) {
1883       NewOperands.push_back(I0->getOperand(O));
1884       continue;
1885     }
1886 
1887     // Create a new PHI in the successor block and populate it.
1888     auto *Op = I0->getOperand(O);
1889     assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1890     auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1891                                Op->getName() + ".sink", &BBEnd->front());
1892     for (auto *I : Insts)
1893       PN->addIncoming(I->getOperand(O), I->getParent());
1894     NewOperands.push_back(PN);
1895   }
1896 
1897   // Arbitrarily use I0 as the new "common" instruction; remap its operands
1898   // and move it to the start of the successor block.
1899   for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1900     I0->getOperandUse(O).set(NewOperands[O]);
1901   I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1902 
1903   // Update metadata and IR flags, and merge debug locations.
1904   for (auto *I : Insts)
1905     if (I != I0) {
1906       // The debug location for the "common" instruction is the merged locations
1907       // of all the commoned instructions.  We start with the original location
1908       // of the "common" instruction and iteratively merge each location in the
1909       // loop below.
1910       // This is an N-way merge, which will be inefficient if I0 is a CallInst.
1911       // However, as N-way merge for CallInst is rare, so we use simplified API
1912       // instead of using complex API for N-way merge.
1913       I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
1914       combineMetadataForCSE(I0, I, true);
1915       I0->andIRFlags(I);
1916     }
1917 
1918   if (!I0->user_empty()) {
1919     // canSinkLastInstruction checked that all instructions were used by
1920     // one and only one PHI node. Find that now, RAUW it to our common
1921     // instruction and nuke it.
1922     auto *PN = cast<PHINode>(*I0->user_begin());
1923     PN->replaceAllUsesWith(I0);
1924     PN->eraseFromParent();
1925   }
1926 
1927   // Finally nuke all instructions apart from the common instruction.
1928   for (auto *I : Insts)
1929     if (I != I0)
1930       I->eraseFromParent();
1931 
1932   return true;
1933 }
1934 
1935 namespace {
1936 
1937   // LockstepReverseIterator - Iterates through instructions
1938   // in a set of blocks in reverse order from the first non-terminator.
1939   // For example (assume all blocks have size n):
1940   //   LockstepReverseIterator I([B1, B2, B3]);
1941   //   *I-- = [B1[n], B2[n], B3[n]];
1942   //   *I-- = [B1[n-1], B2[n-1], B3[n-1]];
1943   //   *I-- = [B1[n-2], B2[n-2], B3[n-2]];
1944   //   ...
1945   class LockstepReverseIterator {
1946     ArrayRef<BasicBlock*> Blocks;
1947     SmallVector<Instruction*,4> Insts;
1948     bool Fail;
1949 
1950   public:
1951     LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
1952       reset();
1953     }
1954 
1955     void reset() {
1956       Fail = false;
1957       Insts.clear();
1958       for (auto *BB : Blocks) {
1959         Instruction *Inst = BB->getTerminator();
1960         for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1961           Inst = Inst->getPrevNode();
1962         if (!Inst) {
1963           // Block wasn't big enough.
1964           Fail = true;
1965           return;
1966         }
1967         Insts.push_back(Inst);
1968       }
1969     }
1970 
1971     bool isValid() const {
1972       return !Fail;
1973     }
1974 
1975     void operator--() {
1976       if (Fail)
1977         return;
1978       for (auto *&Inst : Insts) {
1979         for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1980           Inst = Inst->getPrevNode();
1981         // Already at beginning of block.
1982         if (!Inst) {
1983           Fail = true;
1984           return;
1985         }
1986       }
1987     }
1988 
1989     void operator++() {
1990       if (Fail)
1991         return;
1992       for (auto *&Inst : Insts) {
1993         for (Inst = Inst->getNextNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1994           Inst = Inst->getNextNode();
1995         // Already at end of block.
1996         if (!Inst) {
1997           Fail = true;
1998           return;
1999         }
2000       }
2001     }
2002 
2003     ArrayRef<Instruction*> operator * () const {
2004       return Insts;
2005     }
2006   };
2007 
2008 } // end anonymous namespace
2009 
2010 /// Check whether BB's predecessors end with unconditional branches. If it is
2011 /// true, sink any common code from the predecessors to BB.
2012 static bool SinkCommonCodeFromPredecessors(BasicBlock *BB,
2013                                            DomTreeUpdater *DTU) {
2014   // We support two situations:
2015   //   (1) all incoming arcs are unconditional
2016   //   (2) there are non-unconditional incoming arcs
2017   //
2018   // (2) is very common in switch defaults and
2019   // else-if patterns;
2020   //
2021   //   if (a) f(1);
2022   //   else if (b) f(2);
2023   //
2024   // produces:
2025   //
2026   //       [if]
2027   //      /    \
2028   //    [f(1)] [if]
2029   //      |     | \
2030   //      |     |  |
2031   //      |  [f(2)]|
2032   //       \    | /
2033   //        [ end ]
2034   //
2035   // [end] has two unconditional predecessor arcs and one conditional. The
2036   // conditional refers to the implicit empty 'else' arc. This conditional
2037   // arc can also be caused by an empty default block in a switch.
2038   //
2039   // In this case, we attempt to sink code from all *unconditional* arcs.
2040   // If we can sink instructions from these arcs (determined during the scan
2041   // phase below) we insert a common successor for all unconditional arcs and
2042   // connect that to [end], to enable sinking:
2043   //
2044   //       [if]
2045   //      /    \
2046   //    [x(1)] [if]
2047   //      |     | \
2048   //      |     |  \
2049   //      |  [x(2)] |
2050   //       \   /    |
2051   //   [sink.split] |
2052   //         \     /
2053   //         [ end ]
2054   //
2055   SmallVector<BasicBlock*,4> UnconditionalPreds;
2056   bool HaveNonUnconditionalPredecessors = false;
2057   for (auto *PredBB : predecessors(BB)) {
2058     auto *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
2059     if (PredBr && PredBr->isUnconditional())
2060       UnconditionalPreds.push_back(PredBB);
2061     else
2062       HaveNonUnconditionalPredecessors = true;
2063   }
2064   if (UnconditionalPreds.size() < 2)
2065     return false;
2066 
2067   // We take a two-step approach to tail sinking. First we scan from the end of
2068   // each block upwards in lockstep. If the n'th instruction from the end of each
2069   // block can be sunk, those instructions are added to ValuesToSink and we
2070   // carry on. If we can sink an instruction but need to PHI-merge some operands
2071   // (because they're not identical in each instruction) we add these to
2072   // PHIOperands.
2073   int ScanIdx = 0;
2074   SmallPtrSet<Value*,4> InstructionsToSink;
2075   DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
2076   LockstepReverseIterator LRI(UnconditionalPreds);
2077   while (LRI.isValid() &&
2078          canSinkInstructions(*LRI, PHIOperands)) {
2079     LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2080                       << "\n");
2081     InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
2082     ++ScanIdx;
2083     --LRI;
2084   }
2085 
2086   // If no instructions can be sunk, early-return.
2087   if (ScanIdx == 0)
2088     return false;
2089 
2090   bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2091 
2092   if (!followedByDeoptOrUnreachable) {
2093     // Okay, we *could* sink last ScanIdx instructions. But how many can we
2094     // actually sink before encountering instruction that is unprofitable to
2095     // sink?
2096     auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
2097       unsigned NumPHIdValues = 0;
2098       for (auto *I : *LRI)
2099         for (auto *V : PHIOperands[I]) {
2100           if (!InstructionsToSink.contains(V))
2101             ++NumPHIdValues;
2102           // FIXME: this check is overly optimistic. We may end up not sinking
2103           // said instruction, due to the very same profitability check.
2104           // See @creating_too_many_phis in sink-common-code.ll.
2105         }
2106       LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
2107       unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
2108       if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
2109         NumPHIInsts++;
2110 
2111       return NumPHIInsts <= 1;
2112     };
2113 
2114     // We've determined that we are going to sink last ScanIdx instructions,
2115     // and recorded them in InstructionsToSink. Now, some instructions may be
2116     // unprofitable to sink. But that determination depends on the instructions
2117     // that we are going to sink.
2118 
2119     // First, forward scan: find the first instruction unprofitable to sink,
2120     // recording all the ones that are profitable to sink.
2121     // FIXME: would it be better, after we detect that not all are profitable.
2122     // to either record the profitable ones, or erase the unprofitable ones?
2123     // Maybe we need to choose (at runtime) the one that will touch least
2124     // instrs?
2125     LRI.reset();
2126     int Idx = 0;
2127     SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2128     while (Idx < ScanIdx) {
2129       if (!ProfitableToSinkInstruction(LRI)) {
2130         // Too many PHIs would be created.
2131         LLVM_DEBUG(
2132             dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2133         break;
2134       }
2135       InstructionsProfitableToSink.insert((*LRI).begin(), (*LRI).end());
2136       --LRI;
2137       ++Idx;
2138     }
2139 
2140     // If no instructions can be sunk, early-return.
2141     if (Idx == 0)
2142       return false;
2143 
2144     // Did we determine that (only) some instructions are unprofitable to sink?
2145     if (Idx < ScanIdx) {
2146       // Okay, some instructions are unprofitable.
2147       ScanIdx = Idx;
2148       InstructionsToSink = InstructionsProfitableToSink;
2149 
2150       // But, that may make other instructions unprofitable, too.
2151       // So, do a backward scan, do any earlier instructions become
2152       // unprofitable?
2153       assert(
2154           !ProfitableToSinkInstruction(LRI) &&
2155           "We already know that the last instruction is unprofitable to sink");
2156       ++LRI;
2157       --Idx;
2158       while (Idx >= 0) {
2159         // If we detect that an instruction becomes unprofitable to sink,
2160         // all earlier instructions won't be sunk either,
2161         // so preemptively keep InstructionsProfitableToSink in sync.
2162         // FIXME: is this the most performant approach?
2163         for (auto *I : *LRI)
2164           InstructionsProfitableToSink.erase(I);
2165         if (!ProfitableToSinkInstruction(LRI)) {
2166           // Everything starting with this instruction won't be sunk.
2167           ScanIdx = Idx;
2168           InstructionsToSink = InstructionsProfitableToSink;
2169         }
2170         ++LRI;
2171         --Idx;
2172       }
2173     }
2174 
2175     // If no instructions can be sunk, early-return.
2176     if (ScanIdx == 0)
2177       return false;
2178   }
2179 
2180   bool Changed = false;
2181 
2182   if (HaveNonUnconditionalPredecessors) {
2183     if (!followedByDeoptOrUnreachable) {
2184       // It is always legal to sink common instructions from unconditional
2185       // predecessors. However, if not all predecessors are unconditional,
2186       // this transformation might be pessimizing. So as a rule of thumb,
2187       // don't do it unless we'd sink at least one non-speculatable instruction.
2188       // See https://bugs.llvm.org/show_bug.cgi?id=30244
2189       LRI.reset();
2190       int Idx = 0;
2191       bool Profitable = false;
2192       while (Idx < ScanIdx) {
2193         if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2194           Profitable = true;
2195           break;
2196         }
2197         --LRI;
2198         ++Idx;
2199       }
2200       if (!Profitable)
2201         return false;
2202     }
2203 
2204     LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2205     // We have a conditional edge and we're going to sink some instructions.
2206     // Insert a new block postdominating all blocks we're going to sink from.
2207     if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2208       // Edges couldn't be split.
2209       return false;
2210     Changed = true;
2211   }
2212 
2213   // Now that we've analyzed all potential sinking candidates, perform the
2214   // actual sink. We iteratively sink the last non-terminator of the source
2215   // blocks into their common successor unless doing so would require too
2216   // many PHI instructions to be generated (currently only one PHI is allowed
2217   // per sunk instruction).
2218   //
2219   // We can use InstructionsToSink to discount values needing PHI-merging that will
2220   // actually be sunk in a later iteration. This allows us to be more
2221   // aggressive in what we sink. This does allow a false positive where we
2222   // sink presuming a later value will also be sunk, but stop half way through
2223   // and never actually sink it which means we produce more PHIs than intended.
2224   // This is unlikely in practice though.
2225   int SinkIdx = 0;
2226   for (; SinkIdx != ScanIdx; ++SinkIdx) {
2227     LLVM_DEBUG(dbgs() << "SINK: Sink: "
2228                       << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2229                       << "\n");
2230 
2231     // Because we've sunk every instruction in turn, the current instruction to
2232     // sink is always at index 0.
2233     LRI.reset();
2234 
2235     if (!sinkLastInstruction(UnconditionalPreds)) {
2236       LLVM_DEBUG(
2237           dbgs()
2238           << "SINK: stopping here, failed to actually sink instruction!\n");
2239       break;
2240     }
2241 
2242     NumSinkCommonInstrs++;
2243     Changed = true;
2244   }
2245   if (SinkIdx != 0)
2246     ++NumSinkCommonCode;
2247   return Changed;
2248 }
2249 
2250 namespace {
2251 
2252 struct CompatibleSets {
2253   using SetTy = SmallVector<InvokeInst *, 2>;
2254 
2255   SmallVector<SetTy, 1> Sets;
2256 
2257   static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2258 
2259   SetTy &getCompatibleSet(InvokeInst *II);
2260 
2261   void insert(InvokeInst *II);
2262 };
2263 
2264 CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2265   // Perform a linear scan over all the existing sets, see if the new `invoke`
2266   // is compatible with any particular set. Since we know that all the `invokes`
2267   // within a set are compatible, only check the first `invoke` in each set.
2268   // WARNING: at worst, this has quadratic complexity.
2269   for (CompatibleSets::SetTy &Set : Sets) {
2270     if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2271       return Set;
2272   }
2273 
2274   // Otherwise, we either had no sets yet, or this invoke forms a new set.
2275   return Sets.emplace_back();
2276 }
2277 
2278 void CompatibleSets::insert(InvokeInst *II) {
2279   getCompatibleSet(II).emplace_back(II);
2280 }
2281 
2282 bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2283   assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2284 
2285   // Can we theoretically merge these `invoke`s?
2286   auto IsIllegalToMerge = [](InvokeInst *II) {
2287     return II->cannotMerge() || II->isInlineAsm();
2288   };
2289   if (any_of(Invokes, IsIllegalToMerge))
2290     return false;
2291 
2292   // Either both `invoke`s must be   direct,
2293   // or     both `invoke`s must be indirect.
2294   auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2295   bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2296   bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2297   if (HaveIndirectCalls) {
2298     if (!AllCallsAreIndirect)
2299       return false;
2300   } else {
2301     // All callees must be identical.
2302     Value *Callee = nullptr;
2303     for (InvokeInst *II : Invokes) {
2304       Value *CurrCallee = II->getCalledOperand();
2305       assert(CurrCallee && "There is always a called operand.");
2306       if (!Callee)
2307         Callee = CurrCallee;
2308       else if (Callee != CurrCallee)
2309         return false;
2310     }
2311   }
2312 
2313   // Either both `invoke`s must not have a normal destination,
2314   // or     both `invoke`s must     have a normal destination,
2315   auto HasNormalDest = [](InvokeInst *II) {
2316     return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIOrDbg());
2317   };
2318   if (any_of(Invokes, HasNormalDest)) {
2319     // Do not merge `invoke` that does not have a normal destination with one
2320     // that does have a normal destination, even though doing so would be legal.
2321     if (!all_of(Invokes, HasNormalDest))
2322       return false;
2323 
2324     // All normal destinations must be identical.
2325     BasicBlock *NormalBB = nullptr;
2326     for (InvokeInst *II : Invokes) {
2327       BasicBlock *CurrNormalBB = II->getNormalDest();
2328       assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2329       if (!NormalBB)
2330         NormalBB = CurrNormalBB;
2331       else if (NormalBB != CurrNormalBB)
2332         return false;
2333     }
2334 
2335     // In the normal destination, the incoming values for these two `invoke`s
2336     // must be compatible.
2337     SmallPtrSet<Value *, 16> EquivalenceSet(Invokes.begin(), Invokes.end());
2338     if (!IncomingValuesAreCompatible(
2339             NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2340             &EquivalenceSet))
2341       return false;
2342   }
2343 
2344 #ifndef NDEBUG
2345   // All unwind destinations must be identical.
2346   // We know that because we have started from said unwind destination.
2347   BasicBlock *UnwindBB = nullptr;
2348   for (InvokeInst *II : Invokes) {
2349     BasicBlock *CurrUnwindBB = II->getUnwindDest();
2350     assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2351     if (!UnwindBB)
2352       UnwindBB = CurrUnwindBB;
2353     else
2354       assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2355   }
2356 #endif
2357 
2358   // In the unwind destination, the incoming values for these two `invoke`s
2359   // must be compatible.
2360   if (!IncomingValuesAreCompatible(
2361           Invokes.front()->getUnwindDest(),
2362           {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2363     return false;
2364 
2365   // Ignoring arguments, these `invoke`s must be identical,
2366   // including operand bundles.
2367   const InvokeInst *II0 = Invokes.front();
2368   for (auto *II : Invokes.drop_front())
2369     if (!II->isSameOperationAs(II0))
2370       return false;
2371 
2372   // Can we theoretically form the data operands for the merged `invoke`?
2373   auto IsIllegalToMergeArguments = [](auto Ops) {
2374     Type *Ty = std::get<0>(Ops)->getType();
2375     assert(Ty == std::get<1>(Ops)->getType() && "Incompatible types?");
2376     return Ty->isTokenTy() && std::get<0>(Ops) != std::get<1>(Ops);
2377   };
2378   assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2379   if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2380              IsIllegalToMergeArguments))
2381     return false;
2382 
2383   return true;
2384 }
2385 
2386 } // namespace
2387 
2388 // Merge all invokes in the provided set, all of which are compatible
2389 // as per the `CompatibleSets::shouldBelongToSameSet()`.
2390 static void MergeCompatibleInvokesImpl(ArrayRef<InvokeInst *> Invokes,
2391                                        DomTreeUpdater *DTU) {
2392   assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2393 
2394   SmallVector<DominatorTree::UpdateType, 8> Updates;
2395   if (DTU)
2396     Updates.reserve(2 + 3 * Invokes.size());
2397 
2398   bool HasNormalDest =
2399       !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIOrDbg());
2400 
2401   // Clone one of the invokes into a new basic block.
2402   // Since they are all compatible, it doesn't matter which invoke is cloned.
2403   InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2404     InvokeInst *II0 = Invokes.front();
2405     BasicBlock *II0BB = II0->getParent();
2406     BasicBlock *InsertBeforeBlock =
2407         II0->getParent()->getIterator()->getNextNode();
2408     Function *Func = II0BB->getParent();
2409     LLVMContext &Ctx = II0->getContext();
2410 
2411     BasicBlock *MergedInvokeBB = BasicBlock::Create(
2412         Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2413 
2414     auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2415     // NOTE: all invokes have the same attributes, so no handling needed.
2416     MergedInvokeBB->getInstList().push_back(MergedInvoke);
2417 
2418     if (!HasNormalDest) {
2419       // This set does not have a normal destination,
2420       // so just form a new block with unreachable terminator.
2421       BasicBlock *MergedNormalDest = BasicBlock::Create(
2422           Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2423       new UnreachableInst(Ctx, MergedNormalDest);
2424       MergedInvoke->setNormalDest(MergedNormalDest);
2425     }
2426 
2427     // The unwind destination, however, remainds identical for all invokes here.
2428 
2429     return MergedInvoke;
2430   }();
2431 
2432   if (DTU) {
2433     // Predecessor blocks that contained these invokes will now branch to
2434     // the new block that contains the merged invoke, ...
2435     for (InvokeInst *II : Invokes)
2436       Updates.push_back(
2437           {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2438 
2439     // ... which has the new `unreachable` block as normal destination,
2440     // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2441     for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2442       Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2443                          SuccBBOfMergedInvoke});
2444 
2445     // Since predecessor blocks now unconditionally branch to a new block,
2446     // they no longer branch to their original successors.
2447     for (InvokeInst *II : Invokes)
2448       for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2449         Updates.push_back(
2450             {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2451   }
2452 
2453   bool IsIndirectCall = Invokes[0]->isIndirectCall();
2454 
2455   // Form the merged operands for the merged invoke.
2456   for (Use &U : MergedInvoke->operands()) {
2457     // Only PHI together the indirect callees and data operands.
2458     if (MergedInvoke->isCallee(&U)) {
2459       if (!IsIndirectCall)
2460         continue;
2461     } else if (!MergedInvoke->isDataOperand(&U))
2462       continue;
2463 
2464     // Don't create trivial PHI's with all-identical incoming values.
2465     bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2466       return II->getOperand(U.getOperandNo()) != U.get();
2467     });
2468     if (!NeedPHI)
2469       continue;
2470 
2471     // Form a PHI out of all the data ops under this index.
2472     PHINode *PN = PHINode::Create(
2473         U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke);
2474     for (InvokeInst *II : Invokes)
2475       PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2476 
2477     U.set(PN);
2478   }
2479 
2480   // We've ensured that each PHI node has compatible (identical) incoming values
2481   // when coming from each of the `invoke`s in the current merge set,
2482   // so update the PHI nodes accordingly.
2483   for (BasicBlock *Succ : successors(MergedInvoke))
2484     AddPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2485                           /*ExistPred=*/Invokes.front()->getParent());
2486 
2487   // And finally, replace the original `invoke`s with an unconditional branch
2488   // to the block with the merged `invoke`. Also, give that merged `invoke`
2489   // the merged debugloc of all the original `invoke`s.
2490   const DILocation *MergedDebugLoc = nullptr;
2491   for (InvokeInst *II : Invokes) {
2492     // Compute the debug location common to all the original `invoke`s.
2493     if (!MergedDebugLoc)
2494       MergedDebugLoc = II->getDebugLoc();
2495     else
2496       MergedDebugLoc =
2497           DILocation::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2498 
2499     // And replace the old `invoke` with an unconditionally branch
2500     // to the block with the merged `invoke`.
2501     for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2502       OrigSuccBB->removePredecessor(II->getParent());
2503     BranchInst::Create(MergedInvoke->getParent(), II->getParent());
2504     II->replaceAllUsesWith(MergedInvoke);
2505     II->eraseFromParent();
2506     ++NumInvokesMerged;
2507   }
2508   MergedInvoke->setDebugLoc(MergedDebugLoc);
2509   ++NumInvokeSetsFormed;
2510 
2511   if (DTU)
2512     DTU->applyUpdates(Updates);
2513 }
2514 
2515 /// If this block is a `landingpad` exception handling block, categorize all
2516 /// the predecessor `invoke`s into sets, with all `invoke`s in each set
2517 /// being "mergeable" together, and then merge invokes in each set together.
2518 ///
2519 /// This is a weird mix of hoisting and sinking. Visually, it goes from:
2520 ///          [...]        [...]
2521 ///            |            |
2522 ///        [invoke0]    [invoke1]
2523 ///           / \          / \
2524 ///     [cont0] [landingpad] [cont1]
2525 /// to:
2526 ///      [...] [...]
2527 ///          \ /
2528 ///       [invoke]
2529 ///          / \
2530 ///     [cont] [landingpad]
2531 ///
2532 /// But of course we can only do that if the invokes share the `landingpad`,
2533 /// edges invoke0->cont0 and invoke1->cont1 are "compatible",
2534 /// and the invoked functions are "compatible".
2535 static bool MergeCompatibleInvokes(BasicBlock *BB, DomTreeUpdater *DTU) {
2536   if (!EnableMergeCompatibleInvokes)
2537     return false;
2538 
2539   bool Changed = false;
2540 
2541   // FIXME: generalize to all exception handling blocks?
2542   if (!BB->isLandingPad())
2543     return Changed;
2544 
2545   CompatibleSets Grouper;
2546 
2547   // Record all the predecessors of this `landingpad`. As per verifier,
2548   // the only allowed predecessor is the unwind edge of an `invoke`.
2549   // We want to group "compatible" `invokes` into the same set to be merged.
2550   for (BasicBlock *PredBB : predecessors(BB))
2551     Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
2552 
2553   // And now, merge `invoke`s that were grouped togeter.
2554   for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
2555     if (Invokes.size() < 2)
2556       continue;
2557     Changed = true;
2558     MergeCompatibleInvokesImpl(Invokes, DTU);
2559   }
2560 
2561   return Changed;
2562 }
2563 
2564 /// Determine if we can hoist sink a sole store instruction out of a
2565 /// conditional block.
2566 ///
2567 /// We are looking for code like the following:
2568 ///   BrBB:
2569 ///     store i32 %add, i32* %arrayidx2
2570 ///     ... // No other stores or function calls (we could be calling a memory
2571 ///     ... // function).
2572 ///     %cmp = icmp ult %x, %y
2573 ///     br i1 %cmp, label %EndBB, label %ThenBB
2574 ///   ThenBB:
2575 ///     store i32 %add5, i32* %arrayidx2
2576 ///     br label EndBB
2577 ///   EndBB:
2578 ///     ...
2579 ///   We are going to transform this into:
2580 ///   BrBB:
2581 ///     store i32 %add, i32* %arrayidx2
2582 ///     ... //
2583 ///     %cmp = icmp ult %x, %y
2584 ///     %add.add5 = select i1 %cmp, i32 %add, %add5
2585 ///     store i32 %add.add5, i32* %arrayidx2
2586 ///     ...
2587 ///
2588 /// \return The pointer to the value of the previous store if the store can be
2589 ///         hoisted into the predecessor block. 0 otherwise.
2590 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
2591                                      BasicBlock *StoreBB, BasicBlock *EndBB) {
2592   StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
2593   if (!StoreToHoist)
2594     return nullptr;
2595 
2596   // Volatile or atomic.
2597   if (!StoreToHoist->isSimple())
2598     return nullptr;
2599 
2600   Value *StorePtr = StoreToHoist->getPointerOperand();
2601   Type *StoreTy = StoreToHoist->getValueOperand()->getType();
2602 
2603   // Look for a store to the same pointer in BrBB.
2604   unsigned MaxNumInstToLookAt = 9;
2605   // Skip pseudo probe intrinsic calls which are not really killing any memory
2606   // accesses.
2607   for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug(true))) {
2608     if (!MaxNumInstToLookAt)
2609       break;
2610     --MaxNumInstToLookAt;
2611 
2612     // Could be calling an instruction that affects memory like free().
2613     if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
2614       return nullptr;
2615 
2616     if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
2617       // Found the previous store to same location and type. Make sure it is
2618       // simple, to avoid introducing a spurious non-atomic write after an
2619       // atomic write.
2620       if (SI->getPointerOperand() == StorePtr &&
2621           SI->getValueOperand()->getType() == StoreTy && SI->isSimple())
2622         // Found the previous store, return its value operand.
2623         return SI->getValueOperand();
2624       return nullptr; // Unknown store.
2625     }
2626 
2627     if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
2628       if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
2629           LI->isSimple()) {
2630         // Local objects (created by an `alloca` instruction) are always
2631         // writable, so once we are past a read from a location it is valid to
2632         // also write to that same location.
2633         // If the address of the local object never escapes the function, that
2634         // means it's never concurrently read or written, hence moving the store
2635         // from under the condition will not introduce a data race.
2636         auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(StorePtr));
2637         if (AI && !PointerMayBeCaptured(AI, false, true))
2638           // Found a previous load, return it.
2639           return LI;
2640       }
2641       // The load didn't work out, but we may still find a store.
2642     }
2643   }
2644 
2645   return nullptr;
2646 }
2647 
2648 /// Estimate the cost of the insertion(s) and check that the PHI nodes can be
2649 /// converted to selects.
2650 static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB,
2651                                            BasicBlock *EndBB,
2652                                            unsigned &SpeculatedInstructions,
2653                                            InstructionCost &Cost,
2654                                            const TargetTransformInfo &TTI) {
2655   TargetTransformInfo::TargetCostKind CostKind =
2656     BB->getParent()->hasMinSize()
2657     ? TargetTransformInfo::TCK_CodeSize
2658     : TargetTransformInfo::TCK_SizeAndLatency;
2659 
2660   bool HaveRewritablePHIs = false;
2661   for (PHINode &PN : EndBB->phis()) {
2662     Value *OrigV = PN.getIncomingValueForBlock(BB);
2663     Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2664 
2665     // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
2666     // Skip PHIs which are trivial.
2667     if (ThenV == OrigV)
2668       continue;
2669 
2670     Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(), nullptr,
2671                                    CmpInst::BAD_ICMP_PREDICATE, CostKind);
2672 
2673     // Don't convert to selects if we could remove undefined behavior instead.
2674     if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
2675         passingValueIsAlwaysUndefined(ThenV, &PN))
2676       return false;
2677 
2678     HaveRewritablePHIs = true;
2679     ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
2680     ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
2681     if (!OrigCE && !ThenCE)
2682       continue; // Known safe and cheap.
2683 
2684     if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
2685         (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
2686       return false;
2687     InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
2688     InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
2689     InstructionCost MaxCost =
2690         2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2691     if (OrigCost + ThenCost > MaxCost)
2692       return false;
2693 
2694     // Account for the cost of an unfolded ConstantExpr which could end up
2695     // getting expanded into Instructions.
2696     // FIXME: This doesn't account for how many operations are combined in the
2697     // constant expression.
2698     ++SpeculatedInstructions;
2699     if (SpeculatedInstructions > 1)
2700       return false;
2701   }
2702 
2703   return HaveRewritablePHIs;
2704 }
2705 
2706 /// Speculate a conditional basic block flattening the CFG.
2707 ///
2708 /// Note that this is a very risky transform currently. Speculating
2709 /// instructions like this is most often not desirable. Instead, there is an MI
2710 /// pass which can do it with full awareness of the resource constraints.
2711 /// However, some cases are "obvious" and we should do directly. An example of
2712 /// this is speculating a single, reasonably cheap instruction.
2713 ///
2714 /// There is only one distinct advantage to flattening the CFG at the IR level:
2715 /// it makes very common but simplistic optimizations such as are common in
2716 /// instcombine and the DAG combiner more powerful by removing CFG edges and
2717 /// modeling their effects with easier to reason about SSA value graphs.
2718 ///
2719 ///
2720 /// An illustration of this transform is turning this IR:
2721 /// \code
2722 ///   BB:
2723 ///     %cmp = icmp ult %x, %y
2724 ///     br i1 %cmp, label %EndBB, label %ThenBB
2725 ///   ThenBB:
2726 ///     %sub = sub %x, %y
2727 ///     br label BB2
2728 ///   EndBB:
2729 ///     %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
2730 ///     ...
2731 /// \endcode
2732 ///
2733 /// Into this IR:
2734 /// \code
2735 ///   BB:
2736 ///     %cmp = icmp ult %x, %y
2737 ///     %sub = sub %x, %y
2738 ///     %cond = select i1 %cmp, 0, %sub
2739 ///     ...
2740 /// \endcode
2741 ///
2742 /// \returns true if the conditional block is removed.
2743 bool SimplifyCFGOpt::SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
2744                                             const TargetTransformInfo &TTI) {
2745   // Be conservative for now. FP select instruction can often be expensive.
2746   Value *BrCond = BI->getCondition();
2747   if (isa<FCmpInst>(BrCond))
2748     return false;
2749 
2750   BasicBlock *BB = BI->getParent();
2751   BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
2752   InstructionCost Budget =
2753       PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2754 
2755   // If ThenBB is actually on the false edge of the conditional branch, remember
2756   // to swap the select operands later.
2757   bool Invert = false;
2758   if (ThenBB != BI->getSuccessor(0)) {
2759     assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
2760     Invert = true;
2761   }
2762   assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
2763 
2764   // If the branch is non-unpredictable, and is predicted to *not* branch to
2765   // the `then` block, then avoid speculating it.
2766   if (!BI->getMetadata(LLVMContext::MD_unpredictable)) {
2767     uint64_t TWeight, FWeight;
2768     if (BI->extractProfMetadata(TWeight, FWeight) && (TWeight + FWeight) != 0) {
2769       uint64_t EndWeight = Invert ? TWeight : FWeight;
2770       BranchProbability BIEndProb =
2771           BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
2772       BranchProbability Likely = TTI.getPredictableBranchThreshold();
2773       if (BIEndProb >= Likely)
2774         return false;
2775     }
2776   }
2777 
2778   // Keep a count of how many times instructions are used within ThenBB when
2779   // they are candidates for sinking into ThenBB. Specifically:
2780   // - They are defined in BB, and
2781   // - They have no side effects, and
2782   // - All of their uses are in ThenBB.
2783   SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
2784 
2785   SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
2786 
2787   unsigned SpeculatedInstructions = 0;
2788   Value *SpeculatedStoreValue = nullptr;
2789   StoreInst *SpeculatedStore = nullptr;
2790   for (BasicBlock::iterator BBI = ThenBB->begin(),
2791                             BBE = std::prev(ThenBB->end());
2792        BBI != BBE; ++BBI) {
2793     Instruction *I = &*BBI;
2794     // Skip debug info.
2795     if (isa<DbgInfoIntrinsic>(I)) {
2796       SpeculatedDbgIntrinsics.push_back(I);
2797       continue;
2798     }
2799 
2800     // Skip pseudo probes. The consequence is we lose track of the branch
2801     // probability for ThenBB, which is fine since the optimization here takes
2802     // place regardless of the branch probability.
2803     if (isa<PseudoProbeInst>(I)) {
2804       // The probe should be deleted so that it will not be over-counted when
2805       // the samples collected on the non-conditional path are counted towards
2806       // the conditional path. We leave it for the counts inference algorithm to
2807       // figure out a proper count for an unknown probe.
2808       SpeculatedDbgIntrinsics.push_back(I);
2809       continue;
2810     }
2811 
2812     // Only speculatively execute a single instruction (not counting the
2813     // terminator) for now.
2814     ++SpeculatedInstructions;
2815     if (SpeculatedInstructions > 1)
2816       return false;
2817 
2818     // Don't hoist the instruction if it's unsafe or expensive.
2819     if (!isSafeToSpeculativelyExecute(I) &&
2820         !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
2821                                   I, BB, ThenBB, EndBB))))
2822       return false;
2823     if (!SpeculatedStoreValue &&
2824         computeSpeculationCost(I, TTI) >
2825             PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
2826       return false;
2827 
2828     // Store the store speculation candidate.
2829     if (SpeculatedStoreValue)
2830       SpeculatedStore = cast<StoreInst>(I);
2831 
2832     // Do not hoist the instruction if any of its operands are defined but not
2833     // used in BB. The transformation will prevent the operand from
2834     // being sunk into the use block.
2835     for (Use &Op : I->operands()) {
2836       Instruction *OpI = dyn_cast<Instruction>(Op);
2837       if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
2838         continue; // Not a candidate for sinking.
2839 
2840       ++SinkCandidateUseCounts[OpI];
2841     }
2842   }
2843 
2844   // Consider any sink candidates which are only used in ThenBB as costs for
2845   // speculation. Note, while we iterate over a DenseMap here, we are summing
2846   // and so iteration order isn't significant.
2847   for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
2848            I = SinkCandidateUseCounts.begin(),
2849            E = SinkCandidateUseCounts.end();
2850        I != E; ++I)
2851     if (I->first->hasNUses(I->second)) {
2852       ++SpeculatedInstructions;
2853       if (SpeculatedInstructions > 1)
2854         return false;
2855     }
2856 
2857   // Check that we can insert the selects and that it's not too expensive to do
2858   // so.
2859   bool Convert = SpeculatedStore != nullptr;
2860   InstructionCost Cost = 0;
2861   Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
2862                                             SpeculatedInstructions,
2863                                             Cost, TTI);
2864   if (!Convert || Cost > Budget)
2865     return false;
2866 
2867   // If we get here, we can hoist the instruction and if-convert.
2868   LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
2869 
2870   // Insert a select of the value of the speculated store.
2871   if (SpeculatedStoreValue) {
2872     IRBuilder<NoFolder> Builder(BI);
2873     Value *TrueV = SpeculatedStore->getValueOperand();
2874     Value *FalseV = SpeculatedStoreValue;
2875     if (Invert)
2876       std::swap(TrueV, FalseV);
2877     Value *S = Builder.CreateSelect(
2878         BrCond, TrueV, FalseV, "spec.store.select", BI);
2879     SpeculatedStore->setOperand(0, S);
2880     SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
2881                                          SpeculatedStore->getDebugLoc());
2882   }
2883 
2884   // Metadata can be dependent on the condition we are hoisting above.
2885   // Conservatively strip all metadata on the instruction. Drop the debug loc
2886   // to avoid making it appear as if the condition is a constant, which would
2887   // be misleading while debugging.
2888   // Similarly strip attributes that maybe dependent on condition we are
2889   // hoisting above.
2890   for (auto &I : *ThenBB) {
2891     if (!SpeculatedStoreValue || &I != SpeculatedStore)
2892       I.setDebugLoc(DebugLoc());
2893     I.dropUndefImplyingAttrsAndUnknownMetadata();
2894   }
2895 
2896   // Hoist the instructions.
2897   BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
2898                            ThenBB->begin(), std::prev(ThenBB->end()));
2899 
2900   // Insert selects and rewrite the PHI operands.
2901   IRBuilder<NoFolder> Builder(BI);
2902   for (PHINode &PN : EndBB->phis()) {
2903     unsigned OrigI = PN.getBasicBlockIndex(BB);
2904     unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
2905     Value *OrigV = PN.getIncomingValue(OrigI);
2906     Value *ThenV = PN.getIncomingValue(ThenI);
2907 
2908     // Skip PHIs which are trivial.
2909     if (OrigV == ThenV)
2910       continue;
2911 
2912     // Create a select whose true value is the speculatively executed value and
2913     // false value is the pre-existing value. Swap them if the branch
2914     // destinations were inverted.
2915     Value *TrueV = ThenV, *FalseV = OrigV;
2916     if (Invert)
2917       std::swap(TrueV, FalseV);
2918     Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI);
2919     PN.setIncomingValue(OrigI, V);
2920     PN.setIncomingValue(ThenI, V);
2921   }
2922 
2923   // Remove speculated dbg intrinsics.
2924   // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
2925   // dbg value for the different flows and inserting it after the select.
2926   for (Instruction *I : SpeculatedDbgIntrinsics)
2927     I->eraseFromParent();
2928 
2929   ++NumSpeculations;
2930   return true;
2931 }
2932 
2933 /// Return true if we can thread a branch across this block.
2934 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2935   int Size = 0;
2936 
2937   SmallPtrSet<const Value *, 32> EphValues;
2938   auto IsEphemeral = [&](const Instruction *I) {
2939     if (isa<AssumeInst>(I))
2940       return true;
2941     return !I->mayHaveSideEffects() && !I->isTerminator() &&
2942            all_of(I->users(),
2943                   [&](const User *U) { return EphValues.count(U); });
2944   };
2945 
2946   // Walk the loop in reverse so that we can identify ephemeral values properly
2947   // (values only feeding assumes).
2948   for (Instruction &I : reverse(BB->instructionsWithoutDebug(false))) {
2949     // Can't fold blocks that contain noduplicate or convergent calls.
2950     if (CallInst *CI = dyn_cast<CallInst>(&I))
2951       if (CI->cannotDuplicate() || CI->isConvergent())
2952         return false;
2953 
2954     // Ignore ephemeral values which are deleted during codegen.
2955     if (IsEphemeral(&I))
2956       EphValues.insert(&I);
2957     // We will delete Phis while threading, so Phis should not be accounted in
2958     // block's size.
2959     else if (!isa<PHINode>(I)) {
2960       if (Size++ > MaxSmallBlockSize)
2961         return false; // Don't clone large BB's.
2962     }
2963 
2964     // We can only support instructions that do not define values that are
2965     // live outside of the current basic block.
2966     for (User *U : I.users()) {
2967       Instruction *UI = cast<Instruction>(U);
2968       if (UI->getParent() != BB || isa<PHINode>(UI))
2969         return false;
2970     }
2971 
2972     // Looks ok, continue checking.
2973   }
2974 
2975   return true;
2976 }
2977 
2978 static ConstantInt *getKnownValueOnEdge(Value *V, BasicBlock *From,
2979                                         BasicBlock *To) {
2980   // Don't look past the block defining the value, we might get the value from
2981   // a previous loop iteration.
2982   auto *I = dyn_cast<Instruction>(V);
2983   if (I && I->getParent() == To)
2984     return nullptr;
2985 
2986   // We know the value if the From block branches on it.
2987   auto *BI = dyn_cast<BranchInst>(From->getTerminator());
2988   if (BI && BI->isConditional() && BI->getCondition() == V &&
2989       BI->getSuccessor(0) != BI->getSuccessor(1))
2990     return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
2991                                      : ConstantInt::getFalse(BI->getContext());
2992 
2993   return nullptr;
2994 }
2995 
2996 /// If we have a conditional branch on something for which we know the constant
2997 /// value in predecessors (e.g. a phi node in the current block), thread edges
2998 /// from the predecessor to their ultimate destination.
2999 static Optional<bool>
3000 FoldCondBranchOnValueKnownInPredecessorImpl(BranchInst *BI, DomTreeUpdater *DTU,
3001                                             const DataLayout &DL,
3002                                             AssumptionCache *AC) {
3003   SmallMapVector<BasicBlock *, ConstantInt *, 8> KnownValues;
3004   BasicBlock *BB = BI->getParent();
3005   Value *Cond = BI->getCondition();
3006   PHINode *PN = dyn_cast<PHINode>(Cond);
3007   if (PN && PN->getParent() == BB) {
3008     // Degenerate case of a single entry PHI.
3009     if (PN->getNumIncomingValues() == 1) {
3010       FoldSingleEntryPHINodes(PN->getParent());
3011       return true;
3012     }
3013 
3014     for (Use &U : PN->incoming_values())
3015       if (auto *CB = dyn_cast<ConstantInt>(U))
3016         KnownValues.insert({PN->getIncomingBlock(U), CB});
3017   } else {
3018     for (BasicBlock *Pred : predecessors(BB)) {
3019       if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3020         KnownValues.insert({Pred, CB});
3021     }
3022   }
3023 
3024   if (KnownValues.empty())
3025     return false;
3026 
3027   // Now we know that this block has multiple preds and two succs.
3028   // Check that the block is small enough and values defined in the block are
3029   // not used outside of it.
3030   if (!BlockIsSimpleEnoughToThreadThrough(BB))
3031     return false;
3032 
3033   for (const auto &Pair : KnownValues) {
3034     // Okay, we now know that all edges from PredBB should be revectored to
3035     // branch to RealDest.
3036     ConstantInt *CB = Pair.second;
3037     BasicBlock *PredBB = Pair.first;
3038     BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3039 
3040     if (RealDest == BB)
3041       continue; // Skip self loops.
3042     // Skip if the predecessor's terminator is an indirect branch.
3043     if (isa<IndirectBrInst>(PredBB->getTerminator()))
3044       continue;
3045 
3046     SmallVector<DominatorTree::UpdateType, 3> Updates;
3047 
3048     // The dest block might have PHI nodes, other predecessors and other
3049     // difficult cases.  Instead of being smart about this, just insert a new
3050     // block that jumps to the destination block, effectively splitting
3051     // the edge we are about to create.
3052     BasicBlock *EdgeBB =
3053         BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
3054                            RealDest->getParent(), RealDest);
3055     BranchInst *CritEdgeBranch = BranchInst::Create(RealDest, EdgeBB);
3056     if (DTU)
3057       Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3058     CritEdgeBranch->setDebugLoc(BI->getDebugLoc());
3059 
3060     // Update PHI nodes.
3061     AddPredecessorToBlock(RealDest, EdgeBB, BB);
3062 
3063     // BB may have instructions that are being threaded over.  Clone these
3064     // instructions into EdgeBB.  We know that there will be no uses of the
3065     // cloned instructions outside of EdgeBB.
3066     BasicBlock::iterator InsertPt = EdgeBB->begin();
3067     DenseMap<Value *, Value *> TranslateMap; // Track translated values.
3068     for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3069       if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3070         TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
3071         continue;
3072       }
3073       // Clone the instruction.
3074       Instruction *N = BBI->clone();
3075       if (BBI->hasName())
3076         N->setName(BBI->getName() + ".c");
3077 
3078       // Update operands due to translation.
3079       for (Use &Op : N->operands()) {
3080         DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(Op);
3081         if (PI != TranslateMap.end())
3082           Op = PI->second;
3083       }
3084 
3085       // Check for trivial simplification.
3086       if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3087         if (!BBI->use_empty())
3088           TranslateMap[&*BBI] = V;
3089         if (!N->mayHaveSideEffects()) {
3090           N->deleteValue(); // Instruction folded away, don't need actual inst
3091           N = nullptr;
3092         }
3093       } else {
3094         if (!BBI->use_empty())
3095           TranslateMap[&*BBI] = N;
3096       }
3097       if (N) {
3098         // Insert the new instruction into its new home.
3099         EdgeBB->getInstList().insert(InsertPt, N);
3100 
3101         // Register the new instruction with the assumption cache if necessary.
3102         if (auto *Assume = dyn_cast<AssumeInst>(N))
3103           if (AC)
3104             AC->registerAssumption(Assume);
3105       }
3106     }
3107 
3108     // Loop over all of the edges from PredBB to BB, changing them to branch
3109     // to EdgeBB instead.
3110     Instruction *PredBBTI = PredBB->getTerminator();
3111     for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
3112       if (PredBBTI->getSuccessor(i) == BB) {
3113         BB->removePredecessor(PredBB);
3114         PredBBTI->setSuccessor(i, EdgeBB);
3115       }
3116 
3117     if (DTU) {
3118       Updates.push_back({DominatorTree::Insert, PredBB, EdgeBB});
3119       Updates.push_back({DominatorTree::Delete, PredBB, BB});
3120 
3121       DTU->applyUpdates(Updates);
3122     }
3123 
3124     // Signal repeat, simplifying any other constants.
3125     return None;
3126   }
3127 
3128   return false;
3129 }
3130 
3131 static bool FoldCondBranchOnValueKnownInPredecessor(BranchInst *BI,
3132                                                     DomTreeUpdater *DTU,
3133                                                     const DataLayout &DL,
3134                                                     AssumptionCache *AC) {
3135   Optional<bool> Result;
3136   bool EverChanged = false;
3137   do {
3138     // Note that None means "we changed things, but recurse further."
3139     Result = FoldCondBranchOnValueKnownInPredecessorImpl(BI, DTU, DL, AC);
3140     EverChanged |= Result == None || *Result;
3141   } while (Result == None);
3142   return EverChanged;
3143 }
3144 
3145 /// Given a BB that starts with the specified two-entry PHI node,
3146 /// see if we can eliminate it.
3147 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
3148                                 DomTreeUpdater *DTU, const DataLayout &DL) {
3149   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
3150   // statement", which has a very simple dominance structure.  Basically, we
3151   // are trying to find the condition that is being branched on, which
3152   // subsequently causes this merge to happen.  We really want control
3153   // dependence information for this check, but simplifycfg can't keep it up
3154   // to date, and this catches most of the cases we care about anyway.
3155   BasicBlock *BB = PN->getParent();
3156 
3157   BasicBlock *IfTrue, *IfFalse;
3158   BranchInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3159   if (!DomBI)
3160     return false;
3161   Value *IfCond = DomBI->getCondition();
3162   // Don't bother if the branch will be constant folded trivially.
3163   if (isa<ConstantInt>(IfCond))
3164     return false;
3165 
3166   BasicBlock *DomBlock = DomBI->getParent();
3167   SmallVector<BasicBlock *, 2> IfBlocks;
3168   llvm::copy_if(
3169       PN->blocks(), std::back_inserter(IfBlocks), [](BasicBlock *IfBlock) {
3170         return cast<BranchInst>(IfBlock->getTerminator())->isUnconditional();
3171       });
3172   assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3173          "Will have either one or two blocks to speculate.");
3174 
3175   // If the branch is non-unpredictable, see if we either predictably jump to
3176   // the merge bb (if we have only a single 'then' block), or if we predictably
3177   // jump to one specific 'then' block (if we have two of them).
3178   // It isn't beneficial to speculatively execute the code
3179   // from the block that we know is predictably not entered.
3180   if (!DomBI->getMetadata(LLVMContext::MD_unpredictable)) {
3181     uint64_t TWeight, FWeight;
3182     if (DomBI->extractProfMetadata(TWeight, FWeight) &&
3183         (TWeight + FWeight) != 0) {
3184       BranchProbability BITrueProb =
3185           BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3186       BranchProbability Likely = TTI.getPredictableBranchThreshold();
3187       BranchProbability BIFalseProb = BITrueProb.getCompl();
3188       if (IfBlocks.size() == 1) {
3189         BranchProbability BIBBProb =
3190             DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3191         if (BIBBProb >= Likely)
3192           return false;
3193       } else {
3194         if (BITrueProb >= Likely || BIFalseProb >= Likely)
3195           return false;
3196       }
3197     }
3198   }
3199 
3200   // Don't try to fold an unreachable block. For example, the phi node itself
3201   // can't be the candidate if-condition for a select that we want to form.
3202   if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3203     if (IfCondPhiInst->getParent() == BB)
3204       return false;
3205 
3206   // Okay, we found that we can merge this two-entry phi node into a select.
3207   // Doing so would require us to fold *all* two entry phi nodes in this block.
3208   // At some point this becomes non-profitable (particularly if the target
3209   // doesn't support cmov's).  Only do this transformation if there are two or
3210   // fewer PHI nodes in this block.
3211   unsigned NumPhis = 0;
3212   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3213     if (NumPhis > 2)
3214       return false;
3215 
3216   // Loop over the PHI's seeing if we can promote them all to select
3217   // instructions.  While we are at it, keep track of the instructions
3218   // that need to be moved to the dominating block.
3219   SmallPtrSet<Instruction *, 4> AggressiveInsts;
3220   InstructionCost Cost = 0;
3221   InstructionCost Budget =
3222       TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3223 
3224   bool Changed = false;
3225   for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3226     PHINode *PN = cast<PHINode>(II++);
3227     if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
3228       PN->replaceAllUsesWith(V);
3229       PN->eraseFromParent();
3230       Changed = true;
3231       continue;
3232     }
3233 
3234     if (!dominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
3235                              Cost, Budget, TTI) ||
3236         !dominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
3237                              Cost, Budget, TTI))
3238       return Changed;
3239   }
3240 
3241   // If we folded the first phi, PN dangles at this point.  Refresh it.  If
3242   // we ran out of PHIs then we simplified them all.
3243   PN = dyn_cast<PHINode>(BB->begin());
3244   if (!PN)
3245     return true;
3246 
3247   // Return true if at least one of these is a 'not', and another is either
3248   // a 'not' too, or a constant.
3249   auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) {
3250     if (!match(V0, m_Not(m_Value())))
3251       std::swap(V0, V1);
3252     auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant());
3253     return match(V0, m_Not(m_Value())) && match(V1, Invertible);
3254   };
3255 
3256   // Don't fold i1 branches on PHIs which contain binary operators or
3257   // (possibly inverted) select form of or/ands,  unless one of
3258   // the incoming values is an 'not' and another one is freely invertible.
3259   // These can often be turned into switches and other things.
3260   auto IsBinOpOrAnd = [](Value *V) {
3261     return match(
3262         V, m_CombineOr(
3263                m_BinOp(),
3264                m_CombineOr(m_Select(m_Value(), m_ImmConstant(), m_Value()),
3265                            m_Select(m_Value(), m_Value(), m_ImmConstant()))));
3266   };
3267   if (PN->getType()->isIntegerTy(1) &&
3268       (IsBinOpOrAnd(PN->getIncomingValue(0)) ||
3269        IsBinOpOrAnd(PN->getIncomingValue(1)) || IsBinOpOrAnd(IfCond)) &&
3270       !CanHoistNotFromBothValues(PN->getIncomingValue(0),
3271                                  PN->getIncomingValue(1)))
3272     return Changed;
3273 
3274   // If all PHI nodes are promotable, check to make sure that all instructions
3275   // in the predecessor blocks can be promoted as well. If not, we won't be able
3276   // to get rid of the control flow, so it's not worth promoting to select
3277   // instructions.
3278   for (BasicBlock *IfBlock : IfBlocks)
3279     for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
3280       if (!AggressiveInsts.count(&*I) && !I->isDebugOrPseudoInst()) {
3281         // This is not an aggressive instruction that we can promote.
3282         // Because of this, we won't be able to get rid of the control flow, so
3283         // the xform is not worth it.
3284         return Changed;
3285       }
3286 
3287   // If either of the blocks has it's address taken, we can't do this fold.
3288   if (any_of(IfBlocks,
3289              [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
3290     return Changed;
3291 
3292   LLVM_DEBUG(dbgs() << "FOUND IF CONDITION!  " << *IfCond
3293                     << "  T: " << IfTrue->getName()
3294                     << "  F: " << IfFalse->getName() << "\n");
3295 
3296   // If we can still promote the PHI nodes after this gauntlet of tests,
3297   // do all of the PHI's now.
3298 
3299   // Move all 'aggressive' instructions, which are defined in the
3300   // conditional parts of the if's up to the dominating block.
3301   for (BasicBlock *IfBlock : IfBlocks)
3302       hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
3303 
3304   IRBuilder<NoFolder> Builder(DomBI);
3305   // Propagate fast-math-flags from phi nodes to replacement selects.
3306   IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
3307   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
3308     if (isa<FPMathOperator>(PN))
3309       Builder.setFastMathFlags(PN->getFastMathFlags());
3310 
3311     // Change the PHI node into a select instruction.
3312     Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
3313     Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
3314 
3315     Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", DomBI);
3316     PN->replaceAllUsesWith(Sel);
3317     Sel->takeName(PN);
3318     PN->eraseFromParent();
3319   }
3320 
3321   // At this point, all IfBlocks are empty, so our if statement
3322   // has been flattened.  Change DomBlock to jump directly to our new block to
3323   // avoid other simplifycfg's kicking in on the diamond.
3324   Builder.CreateBr(BB);
3325 
3326   SmallVector<DominatorTree::UpdateType, 3> Updates;
3327   if (DTU) {
3328     Updates.push_back({DominatorTree::Insert, DomBlock, BB});
3329     for (auto *Successor : successors(DomBlock))
3330       Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
3331   }
3332 
3333   DomBI->eraseFromParent();
3334   if (DTU)
3335     DTU->applyUpdates(Updates);
3336 
3337   return true;
3338 }
3339 
3340 static Value *createLogicalOp(IRBuilderBase &Builder,
3341                               Instruction::BinaryOps Opc, Value *LHS,
3342                               Value *RHS, const Twine &Name = "") {
3343   // Try to relax logical op to binary op.
3344   if (impliesPoison(RHS, LHS))
3345     return Builder.CreateBinOp(Opc, LHS, RHS, Name);
3346   if (Opc == Instruction::And)
3347     return Builder.CreateLogicalAnd(LHS, RHS, Name);
3348   if (Opc == Instruction::Or)
3349     return Builder.CreateLogicalOr(LHS, RHS, Name);
3350   llvm_unreachable("Invalid logical opcode");
3351 }
3352 
3353 /// Return true if either PBI or BI has branch weight available, and store
3354 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
3355 /// not have branch weight, use 1:1 as its weight.
3356 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
3357                                    uint64_t &PredTrueWeight,
3358                                    uint64_t &PredFalseWeight,
3359                                    uint64_t &SuccTrueWeight,
3360                                    uint64_t &SuccFalseWeight) {
3361   bool PredHasWeights =
3362       PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
3363   bool SuccHasWeights =
3364       BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
3365   if (PredHasWeights || SuccHasWeights) {
3366     if (!PredHasWeights)
3367       PredTrueWeight = PredFalseWeight = 1;
3368     if (!SuccHasWeights)
3369       SuccTrueWeight = SuccFalseWeight = 1;
3370     return true;
3371   } else {
3372     return false;
3373   }
3374 }
3375 
3376 /// Determine if the two branches share a common destination and deduce a glue
3377 /// that joins the branches' conditions to arrive at the common destination if
3378 /// that would be profitable.
3379 static Optional<std::pair<Instruction::BinaryOps, bool>>
3380 shouldFoldCondBranchesToCommonDestination(BranchInst *BI, BranchInst *PBI,
3381                                           const TargetTransformInfo *TTI) {
3382   assert(BI && PBI && BI->isConditional() && PBI->isConditional() &&
3383          "Both blocks must end with a conditional branches.");
3384   assert(is_contained(predecessors(BI->getParent()), PBI->getParent()) &&
3385          "PredBB must be a predecessor of BB.");
3386 
3387   // We have the potential to fold the conditions together, but if the
3388   // predecessor branch is predictable, we may not want to merge them.
3389   uint64_t PTWeight, PFWeight;
3390   BranchProbability PBITrueProb, Likely;
3391   if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
3392       PBI->extractProfMetadata(PTWeight, PFWeight) &&
3393       (PTWeight + PFWeight) != 0) {
3394     PBITrueProb =
3395         BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
3396     Likely = TTI->getPredictableBranchThreshold();
3397   }
3398 
3399   if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3400     // Speculate the 2nd condition unless the 1st is probably true.
3401     if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3402       return {{Instruction::Or, false}};
3403   } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3404     // Speculate the 2nd condition unless the 1st is probably false.
3405     if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3406       return {{Instruction::And, false}};
3407   } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3408     // Speculate the 2nd condition unless the 1st is probably true.
3409     if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3410       return {{Instruction::And, true}};
3411   } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3412     // Speculate the 2nd condition unless the 1st is probably false.
3413     if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3414       return {{Instruction::Or, true}};
3415   }
3416   return None;
3417 }
3418 
3419 static bool performBranchToCommonDestFolding(BranchInst *BI, BranchInst *PBI,
3420                                              DomTreeUpdater *DTU,
3421                                              MemorySSAUpdater *MSSAU,
3422                                              const TargetTransformInfo *TTI) {
3423   BasicBlock *BB = BI->getParent();
3424   BasicBlock *PredBlock = PBI->getParent();
3425 
3426   // Determine if the two branches share a common destination.
3427   Instruction::BinaryOps Opc;
3428   bool InvertPredCond;
3429   std::tie(Opc, InvertPredCond) =
3430       *shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI);
3431 
3432   LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
3433 
3434   IRBuilder<> Builder(PBI);
3435   // The builder is used to create instructions to eliminate the branch in BB.
3436   // If BB's terminator has !annotation metadata, add it to the new
3437   // instructions.
3438   Builder.CollectMetadataToCopy(BB->getTerminator(),
3439                                 {LLVMContext::MD_annotation});
3440 
3441   // If we need to invert the condition in the pred block to match, do so now.
3442   if (InvertPredCond) {
3443     Value *NewCond = PBI->getCondition();
3444     if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
3445       CmpInst *CI = cast<CmpInst>(NewCond);
3446       CI->setPredicate(CI->getInversePredicate());
3447     } else {
3448       NewCond =
3449           Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
3450     }
3451 
3452     PBI->setCondition(NewCond);
3453     PBI->swapSuccessors();
3454   }
3455 
3456   BasicBlock *UniqueSucc =
3457       PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
3458 
3459   // Before cloning instructions, notify the successor basic block that it
3460   // is about to have a new predecessor. This will update PHI nodes,
3461   // which will allow us to update live-out uses of bonus instructions.
3462   AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
3463 
3464   // Try to update branch weights.
3465   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3466   if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3467                              SuccTrueWeight, SuccFalseWeight)) {
3468     SmallVector<uint64_t, 8> NewWeights;
3469 
3470     if (PBI->getSuccessor(0) == BB) {
3471       // PBI: br i1 %x, BB, FalseDest
3472       // BI:  br i1 %y, UniqueSucc, FalseDest
3473       // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
3474       NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
3475       // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
3476       //               TrueWeight for PBI * FalseWeight for BI.
3477       // We assume that total weights of a BranchInst can fit into 32 bits.
3478       // Therefore, we will not have overflow using 64-bit arithmetic.
3479       NewWeights.push_back(PredFalseWeight *
3480                                (SuccFalseWeight + SuccTrueWeight) +
3481                            PredTrueWeight * SuccFalseWeight);
3482     } else {
3483       // PBI: br i1 %x, TrueDest, BB
3484       // BI:  br i1 %y, TrueDest, UniqueSucc
3485       // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
3486       //              FalseWeight for PBI * TrueWeight for BI.
3487       NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
3488                            PredFalseWeight * SuccTrueWeight);
3489       // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
3490       NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
3491     }
3492 
3493     // Halve the weights if any of them cannot fit in an uint32_t
3494     FitWeights(NewWeights);
3495 
3496     SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end());
3497     setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
3498 
3499     // TODO: If BB is reachable from all paths through PredBlock, then we
3500     // could replace PBI's branch probabilities with BI's.
3501   } else
3502     PBI->setMetadata(LLVMContext::MD_prof, nullptr);
3503 
3504   // Now, update the CFG.
3505   PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
3506 
3507   if (DTU)
3508     DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
3509                        {DominatorTree::Delete, PredBlock, BB}});
3510 
3511   // If BI was a loop latch, it may have had associated loop metadata.
3512   // We need to copy it to the new latch, that is, PBI.
3513   if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
3514     PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
3515 
3516   ValueToValueMapTy VMap; // maps original values to cloned values
3517   CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BB, PredBlock, VMap);
3518 
3519   // Now that the Cond was cloned into the predecessor basic block,
3520   // or/and the two conditions together.
3521   Value *BICond = VMap[BI->getCondition()];
3522   PBI->setCondition(
3523       createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
3524 
3525   // Copy any debug value intrinsics into the end of PredBlock.
3526   for (Instruction &I : *BB) {
3527     if (isa<DbgInfoIntrinsic>(I)) {
3528       Instruction *NewI = I.clone();
3529       RemapInstruction(NewI, VMap,
3530                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
3531       NewI->insertBefore(PBI);
3532     }
3533   }
3534 
3535   ++NumFoldBranchToCommonDest;
3536   return true;
3537 }
3538 
3539 /// Return if an instruction's type or any of its operands' types are a vector
3540 /// type.
3541 static bool isVectorOp(Instruction &I) {
3542   return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
3543            return U->getType()->isVectorTy();
3544          });
3545 }
3546 
3547 /// If this basic block is simple enough, and if a predecessor branches to us
3548 /// and one of our successors, fold the block into the predecessor and use
3549 /// logical operations to pick the right destination.
3550 bool llvm::FoldBranchToCommonDest(BranchInst *BI, DomTreeUpdater *DTU,
3551                                   MemorySSAUpdater *MSSAU,
3552                                   const TargetTransformInfo *TTI,
3553                                   unsigned BonusInstThreshold) {
3554   // If this block ends with an unconditional branch,
3555   // let SpeculativelyExecuteBB() deal with it.
3556   if (!BI->isConditional())
3557     return false;
3558 
3559   BasicBlock *BB = BI->getParent();
3560   TargetTransformInfo::TargetCostKind CostKind =
3561     BB->getParent()->hasMinSize() ? TargetTransformInfo::TCK_CodeSize
3562                                   : TargetTransformInfo::TCK_SizeAndLatency;
3563 
3564   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3565 
3566   if (!Cond ||
3567       (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond) &&
3568        !isa<SelectInst>(Cond)) ||
3569       Cond->getParent() != BB || !Cond->hasOneUse())
3570     return false;
3571 
3572   // Cond is known to be a compare or binary operator.  Check to make sure that
3573   // neither operand is a potentially-trapping constant expression.
3574   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
3575     if (CE->canTrap())
3576       return false;
3577   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
3578     if (CE->canTrap())
3579       return false;
3580 
3581   // Finally, don't infinitely unroll conditional loops.
3582   if (is_contained(successors(BB), BB))
3583     return false;
3584 
3585   // With which predecessors will we want to deal with?
3586   SmallVector<BasicBlock *, 8> Preds;
3587   for (BasicBlock *PredBlock : predecessors(BB)) {
3588     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
3589 
3590     // Check that we have two conditional branches.  If there is a PHI node in
3591     // the common successor, verify that the same value flows in from both
3592     // blocks.
3593     if (!PBI || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
3594       continue;
3595 
3596     // Determine if the two branches share a common destination.
3597     Instruction::BinaryOps Opc;
3598     bool InvertPredCond;
3599     if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
3600       std::tie(Opc, InvertPredCond) = *Recipe;
3601     else
3602       continue;
3603 
3604     // Check the cost of inserting the necessary logic before performing the
3605     // transformation.
3606     if (TTI) {
3607       Type *Ty = BI->getCondition()->getType();
3608       InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
3609       if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
3610           !isa<CmpInst>(PBI->getCondition())))
3611         Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
3612 
3613       if (Cost > BranchFoldThreshold)
3614         continue;
3615     }
3616 
3617     // Ok, we do want to deal with this predecessor. Record it.
3618     Preds.emplace_back(PredBlock);
3619   }
3620 
3621   // If there aren't any predecessors into which we can fold,
3622   // don't bother checking the cost.
3623   if (Preds.empty())
3624     return false;
3625 
3626   // Only allow this transformation if computing the condition doesn't involve
3627   // too many instructions and these involved instructions can be executed
3628   // unconditionally. We denote all involved instructions except the condition
3629   // as "bonus instructions", and only allow this transformation when the
3630   // number of the bonus instructions we'll need to create when cloning into
3631   // each predecessor does not exceed a certain threshold.
3632   unsigned NumBonusInsts = 0;
3633   bool SawVectorOp = false;
3634   const unsigned PredCount = Preds.size();
3635   for (Instruction &I : *BB) {
3636     // Don't check the branch condition comparison itself.
3637     if (&I == Cond)
3638       continue;
3639     // Ignore dbg intrinsics, and the terminator.
3640     if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I))
3641       continue;
3642     // I must be safe to execute unconditionally.
3643     if (!isSafeToSpeculativelyExecute(&I))
3644       return false;
3645     SawVectorOp |= isVectorOp(I);
3646 
3647     // Account for the cost of duplicating this instruction into each
3648     // predecessor. Ignore free instructions.
3649     if (!TTI ||
3650         TTI->getUserCost(&I, CostKind) != TargetTransformInfo::TCC_Free) {
3651       NumBonusInsts += PredCount;
3652 
3653       // Early exits once we reach the limit.
3654       if (NumBonusInsts >
3655           BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
3656         return false;
3657     }
3658 
3659     auto IsBCSSAUse = [BB, &I](Use &U) {
3660       auto *UI = cast<Instruction>(U.getUser());
3661       if (auto *PN = dyn_cast<PHINode>(UI))
3662         return PN->getIncomingBlock(U) == BB;
3663       return UI->getParent() == BB && I.comesBefore(UI);
3664     };
3665 
3666     // Does this instruction require rewriting of uses?
3667     if (!all_of(I.uses(), IsBCSSAUse))
3668       return false;
3669   }
3670   if (NumBonusInsts >
3671       BonusInstThreshold *
3672           (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
3673     return false;
3674 
3675   // Ok, we have the budget. Perform the transformation.
3676   for (BasicBlock *PredBlock : Preds) {
3677     auto *PBI = cast<BranchInst>(PredBlock->getTerminator());
3678     return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
3679   }
3680   return false;
3681 }
3682 
3683 // If there is only one store in BB1 and BB2, return it, otherwise return
3684 // nullptr.
3685 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
3686   StoreInst *S = nullptr;
3687   for (auto *BB : {BB1, BB2}) {
3688     if (!BB)
3689       continue;
3690     for (auto &I : *BB)
3691       if (auto *SI = dyn_cast<StoreInst>(&I)) {
3692         if (S)
3693           // Multiple stores seen.
3694           return nullptr;
3695         else
3696           S = SI;
3697       }
3698   }
3699   return S;
3700 }
3701 
3702 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
3703                                               Value *AlternativeV = nullptr) {
3704   // PHI is going to be a PHI node that allows the value V that is defined in
3705   // BB to be referenced in BB's only successor.
3706   //
3707   // If AlternativeV is nullptr, the only value we care about in PHI is V. It
3708   // doesn't matter to us what the other operand is (it'll never get used). We
3709   // could just create a new PHI with an undef incoming value, but that could
3710   // increase register pressure if EarlyCSE/InstCombine can't fold it with some
3711   // other PHI. So here we directly look for some PHI in BB's successor with V
3712   // as an incoming operand. If we find one, we use it, else we create a new
3713   // one.
3714   //
3715   // If AlternativeV is not nullptr, we care about both incoming values in PHI.
3716   // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
3717   // where OtherBB is the single other predecessor of BB's only successor.
3718   PHINode *PHI = nullptr;
3719   BasicBlock *Succ = BB->getSingleSuccessor();
3720 
3721   for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
3722     if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
3723       PHI = cast<PHINode>(I);
3724       if (!AlternativeV)
3725         break;
3726 
3727       assert(Succ->hasNPredecessors(2));
3728       auto PredI = pred_begin(Succ);
3729       BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
3730       if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
3731         break;
3732       PHI = nullptr;
3733     }
3734   if (PHI)
3735     return PHI;
3736 
3737   // If V is not an instruction defined in BB, just return it.
3738   if (!AlternativeV &&
3739       (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
3740     return V;
3741 
3742   PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
3743   PHI->addIncoming(V, BB);
3744   for (BasicBlock *PredBB : predecessors(Succ))
3745     if (PredBB != BB)
3746       PHI->addIncoming(
3747           AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
3748   return PHI;
3749 }
3750 
3751 static bool mergeConditionalStoreToAddress(
3752     BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
3753     BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
3754     DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
3755   // For every pointer, there must be exactly two stores, one coming from
3756   // PTB or PFB, and the other from QTB or QFB. We don't support more than one
3757   // store (to any address) in PTB,PFB or QTB,QFB.
3758   // FIXME: We could relax this restriction with a bit more work and performance
3759   // testing.
3760   StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
3761   StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
3762   if (!PStore || !QStore)
3763     return false;
3764 
3765   // Now check the stores are compatible.
3766   if (!QStore->isUnordered() || !PStore->isUnordered() ||
3767       PStore->getValueOperand()->getType() !=
3768           QStore->getValueOperand()->getType())
3769     return false;
3770 
3771   // Check that sinking the store won't cause program behavior changes. Sinking
3772   // the store out of the Q blocks won't change any behavior as we're sinking
3773   // from a block to its unconditional successor. But we're moving a store from
3774   // the P blocks down through the middle block (QBI) and past both QFB and QTB.
3775   // So we need to check that there are no aliasing loads or stores in
3776   // QBI, QTB and QFB. We also need to check there are no conflicting memory
3777   // operations between PStore and the end of its parent block.
3778   //
3779   // The ideal way to do this is to query AliasAnalysis, but we don't
3780   // preserve AA currently so that is dangerous. Be super safe and just
3781   // check there are no other memory operations at all.
3782   for (auto &I : *QFB->getSinglePredecessor())
3783     if (I.mayReadOrWriteMemory())
3784       return false;
3785   for (auto &I : *QFB)
3786     if (&I != QStore && I.mayReadOrWriteMemory())
3787       return false;
3788   if (QTB)
3789     for (auto &I : *QTB)
3790       if (&I != QStore && I.mayReadOrWriteMemory())
3791         return false;
3792   for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
3793        I != E; ++I)
3794     if (&*I != PStore && I->mayReadOrWriteMemory())
3795       return false;
3796 
3797   // If we're not in aggressive mode, we only optimize if we have some
3798   // confidence that by optimizing we'll allow P and/or Q to be if-converted.
3799   auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
3800     if (!BB)
3801       return true;
3802     // Heuristic: if the block can be if-converted/phi-folded and the
3803     // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
3804     // thread this store.
3805     InstructionCost Cost = 0;
3806     InstructionCost Budget =
3807         PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3808     for (auto &I : BB->instructionsWithoutDebug(false)) {
3809       // Consider terminator instruction to be free.
3810       if (I.isTerminator())
3811         continue;
3812       // If this is one the stores that we want to speculate out of this BB,
3813       // then don't count it's cost, consider it to be free.
3814       if (auto *S = dyn_cast<StoreInst>(&I))
3815         if (llvm::find(FreeStores, S))
3816           continue;
3817       // Else, we have a white-list of instructions that we are ak speculating.
3818       if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
3819         return false; // Not in white-list - not worthwhile folding.
3820       // And finally, if this is a non-free instruction that we are okay
3821       // speculating, ensure that we consider the speculation budget.
3822       Cost += TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
3823       if (Cost > Budget)
3824         return false; // Eagerly refuse to fold as soon as we're out of budget.
3825     }
3826     assert(Cost <= Budget &&
3827            "When we run out of budget we will eagerly return from within the "
3828            "per-instruction loop.");
3829     return true;
3830   };
3831 
3832   const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
3833   if (!MergeCondStoresAggressively &&
3834       (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
3835        !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
3836     return false;
3837 
3838   // If PostBB has more than two predecessors, we need to split it so we can
3839   // sink the store.
3840   if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
3841     // We know that QFB's only successor is PostBB. And QFB has a single
3842     // predecessor. If QTB exists, then its only successor is also PostBB.
3843     // If QTB does not exist, then QFB's only predecessor has a conditional
3844     // branch to QFB and PostBB.
3845     BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
3846     BasicBlock *NewBB =
3847         SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
3848     if (!NewBB)
3849       return false;
3850     PostBB = NewBB;
3851   }
3852 
3853   // OK, we're going to sink the stores to PostBB. The store has to be
3854   // conditional though, so first create the predicate.
3855   Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
3856                      ->getCondition();
3857   Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3858                      ->getCondition();
3859 
3860   Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
3861                                                 PStore->getParent());
3862   Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
3863                                                 QStore->getParent(), PPHI);
3864 
3865   IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
3866 
3867   Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
3868   Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
3869 
3870   if (InvertPCond)
3871     PPred = QB.CreateNot(PPred);
3872   if (InvertQCond)
3873     QPred = QB.CreateNot(QPred);
3874   Value *CombinedPred = QB.CreateOr(PPred, QPred);
3875 
3876   auto *T = SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(),
3877                                       /*Unreachable=*/false,
3878                                       /*BranchWeights=*/nullptr, DTU);
3879   QB.SetInsertPoint(T);
3880   StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3881   SI->setAAMetadata(PStore->getAAMetadata().merge(QStore->getAAMetadata()));
3882   // Choose the minimum alignment. If we could prove both stores execute, we
3883   // could use biggest one.  In this case, though, we only know that one of the
3884   // stores executes.  And we don't know it's safe to take the alignment from a
3885   // store that doesn't execute.
3886   SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
3887 
3888   QStore->eraseFromParent();
3889   PStore->eraseFromParent();
3890 
3891   return true;
3892 }
3893 
3894 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
3895                                    DomTreeUpdater *DTU, const DataLayout &DL,
3896                                    const TargetTransformInfo &TTI) {
3897   // The intention here is to find diamonds or triangles (see below) where each
3898   // conditional block contains a store to the same address. Both of these
3899   // stores are conditional, so they can't be unconditionally sunk. But it may
3900   // be profitable to speculatively sink the stores into one merged store at the
3901   // end, and predicate the merged store on the union of the two conditions of
3902   // PBI and QBI.
3903   //
3904   // This can reduce the number of stores executed if both of the conditions are
3905   // true, and can allow the blocks to become small enough to be if-converted.
3906   // This optimization will also chain, so that ladders of test-and-set
3907   // sequences can be if-converted away.
3908   //
3909   // We only deal with simple diamonds or triangles:
3910   //
3911   //     PBI       or      PBI        or a combination of the two
3912   //    /   \               | \
3913   //   PTB  PFB             |  PFB
3914   //    \   /               | /
3915   //     QBI                QBI
3916   //    /  \                | \
3917   //   QTB  QFB             |  QFB
3918   //    \  /                | /
3919   //    PostBB            PostBB
3920   //
3921   // We model triangles as a type of diamond with a nullptr "true" block.
3922   // Triangles are canonicalized so that the fallthrough edge is represented by
3923   // a true condition, as in the diagram above.
3924   BasicBlock *PTB = PBI->getSuccessor(0);
3925   BasicBlock *PFB = PBI->getSuccessor(1);
3926   BasicBlock *QTB = QBI->getSuccessor(0);
3927   BasicBlock *QFB = QBI->getSuccessor(1);
3928   BasicBlock *PostBB = QFB->getSingleSuccessor();
3929 
3930   // Make sure we have a good guess for PostBB. If QTB's only successor is
3931   // QFB, then QFB is a better PostBB.
3932   if (QTB->getSingleSuccessor() == QFB)
3933     PostBB = QFB;
3934 
3935   // If we couldn't find a good PostBB, stop.
3936   if (!PostBB)
3937     return false;
3938 
3939   bool InvertPCond = false, InvertQCond = false;
3940   // Canonicalize fallthroughs to the true branches.
3941   if (PFB == QBI->getParent()) {
3942     std::swap(PFB, PTB);
3943     InvertPCond = true;
3944   }
3945   if (QFB == PostBB) {
3946     std::swap(QFB, QTB);
3947     InvertQCond = true;
3948   }
3949 
3950   // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3951   // and QFB may not. Model fallthroughs as a nullptr block.
3952   if (PTB == QBI->getParent())
3953     PTB = nullptr;
3954   if (QTB == PostBB)
3955     QTB = nullptr;
3956 
3957   // Legality bailouts. We must have at least the non-fallthrough blocks and
3958   // the post-dominating block, and the non-fallthroughs must only have one
3959   // predecessor.
3960   auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
3961     return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
3962   };
3963   if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
3964       !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3965     return false;
3966   if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3967       (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3968     return false;
3969   if (!QBI->getParent()->hasNUses(2))
3970     return false;
3971 
3972   // OK, this is a sequence of two diamonds or triangles.
3973   // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
3974   SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
3975   for (auto *BB : {PTB, PFB}) {
3976     if (!BB)
3977       continue;
3978     for (auto &I : *BB)
3979       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3980         PStoreAddresses.insert(SI->getPointerOperand());
3981   }
3982   for (auto *BB : {QTB, QFB}) {
3983     if (!BB)
3984       continue;
3985     for (auto &I : *BB)
3986       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3987         QStoreAddresses.insert(SI->getPointerOperand());
3988   }
3989 
3990   set_intersect(PStoreAddresses, QStoreAddresses);
3991   // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3992   // clear what it contains.
3993   auto &CommonAddresses = PStoreAddresses;
3994 
3995   bool Changed = false;
3996   for (auto *Address : CommonAddresses)
3997     Changed |=
3998         mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
3999                                        InvertPCond, InvertQCond, DTU, DL, TTI);
4000   return Changed;
4001 }
4002 
4003 /// If the previous block ended with a widenable branch, determine if reusing
4004 /// the target block is profitable and legal.  This will have the effect of
4005 /// "widening" PBI, but doesn't require us to reason about hosting safety.
4006 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
4007                                            DomTreeUpdater *DTU) {
4008   // TODO: This can be generalized in two important ways:
4009   // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4010   //    values from the PBI edge.
4011   // 2) We can sink side effecting instructions into BI's fallthrough
4012   //    successor provided they doesn't contribute to computation of
4013   //    BI's condition.
4014   Value *CondWB, *WC;
4015   BasicBlock *IfTrueBB, *IfFalseBB;
4016   if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) ||
4017       IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor())
4018     return false;
4019   if (!IfFalseBB->phis().empty())
4020     return false; // TODO
4021   // Use lambda to lazily compute expensive condition after cheap ones.
4022   auto NoSideEffects = [](BasicBlock &BB) {
4023     return llvm::none_of(BB, [](const Instruction &I) {
4024         return I.mayWriteToMemory() || I.mayHaveSideEffects();
4025       });
4026   };
4027   if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4028       BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4029       NoSideEffects(*BI->getParent())) {
4030     auto *OldSuccessor = BI->getSuccessor(1);
4031     OldSuccessor->removePredecessor(BI->getParent());
4032     BI->setSuccessor(1, IfFalseBB);
4033     if (DTU)
4034       DTU->applyUpdates(
4035           {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4036            {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4037     return true;
4038   }
4039   if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4040       BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4041       NoSideEffects(*BI->getParent())) {
4042     auto *OldSuccessor = BI->getSuccessor(0);
4043     OldSuccessor->removePredecessor(BI->getParent());
4044     BI->setSuccessor(0, IfFalseBB);
4045     if (DTU)
4046       DTU->applyUpdates(
4047           {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4048            {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4049     return true;
4050   }
4051   return false;
4052 }
4053 
4054 /// If we have a conditional branch as a predecessor of another block,
4055 /// this function tries to simplify it.  We know
4056 /// that PBI and BI are both conditional branches, and BI is in one of the
4057 /// successor blocks of PBI - PBI branches to BI.
4058 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
4059                                            DomTreeUpdater *DTU,
4060                                            const DataLayout &DL,
4061                                            const TargetTransformInfo &TTI) {
4062   assert(PBI->isConditional() && BI->isConditional());
4063   BasicBlock *BB = BI->getParent();
4064 
4065   // If this block ends with a branch instruction, and if there is a
4066   // predecessor that ends on a branch of the same condition, make
4067   // this conditional branch redundant.
4068   if (PBI->getCondition() == BI->getCondition() &&
4069       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4070     // Okay, the outcome of this conditional branch is statically
4071     // knowable.  If this block had a single pred, handle specially, otherwise
4072     // FoldCondBranchOnValueKnownInPredecessor() will handle it.
4073     if (BB->getSinglePredecessor()) {
4074       // Turn this into a branch on constant.
4075       bool CondIsTrue = PBI->getSuccessor(0) == BB;
4076       BI->setCondition(
4077           ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4078       return true; // Nuke the branch on constant.
4079     }
4080   }
4081 
4082   // If the previous block ended with a widenable branch, determine if reusing
4083   // the target block is profitable and legal.  This will have the effect of
4084   // "widening" PBI, but doesn't require us to reason about hosting safety.
4085   if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4086     return true;
4087 
4088   if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
4089     if (CE->canTrap())
4090       return false;
4091 
4092   // If both branches are conditional and both contain stores to the same
4093   // address, remove the stores from the conditionals and create a conditional
4094   // merged store at the end.
4095   if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4096     return true;
4097 
4098   // If this is a conditional branch in an empty block, and if any
4099   // predecessors are a conditional branch to one of our destinations,
4100   // fold the conditions into logical ops and one cond br.
4101 
4102   // Ignore dbg intrinsics.
4103   if (&*BB->instructionsWithoutDebug(false).begin() != BI)
4104     return false;
4105 
4106   int PBIOp, BIOp;
4107   if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4108     PBIOp = 0;
4109     BIOp = 0;
4110   } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4111     PBIOp = 0;
4112     BIOp = 1;
4113   } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4114     PBIOp = 1;
4115     BIOp = 0;
4116   } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4117     PBIOp = 1;
4118     BIOp = 1;
4119   } else {
4120     return false;
4121   }
4122 
4123   // Check to make sure that the other destination of this branch
4124   // isn't BB itself.  If so, this is an infinite loop that will
4125   // keep getting unwound.
4126   if (PBI->getSuccessor(PBIOp) == BB)
4127     return false;
4128 
4129   // Do not perform this transformation if it would require
4130   // insertion of a large number of select instructions. For targets
4131   // without predication/cmovs, this is a big pessimization.
4132 
4133   // Also do not perform this transformation if any phi node in the common
4134   // destination block can trap when reached by BB or PBB (PR17073). In that
4135   // case, it would be unsafe to hoist the operation into a select instruction.
4136 
4137   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4138   BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4139   unsigned NumPhis = 0;
4140   for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4141        ++II, ++NumPhis) {
4142     if (NumPhis > 2) // Disable this xform.
4143       return false;
4144 
4145     PHINode *PN = cast<PHINode>(II);
4146     Value *BIV = PN->getIncomingValueForBlock(BB);
4147     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
4148       if (CE->canTrap())
4149         return false;
4150 
4151     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
4152     Value *PBIV = PN->getIncomingValue(PBBIdx);
4153     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
4154       if (CE->canTrap())
4155         return false;
4156   }
4157 
4158   // Finally, if everything is ok, fold the branches to logical ops.
4159   BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4160 
4161   LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4162                     << "AND: " << *BI->getParent());
4163 
4164   SmallVector<DominatorTree::UpdateType, 5> Updates;
4165 
4166   // If OtherDest *is* BB, then BB is a basic block with a single conditional
4167   // branch in it, where one edge (OtherDest) goes back to itself but the other
4168   // exits.  We don't *know* that the program avoids the infinite loop
4169   // (even though that seems likely).  If we do this xform naively, we'll end up
4170   // recursively unpeeling the loop.  Since we know that (after the xform is
4171   // done) that the block *is* infinite if reached, we just make it an obviously
4172   // infinite loop with no cond branch.
4173   if (OtherDest == BB) {
4174     // Insert it at the end of the function, because it's either code,
4175     // or it won't matter if it's hot. :)
4176     BasicBlock *InfLoopBlock =
4177         BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4178     BranchInst::Create(InfLoopBlock, InfLoopBlock);
4179     if (DTU)
4180       Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4181     OtherDest = InfLoopBlock;
4182   }
4183 
4184   LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4185 
4186   // BI may have other predecessors.  Because of this, we leave
4187   // it alone, but modify PBI.
4188 
4189   // Make sure we get to CommonDest on True&True directions.
4190   Value *PBICond = PBI->getCondition();
4191   IRBuilder<NoFolder> Builder(PBI);
4192   if (PBIOp)
4193     PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4194 
4195   Value *BICond = BI->getCondition();
4196   if (BIOp)
4197     BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4198 
4199   // Merge the conditions.
4200   Value *Cond =
4201       createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4202 
4203   // Modify PBI to branch on the new condition to the new dests.
4204   PBI->setCondition(Cond);
4205   PBI->setSuccessor(0, CommonDest);
4206   PBI->setSuccessor(1, OtherDest);
4207 
4208   if (DTU) {
4209     Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4210     Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4211 
4212     DTU->applyUpdates(Updates);
4213   }
4214 
4215   // Update branch weight for PBI.
4216   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4217   uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4218   bool HasWeights =
4219       extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4220                              SuccTrueWeight, SuccFalseWeight);
4221   if (HasWeights) {
4222     PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4223     PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4224     SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4225     SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4226     // The weight to CommonDest should be PredCommon * SuccTotal +
4227     //                                    PredOther * SuccCommon.
4228     // The weight to OtherDest should be PredOther * SuccOther.
4229     uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4230                                   PredOther * SuccCommon,
4231                               PredOther * SuccOther};
4232     // Halve the weights if any of them cannot fit in an uint32_t
4233     FitWeights(NewWeights);
4234 
4235     setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
4236   }
4237 
4238   // OtherDest may have phi nodes.  If so, add an entry from PBI's
4239   // block that are identical to the entries for BI's block.
4240   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
4241 
4242   // We know that the CommonDest already had an edge from PBI to
4243   // it.  If it has PHIs though, the PHIs may have different
4244   // entries for BB and PBI's BB.  If so, insert a select to make
4245   // them agree.
4246   for (PHINode &PN : CommonDest->phis()) {
4247     Value *BIV = PN.getIncomingValueForBlock(BB);
4248     unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
4249     Value *PBIV = PN.getIncomingValue(PBBIdx);
4250     if (BIV != PBIV) {
4251       // Insert a select in PBI to pick the right value.
4252       SelectInst *NV = cast<SelectInst>(
4253           Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
4254       PN.setIncomingValue(PBBIdx, NV);
4255       // Although the select has the same condition as PBI, the original branch
4256       // weights for PBI do not apply to the new select because the select's
4257       // 'logical' edges are incoming edges of the phi that is eliminated, not
4258       // the outgoing edges of PBI.
4259       if (HasWeights) {
4260         uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4261         uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4262         uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4263         uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4264         // The weight to PredCommonDest should be PredCommon * SuccTotal.
4265         // The weight to PredOtherDest should be PredOther * SuccCommon.
4266         uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
4267                                   PredOther * SuccCommon};
4268 
4269         FitWeights(NewWeights);
4270 
4271         setBranchWeights(NV, NewWeights[0], NewWeights[1]);
4272       }
4273     }
4274   }
4275 
4276   LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
4277   LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4278 
4279   // This basic block is probably dead.  We know it has at least
4280   // one fewer predecessor.
4281   return true;
4282 }
4283 
4284 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
4285 // true or to FalseBB if Cond is false.
4286 // Takes care of updating the successors and removing the old terminator.
4287 // Also makes sure not to introduce new successors by assuming that edges to
4288 // non-successor TrueBBs and FalseBBs aren't reachable.
4289 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm,
4290                                                 Value *Cond, BasicBlock *TrueBB,
4291                                                 BasicBlock *FalseBB,
4292                                                 uint32_t TrueWeight,
4293                                                 uint32_t FalseWeight) {
4294   auto *BB = OldTerm->getParent();
4295   // Remove any superfluous successor edges from the CFG.
4296   // First, figure out which successors to preserve.
4297   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
4298   // successor.
4299   BasicBlock *KeepEdge1 = TrueBB;
4300   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
4301 
4302   SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
4303 
4304   // Then remove the rest.
4305   for (BasicBlock *Succ : successors(OldTerm)) {
4306     // Make sure only to keep exactly one copy of each edge.
4307     if (Succ == KeepEdge1)
4308       KeepEdge1 = nullptr;
4309     else if (Succ == KeepEdge2)
4310       KeepEdge2 = nullptr;
4311     else {
4312       Succ->removePredecessor(BB,
4313                               /*KeepOneInputPHIs=*/true);
4314 
4315       if (Succ != TrueBB && Succ != FalseBB)
4316         RemovedSuccessors.insert(Succ);
4317     }
4318   }
4319 
4320   IRBuilder<> Builder(OldTerm);
4321   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
4322 
4323   // Insert an appropriate new terminator.
4324   if (!KeepEdge1 && !KeepEdge2) {
4325     if (TrueBB == FalseBB) {
4326       // We were only looking for one successor, and it was present.
4327       // Create an unconditional branch to it.
4328       Builder.CreateBr(TrueBB);
4329     } else {
4330       // We found both of the successors we were looking for.
4331       // Create a conditional branch sharing the condition of the select.
4332       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
4333       if (TrueWeight != FalseWeight)
4334         setBranchWeights(NewBI, TrueWeight, FalseWeight);
4335     }
4336   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
4337     // Neither of the selected blocks were successors, so this
4338     // terminator must be unreachable.
4339     new UnreachableInst(OldTerm->getContext(), OldTerm);
4340   } else {
4341     // One of the selected values was a successor, but the other wasn't.
4342     // Insert an unconditional branch to the one that was found;
4343     // the edge to the one that wasn't must be unreachable.
4344     if (!KeepEdge1) {
4345       // Only TrueBB was found.
4346       Builder.CreateBr(TrueBB);
4347     } else {
4348       // Only FalseBB was found.
4349       Builder.CreateBr(FalseBB);
4350     }
4351   }
4352 
4353   EraseTerminatorAndDCECond(OldTerm);
4354 
4355   if (DTU) {
4356     SmallVector<DominatorTree::UpdateType, 2> Updates;
4357     Updates.reserve(RemovedSuccessors.size());
4358     for (auto *RemovedSuccessor : RemovedSuccessors)
4359       Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
4360     DTU->applyUpdates(Updates);
4361   }
4362 
4363   return true;
4364 }
4365 
4366 // Replaces
4367 //   (switch (select cond, X, Y)) on constant X, Y
4368 // with a branch - conditional if X and Y lead to distinct BBs,
4369 // unconditional otherwise.
4370 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI,
4371                                             SelectInst *Select) {
4372   // Check for constant integer values in the select.
4373   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
4374   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
4375   if (!TrueVal || !FalseVal)
4376     return false;
4377 
4378   // Find the relevant condition and destinations.
4379   Value *Condition = Select->getCondition();
4380   BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
4381   BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
4382 
4383   // Get weight for TrueBB and FalseBB.
4384   uint32_t TrueWeight = 0, FalseWeight = 0;
4385   SmallVector<uint64_t, 8> Weights;
4386   bool HasWeights = HasBranchWeights(SI);
4387   if (HasWeights) {
4388     GetBranchWeights(SI, Weights);
4389     if (Weights.size() == 1 + SI->getNumCases()) {
4390       TrueWeight =
4391           (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
4392       FalseWeight =
4393           (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
4394     }
4395   }
4396 
4397   // Perform the actual simplification.
4398   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
4399                                     FalseWeight);
4400 }
4401 
4402 // Replaces
4403 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
4404 //                             blockaddress(@fn, BlockB)))
4405 // with
4406 //   (br cond, BlockA, BlockB).
4407 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI,
4408                                                 SelectInst *SI) {
4409   // Check that both operands of the select are block addresses.
4410   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
4411   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
4412   if (!TBA || !FBA)
4413     return false;
4414 
4415   // Extract the actual blocks.
4416   BasicBlock *TrueBB = TBA->getBasicBlock();
4417   BasicBlock *FalseBB = FBA->getBasicBlock();
4418 
4419   // Perform the actual simplification.
4420   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
4421                                     0);
4422 }
4423 
4424 /// This is called when we find an icmp instruction
4425 /// (a seteq/setne with a constant) as the only instruction in a
4426 /// block that ends with an uncond branch.  We are looking for a very specific
4427 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
4428 /// this case, we merge the first two "or's of icmp" into a switch, but then the
4429 /// default value goes to an uncond block with a seteq in it, we get something
4430 /// like:
4431 ///
4432 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
4433 /// DEFAULT:
4434 ///   %tmp = icmp eq i8 %A, 92
4435 ///   br label %end
4436 /// end:
4437 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
4438 ///
4439 /// We prefer to split the edge to 'end' so that there is a true/false entry to
4440 /// the PHI, merging the third icmp into the switch.
4441 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
4442     ICmpInst *ICI, IRBuilder<> &Builder) {
4443   BasicBlock *BB = ICI->getParent();
4444 
4445   // If the block has any PHIs in it or the icmp has multiple uses, it is too
4446   // complex.
4447   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
4448     return false;
4449 
4450   Value *V = ICI->getOperand(0);
4451   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
4452 
4453   // The pattern we're looking for is where our only predecessor is a switch on
4454   // 'V' and this block is the default case for the switch.  In this case we can
4455   // fold the compared value into the switch to simplify things.
4456   BasicBlock *Pred = BB->getSinglePredecessor();
4457   if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
4458     return false;
4459 
4460   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
4461   if (SI->getCondition() != V)
4462     return false;
4463 
4464   // If BB is reachable on a non-default case, then we simply know the value of
4465   // V in this block.  Substitute it and constant fold the icmp instruction
4466   // away.
4467   if (SI->getDefaultDest() != BB) {
4468     ConstantInt *VVal = SI->findCaseDest(BB);
4469     assert(VVal && "Should have a unique destination value");
4470     ICI->setOperand(0, VVal);
4471 
4472     if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
4473       ICI->replaceAllUsesWith(V);
4474       ICI->eraseFromParent();
4475     }
4476     // BB is now empty, so it is likely to simplify away.
4477     return requestResimplify();
4478   }
4479 
4480   // Ok, the block is reachable from the default dest.  If the constant we're
4481   // comparing exists in one of the other edges, then we can constant fold ICI
4482   // and zap it.
4483   if (SI->findCaseValue(Cst) != SI->case_default()) {
4484     Value *V;
4485     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4486       V = ConstantInt::getFalse(BB->getContext());
4487     else
4488       V = ConstantInt::getTrue(BB->getContext());
4489 
4490     ICI->replaceAllUsesWith(V);
4491     ICI->eraseFromParent();
4492     // BB is now empty, so it is likely to simplify away.
4493     return requestResimplify();
4494   }
4495 
4496   // The use of the icmp has to be in the 'end' block, by the only PHI node in
4497   // the block.
4498   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
4499   PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
4500   if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
4501       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
4502     return false;
4503 
4504   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
4505   // true in the PHI.
4506   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
4507   Constant *NewCst = ConstantInt::getFalse(BB->getContext());
4508 
4509   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4510     std::swap(DefaultCst, NewCst);
4511 
4512   // Replace ICI (which is used by the PHI for the default value) with true or
4513   // false depending on if it is EQ or NE.
4514   ICI->replaceAllUsesWith(DefaultCst);
4515   ICI->eraseFromParent();
4516 
4517   SmallVector<DominatorTree::UpdateType, 2> Updates;
4518 
4519   // Okay, the switch goes to this block on a default value.  Add an edge from
4520   // the switch to the merge point on the compared value.
4521   BasicBlock *NewBB =
4522       BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
4523   {
4524     SwitchInstProfUpdateWrapper SIW(*SI);
4525     auto W0 = SIW.getSuccessorWeight(0);
4526     SwitchInstProfUpdateWrapper::CaseWeightOpt NewW;
4527     if (W0) {
4528       NewW = ((uint64_t(*W0) + 1) >> 1);
4529       SIW.setSuccessorWeight(0, *NewW);
4530     }
4531     SIW.addCase(Cst, NewBB, NewW);
4532     if (DTU)
4533       Updates.push_back({DominatorTree::Insert, Pred, NewBB});
4534   }
4535 
4536   // NewBB branches to the phi block, add the uncond branch and the phi entry.
4537   Builder.SetInsertPoint(NewBB);
4538   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
4539   Builder.CreateBr(SuccBlock);
4540   PHIUse->addIncoming(NewCst, NewBB);
4541   if (DTU) {
4542     Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
4543     DTU->applyUpdates(Updates);
4544   }
4545   return true;
4546 }
4547 
4548 /// The specified branch is a conditional branch.
4549 /// Check to see if it is branching on an or/and chain of icmp instructions, and
4550 /// fold it into a switch instruction if so.
4551 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI,
4552                                                IRBuilder<> &Builder,
4553                                                const DataLayout &DL) {
4554   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
4555   if (!Cond)
4556     return false;
4557 
4558   // Change br (X == 0 | X == 1), T, F into a switch instruction.
4559   // If this is a bunch of seteq's or'd together, or if it's a bunch of
4560   // 'setne's and'ed together, collect them.
4561 
4562   // Try to gather values from a chain of and/or to be turned into a switch
4563   ConstantComparesGatherer ConstantCompare(Cond, DL);
4564   // Unpack the result
4565   SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
4566   Value *CompVal = ConstantCompare.CompValue;
4567   unsigned UsedICmps = ConstantCompare.UsedICmps;
4568   Value *ExtraCase = ConstantCompare.Extra;
4569 
4570   // If we didn't have a multiply compared value, fail.
4571   if (!CompVal)
4572     return false;
4573 
4574   // Avoid turning single icmps into a switch.
4575   if (UsedICmps <= 1)
4576     return false;
4577 
4578   bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value()));
4579 
4580   // There might be duplicate constants in the list, which the switch
4581   // instruction can't handle, remove them now.
4582   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
4583   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
4584 
4585   // If Extra was used, we require at least two switch values to do the
4586   // transformation.  A switch with one value is just a conditional branch.
4587   if (ExtraCase && Values.size() < 2)
4588     return false;
4589 
4590   // TODO: Preserve branch weight metadata, similarly to how
4591   // FoldValueComparisonIntoPredecessors preserves it.
4592 
4593   // Figure out which block is which destination.
4594   BasicBlock *DefaultBB = BI->getSuccessor(1);
4595   BasicBlock *EdgeBB = BI->getSuccessor(0);
4596   if (!TrueWhenEqual)
4597     std::swap(DefaultBB, EdgeBB);
4598 
4599   BasicBlock *BB = BI->getParent();
4600 
4601   LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
4602                     << " cases into SWITCH.  BB is:\n"
4603                     << *BB);
4604 
4605   SmallVector<DominatorTree::UpdateType, 2> Updates;
4606 
4607   // If there are any extra values that couldn't be folded into the switch
4608   // then we evaluate them with an explicit branch first. Split the block
4609   // right before the condbr to handle it.
4610   if (ExtraCase) {
4611     BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
4612                                    /*MSSAU=*/nullptr, "switch.early.test");
4613 
4614     // Remove the uncond branch added to the old block.
4615     Instruction *OldTI = BB->getTerminator();
4616     Builder.SetInsertPoint(OldTI);
4617 
4618     // There can be an unintended UB if extra values are Poison. Before the
4619     // transformation, extra values may not be evaluated according to the
4620     // condition, and it will not raise UB. But after transformation, we are
4621     // evaluating extra values before checking the condition, and it will raise
4622     // UB. It can be solved by adding freeze instruction to extra values.
4623     AssumptionCache *AC = Options.AC;
4624 
4625     if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
4626       ExtraCase = Builder.CreateFreeze(ExtraCase);
4627 
4628     if (TrueWhenEqual)
4629       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
4630     else
4631       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
4632 
4633     OldTI->eraseFromParent();
4634 
4635     if (DTU)
4636       Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
4637 
4638     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
4639     // for the edge we just added.
4640     AddPredecessorToBlock(EdgeBB, BB, NewBB);
4641 
4642     LLVM_DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
4643                       << "\nEXTRABB = " << *BB);
4644     BB = NewBB;
4645   }
4646 
4647   Builder.SetInsertPoint(BI);
4648   // Convert pointer to int before we switch.
4649   if (CompVal->getType()->isPointerTy()) {
4650     CompVal = Builder.CreatePtrToInt(
4651         CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
4652   }
4653 
4654   // Create the new switch instruction now.
4655   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
4656 
4657   // Add all of the 'cases' to the switch instruction.
4658   for (unsigned i = 0, e = Values.size(); i != e; ++i)
4659     New->addCase(Values[i], EdgeBB);
4660 
4661   // We added edges from PI to the EdgeBB.  As such, if there were any
4662   // PHI nodes in EdgeBB, they need entries to be added corresponding to
4663   // the number of edges added.
4664   for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
4665     PHINode *PN = cast<PHINode>(BBI);
4666     Value *InVal = PN->getIncomingValueForBlock(BB);
4667     for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
4668       PN->addIncoming(InVal, BB);
4669   }
4670 
4671   // Erase the old branch instruction.
4672   EraseTerminatorAndDCECond(BI);
4673   if (DTU)
4674     DTU->applyUpdates(Updates);
4675 
4676   LLVM_DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
4677   return true;
4678 }
4679 
4680 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
4681   if (isa<PHINode>(RI->getValue()))
4682     return simplifyCommonResume(RI);
4683   else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
4684            RI->getValue() == RI->getParent()->getFirstNonPHI())
4685     // The resume must unwind the exception that caused control to branch here.
4686     return simplifySingleResume(RI);
4687 
4688   return false;
4689 }
4690 
4691 // Check if cleanup block is empty
4692 static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) {
4693   for (Instruction &I : R) {
4694     auto *II = dyn_cast<IntrinsicInst>(&I);
4695     if (!II)
4696       return false;
4697 
4698     Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4699     switch (IntrinsicID) {
4700     case Intrinsic::dbg_declare:
4701     case Intrinsic::dbg_value:
4702     case Intrinsic::dbg_label:
4703     case Intrinsic::lifetime_end:
4704       break;
4705     default:
4706       return false;
4707     }
4708   }
4709   return true;
4710 }
4711 
4712 // Simplify resume that is shared by several landing pads (phi of landing pad).
4713 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
4714   BasicBlock *BB = RI->getParent();
4715 
4716   // Check that there are no other instructions except for debug and lifetime
4717   // intrinsics between the phi's and resume instruction.
4718   if (!isCleanupBlockEmpty(
4719           make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator())))
4720     return false;
4721 
4722   SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
4723   auto *PhiLPInst = cast<PHINode>(RI->getValue());
4724 
4725   // Check incoming blocks to see if any of them are trivial.
4726   for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
4727        Idx++) {
4728     auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
4729     auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
4730 
4731     // If the block has other successors, we can not delete it because
4732     // it has other dependents.
4733     if (IncomingBB->getUniqueSuccessor() != BB)
4734       continue;
4735 
4736     auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
4737     // Not the landing pad that caused the control to branch here.
4738     if (IncomingValue != LandingPad)
4739       continue;
4740 
4741     if (isCleanupBlockEmpty(
4742             make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
4743       TrivialUnwindBlocks.insert(IncomingBB);
4744   }
4745 
4746   // If no trivial unwind blocks, don't do any simplifications.
4747   if (TrivialUnwindBlocks.empty())
4748     return false;
4749 
4750   // Turn all invokes that unwind here into calls.
4751   for (auto *TrivialBB : TrivialUnwindBlocks) {
4752     // Blocks that will be simplified should be removed from the phi node.
4753     // Note there could be multiple edges to the resume block, and we need
4754     // to remove them all.
4755     while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
4756       BB->removePredecessor(TrivialBB, true);
4757 
4758     for (BasicBlock *Pred :
4759          llvm::make_early_inc_range(predecessors(TrivialBB))) {
4760       removeUnwindEdge(Pred, DTU);
4761       ++NumInvokes;
4762     }
4763 
4764     // In each SimplifyCFG run, only the current processed block can be erased.
4765     // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
4766     // of erasing TrivialBB, we only remove the branch to the common resume
4767     // block so that we can later erase the resume block since it has no
4768     // predecessors.
4769     TrivialBB->getTerminator()->eraseFromParent();
4770     new UnreachableInst(RI->getContext(), TrivialBB);
4771     if (DTU)
4772       DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
4773   }
4774 
4775   // Delete the resume block if all its predecessors have been removed.
4776   if (pred_empty(BB))
4777     DeleteDeadBlock(BB, DTU);
4778 
4779   return !TrivialUnwindBlocks.empty();
4780 }
4781 
4782 // Simplify resume that is only used by a single (non-phi) landing pad.
4783 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
4784   BasicBlock *BB = RI->getParent();
4785   auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
4786   assert(RI->getValue() == LPInst &&
4787          "Resume must unwind the exception that caused control to here");
4788 
4789   // Check that there are no other instructions except for debug intrinsics.
4790   if (!isCleanupBlockEmpty(
4791           make_range<Instruction *>(LPInst->getNextNode(), RI)))
4792     return false;
4793 
4794   // Turn all invokes that unwind here into calls and delete the basic block.
4795   for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
4796     removeUnwindEdge(Pred, DTU);
4797     ++NumInvokes;
4798   }
4799 
4800   // The landingpad is now unreachable.  Zap it.
4801   DeleteDeadBlock(BB, DTU);
4802   return true;
4803 }
4804 
4805 static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU) {
4806   // If this is a trivial cleanup pad that executes no instructions, it can be
4807   // eliminated.  If the cleanup pad continues to the caller, any predecessor
4808   // that is an EH pad will be updated to continue to the caller and any
4809   // predecessor that terminates with an invoke instruction will have its invoke
4810   // instruction converted to a call instruction.  If the cleanup pad being
4811   // simplified does not continue to the caller, each predecessor will be
4812   // updated to continue to the unwind destination of the cleanup pad being
4813   // simplified.
4814   BasicBlock *BB = RI->getParent();
4815   CleanupPadInst *CPInst = RI->getCleanupPad();
4816   if (CPInst->getParent() != BB)
4817     // This isn't an empty cleanup.
4818     return false;
4819 
4820   // We cannot kill the pad if it has multiple uses.  This typically arises
4821   // from unreachable basic blocks.
4822   if (!CPInst->hasOneUse())
4823     return false;
4824 
4825   // Check that there are no other instructions except for benign intrinsics.
4826   if (!isCleanupBlockEmpty(
4827           make_range<Instruction *>(CPInst->getNextNode(), RI)))
4828     return false;
4829 
4830   // If the cleanup return we are simplifying unwinds to the caller, this will
4831   // set UnwindDest to nullptr.
4832   BasicBlock *UnwindDest = RI->getUnwindDest();
4833   Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
4834 
4835   // We're about to remove BB from the control flow.  Before we do, sink any
4836   // PHINodes into the unwind destination.  Doing this before changing the
4837   // control flow avoids some potentially slow checks, since we can currently
4838   // be certain that UnwindDest and BB have no common predecessors (since they
4839   // are both EH pads).
4840   if (UnwindDest) {
4841     // First, go through the PHI nodes in UnwindDest and update any nodes that
4842     // reference the block we are removing
4843     for (PHINode &DestPN : UnwindDest->phis()) {
4844       int Idx = DestPN.getBasicBlockIndex(BB);
4845       // Since BB unwinds to UnwindDest, it has to be in the PHI node.
4846       assert(Idx != -1);
4847       // This PHI node has an incoming value that corresponds to a control
4848       // path through the cleanup pad we are removing.  If the incoming
4849       // value is in the cleanup pad, it must be a PHINode (because we
4850       // verified above that the block is otherwise empty).  Otherwise, the
4851       // value is either a constant or a value that dominates the cleanup
4852       // pad being removed.
4853       //
4854       // Because BB and UnwindDest are both EH pads, all of their
4855       // predecessors must unwind to these blocks, and since no instruction
4856       // can have multiple unwind destinations, there will be no overlap in
4857       // incoming blocks between SrcPN and DestPN.
4858       Value *SrcVal = DestPN.getIncomingValue(Idx);
4859       PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
4860 
4861       bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
4862       for (auto *Pred : predecessors(BB)) {
4863         Value *Incoming =
4864             NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
4865         DestPN.addIncoming(Incoming, Pred);
4866       }
4867     }
4868 
4869     // Sink any remaining PHI nodes directly into UnwindDest.
4870     Instruction *InsertPt = DestEHPad;
4871     for (PHINode &PN : make_early_inc_range(BB->phis())) {
4872       if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
4873         // If the PHI node has no uses or all of its uses are in this basic
4874         // block (meaning they are debug or lifetime intrinsics), just leave
4875         // it.  It will be erased when we erase BB below.
4876         continue;
4877 
4878       // Otherwise, sink this PHI node into UnwindDest.
4879       // Any predecessors to UnwindDest which are not already represented
4880       // must be back edges which inherit the value from the path through
4881       // BB.  In this case, the PHI value must reference itself.
4882       for (auto *pred : predecessors(UnwindDest))
4883         if (pred != BB)
4884           PN.addIncoming(&PN, pred);
4885       PN.moveBefore(InsertPt);
4886       // Also, add a dummy incoming value for the original BB itself,
4887       // so that the PHI is well-formed until we drop said predecessor.
4888       PN.addIncoming(UndefValue::get(PN.getType()), BB);
4889     }
4890   }
4891 
4892   std::vector<DominatorTree::UpdateType> Updates;
4893 
4894   // We use make_early_inc_range here because we will remove all predecessors.
4895   for (BasicBlock *PredBB : llvm::make_early_inc_range(predecessors(BB))) {
4896     if (UnwindDest == nullptr) {
4897       if (DTU) {
4898         DTU->applyUpdates(Updates);
4899         Updates.clear();
4900       }
4901       removeUnwindEdge(PredBB, DTU);
4902       ++NumInvokes;
4903     } else {
4904       BB->removePredecessor(PredBB);
4905       Instruction *TI = PredBB->getTerminator();
4906       TI->replaceUsesOfWith(BB, UnwindDest);
4907       if (DTU) {
4908         Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
4909         Updates.push_back({DominatorTree::Delete, PredBB, BB});
4910       }
4911     }
4912   }
4913 
4914   if (DTU)
4915     DTU->applyUpdates(Updates);
4916 
4917   DeleteDeadBlock(BB, DTU);
4918 
4919   return true;
4920 }
4921 
4922 // Try to merge two cleanuppads together.
4923 static bool mergeCleanupPad(CleanupReturnInst *RI) {
4924   // Skip any cleanuprets which unwind to caller, there is nothing to merge
4925   // with.
4926   BasicBlock *UnwindDest = RI->getUnwindDest();
4927   if (!UnwindDest)
4928     return false;
4929 
4930   // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
4931   // be safe to merge without code duplication.
4932   if (UnwindDest->getSinglePredecessor() != RI->getParent())
4933     return false;
4934 
4935   // Verify that our cleanuppad's unwind destination is another cleanuppad.
4936   auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
4937   if (!SuccessorCleanupPad)
4938     return false;
4939 
4940   CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
4941   // Replace any uses of the successor cleanupad with the predecessor pad
4942   // The only cleanuppad uses should be this cleanupret, it's cleanupret and
4943   // funclet bundle operands.
4944   SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
4945   // Remove the old cleanuppad.
4946   SuccessorCleanupPad->eraseFromParent();
4947   // Now, we simply replace the cleanupret with a branch to the unwind
4948   // destination.
4949   BranchInst::Create(UnwindDest, RI->getParent());
4950   RI->eraseFromParent();
4951 
4952   return true;
4953 }
4954 
4955 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
4956   // It is possible to transiantly have an undef cleanuppad operand because we
4957   // have deleted some, but not all, dead blocks.
4958   // Eventually, this block will be deleted.
4959   if (isa<UndefValue>(RI->getOperand(0)))
4960     return false;
4961 
4962   if (mergeCleanupPad(RI))
4963     return true;
4964 
4965   if (removeEmptyCleanup(RI, DTU))
4966     return true;
4967 
4968   return false;
4969 }
4970 
4971 // WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
4972 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
4973   BasicBlock *BB = UI->getParent();
4974 
4975   bool Changed = false;
4976 
4977   // If there are any instructions immediately before the unreachable that can
4978   // be removed, do so.
4979   while (UI->getIterator() != BB->begin()) {
4980     BasicBlock::iterator BBI = UI->getIterator();
4981     --BBI;
4982 
4983     if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI))
4984       break; // Can not drop any more instructions. We're done here.
4985     // Otherwise, this instruction can be freely erased,
4986     // even if it is not side-effect free.
4987 
4988     // Note that deleting EH's here is in fact okay, although it involves a bit
4989     // of subtle reasoning. If this inst is an EH, all the predecessors of this
4990     // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
4991     // and we can therefore guarantee this block will be erased.
4992 
4993     // Delete this instruction (any uses are guaranteed to be dead)
4994     BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
4995     BBI->eraseFromParent();
4996     Changed = true;
4997   }
4998 
4999   // If the unreachable instruction is the first in the block, take a gander
5000   // at all of the predecessors of this instruction, and simplify them.
5001   if (&BB->front() != UI)
5002     return Changed;
5003 
5004   std::vector<DominatorTree::UpdateType> Updates;
5005 
5006   SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
5007   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
5008     auto *Predecessor = Preds[i];
5009     Instruction *TI = Predecessor->getTerminator();
5010     IRBuilder<> Builder(TI);
5011     if (auto *BI = dyn_cast<BranchInst>(TI)) {
5012       // We could either have a proper unconditional branch,
5013       // or a degenerate conditional branch with matching destinations.
5014       if (all_of(BI->successors(),
5015                  [BB](auto *Successor) { return Successor == BB; })) {
5016         new UnreachableInst(TI->getContext(), TI);
5017         TI->eraseFromParent();
5018         Changed = true;
5019       } else {
5020         assert(BI->isConditional() && "Can't get here with an uncond branch.");
5021         Value* Cond = BI->getCondition();
5022         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5023                "The destinations are guaranteed to be different here.");
5024         if (BI->getSuccessor(0) == BB) {
5025           Builder.CreateAssumption(Builder.CreateNot(Cond));
5026           Builder.CreateBr(BI->getSuccessor(1));
5027         } else {
5028           assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
5029           Builder.CreateAssumption(Cond);
5030           Builder.CreateBr(BI->getSuccessor(0));
5031         }
5032         EraseTerminatorAndDCECond(BI);
5033         Changed = true;
5034       }
5035       if (DTU)
5036         Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5037     } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
5038       SwitchInstProfUpdateWrapper SU(*SI);
5039       for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
5040         if (i->getCaseSuccessor() != BB) {
5041           ++i;
5042           continue;
5043         }
5044         BB->removePredecessor(SU->getParent());
5045         i = SU.removeCase(i);
5046         e = SU->case_end();
5047         Changed = true;
5048       }
5049       // Note that the default destination can't be removed!
5050       if (DTU && SI->getDefaultDest() != BB)
5051         Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5052     } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
5053       if (II->getUnwindDest() == BB) {
5054         if (DTU) {
5055           DTU->applyUpdates(Updates);
5056           Updates.clear();
5057         }
5058         removeUnwindEdge(TI->getParent(), DTU);
5059         Changed = true;
5060       }
5061     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
5062       if (CSI->getUnwindDest() == BB) {
5063         if (DTU) {
5064           DTU->applyUpdates(Updates);
5065           Updates.clear();
5066         }
5067         removeUnwindEdge(TI->getParent(), DTU);
5068         Changed = true;
5069         continue;
5070       }
5071 
5072       for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
5073                                              E = CSI->handler_end();
5074            I != E; ++I) {
5075         if (*I == BB) {
5076           CSI->removeHandler(I);
5077           --I;
5078           --E;
5079           Changed = true;
5080         }
5081       }
5082       if (DTU)
5083         Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5084       if (CSI->getNumHandlers() == 0) {
5085         if (CSI->hasUnwindDest()) {
5086           // Redirect all predecessors of the block containing CatchSwitchInst
5087           // to instead branch to the CatchSwitchInst's unwind destination.
5088           if (DTU) {
5089             for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
5090               Updates.push_back({DominatorTree::Insert,
5091                                  PredecessorOfPredecessor,
5092                                  CSI->getUnwindDest()});
5093               Updates.push_back({DominatorTree::Delete,
5094                                  PredecessorOfPredecessor, Predecessor});
5095             }
5096           }
5097           Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
5098         } else {
5099           // Rewrite all preds to unwind to caller (or from invoke to call).
5100           if (DTU) {
5101             DTU->applyUpdates(Updates);
5102             Updates.clear();
5103           }
5104           SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
5105           for (BasicBlock *EHPred : EHPreds)
5106             removeUnwindEdge(EHPred, DTU);
5107         }
5108         // The catchswitch is no longer reachable.
5109         new UnreachableInst(CSI->getContext(), CSI);
5110         CSI->eraseFromParent();
5111         Changed = true;
5112       }
5113     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
5114       (void)CRI;
5115       assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
5116              "Expected to always have an unwind to BB.");
5117       if (DTU)
5118         Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5119       new UnreachableInst(TI->getContext(), TI);
5120       TI->eraseFromParent();
5121       Changed = true;
5122     }
5123   }
5124 
5125   if (DTU)
5126     DTU->applyUpdates(Updates);
5127 
5128   // If this block is now dead, remove it.
5129   if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
5130     DeleteDeadBlock(BB, DTU);
5131     return true;
5132   }
5133 
5134   return Changed;
5135 }
5136 
5137 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
5138   assert(Cases.size() >= 1);
5139 
5140   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
5141   for (size_t I = 1, E = Cases.size(); I != E; ++I) {
5142     if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
5143       return false;
5144   }
5145   return true;
5146 }
5147 
5148 static void createUnreachableSwitchDefault(SwitchInst *Switch,
5149                                            DomTreeUpdater *DTU) {
5150   LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
5151   auto *BB = Switch->getParent();
5152   auto *OrigDefaultBlock = Switch->getDefaultDest();
5153   OrigDefaultBlock->removePredecessor(BB);
5154   BasicBlock *NewDefaultBlock = BasicBlock::Create(
5155       BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(),
5156       OrigDefaultBlock);
5157   new UnreachableInst(Switch->getContext(), NewDefaultBlock);
5158   Switch->setDefaultDest(&*NewDefaultBlock);
5159   if (DTU) {
5160     SmallVector<DominatorTree::UpdateType, 2> Updates;
5161     Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock});
5162     if (!is_contained(successors(BB), OrigDefaultBlock))
5163       Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock});
5164     DTU->applyUpdates(Updates);
5165   }
5166 }
5167 
5168 /// Turn a switch with two reachable destinations into an integer range
5169 /// comparison and branch.
5170 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI,
5171                                              IRBuilder<> &Builder) {
5172   assert(SI->getNumCases() > 1 && "Degenerate switch?");
5173 
5174   bool HasDefault =
5175       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5176 
5177   auto *BB = SI->getParent();
5178 
5179   // Partition the cases into two sets with different destinations.
5180   BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
5181   BasicBlock *DestB = nullptr;
5182   SmallVector<ConstantInt *, 16> CasesA;
5183   SmallVector<ConstantInt *, 16> CasesB;
5184 
5185   for (auto Case : SI->cases()) {
5186     BasicBlock *Dest = Case.getCaseSuccessor();
5187     if (!DestA)
5188       DestA = Dest;
5189     if (Dest == DestA) {
5190       CasesA.push_back(Case.getCaseValue());
5191       continue;
5192     }
5193     if (!DestB)
5194       DestB = Dest;
5195     if (Dest == DestB) {
5196       CasesB.push_back(Case.getCaseValue());
5197       continue;
5198     }
5199     return false; // More than two destinations.
5200   }
5201 
5202   assert(DestA && DestB &&
5203          "Single-destination switch should have been folded.");
5204   assert(DestA != DestB);
5205   assert(DestB != SI->getDefaultDest());
5206   assert(!CasesB.empty() && "There must be non-default cases.");
5207   assert(!CasesA.empty() || HasDefault);
5208 
5209   // Figure out if one of the sets of cases form a contiguous range.
5210   SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
5211   BasicBlock *ContiguousDest = nullptr;
5212   BasicBlock *OtherDest = nullptr;
5213   if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
5214     ContiguousCases = &CasesA;
5215     ContiguousDest = DestA;
5216     OtherDest = DestB;
5217   } else if (CasesAreContiguous(CasesB)) {
5218     ContiguousCases = &CasesB;
5219     ContiguousDest = DestB;
5220     OtherDest = DestA;
5221   } else
5222     return false;
5223 
5224   // Start building the compare and branch.
5225 
5226   Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
5227   Constant *NumCases =
5228       ConstantInt::get(Offset->getType(), ContiguousCases->size());
5229 
5230   Value *Sub = SI->getCondition();
5231   if (!Offset->isNullValue())
5232     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
5233 
5234   Value *Cmp;
5235   // If NumCases overflowed, then all possible values jump to the successor.
5236   if (NumCases->isNullValue() && !ContiguousCases->empty())
5237     Cmp = ConstantInt::getTrue(SI->getContext());
5238   else
5239     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
5240   BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
5241 
5242   // Update weight for the newly-created conditional branch.
5243   if (HasBranchWeights(SI)) {
5244     SmallVector<uint64_t, 8> Weights;
5245     GetBranchWeights(SI, Weights);
5246     if (Weights.size() == 1 + SI->getNumCases()) {
5247       uint64_t TrueWeight = 0;
5248       uint64_t FalseWeight = 0;
5249       for (size_t I = 0, E = Weights.size(); I != E; ++I) {
5250         if (SI->getSuccessor(I) == ContiguousDest)
5251           TrueWeight += Weights[I];
5252         else
5253           FalseWeight += Weights[I];
5254       }
5255       while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
5256         TrueWeight /= 2;
5257         FalseWeight /= 2;
5258       }
5259       setBranchWeights(NewBI, TrueWeight, FalseWeight);
5260     }
5261   }
5262 
5263   // Prune obsolete incoming values off the successors' PHI nodes.
5264   for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
5265     unsigned PreviousEdges = ContiguousCases->size();
5266     if (ContiguousDest == SI->getDefaultDest())
5267       ++PreviousEdges;
5268     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
5269       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
5270   }
5271   for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
5272     unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
5273     if (OtherDest == SI->getDefaultDest())
5274       ++PreviousEdges;
5275     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
5276       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
5277   }
5278 
5279   // Clean up the default block - it may have phis or other instructions before
5280   // the unreachable terminator.
5281   if (!HasDefault)
5282     createUnreachableSwitchDefault(SI, DTU);
5283 
5284   auto *UnreachableDefault = SI->getDefaultDest();
5285 
5286   // Drop the switch.
5287   SI->eraseFromParent();
5288 
5289   if (!HasDefault && DTU)
5290     DTU->applyUpdates({{DominatorTree::Delete, BB, UnreachableDefault}});
5291 
5292   return true;
5293 }
5294 
5295 /// Compute masked bits for the condition of a switch
5296 /// and use it to remove dead cases.
5297 static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU,
5298                                      AssumptionCache *AC,
5299                                      const DataLayout &DL) {
5300   Value *Cond = SI->getCondition();
5301   KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
5302 
5303   // We can also eliminate cases by determining that their values are outside of
5304   // the limited range of the condition based on how many significant (non-sign)
5305   // bits are in the condition value.
5306   unsigned MaxSignificantBitsInCond =
5307       ComputeMaxSignificantBits(Cond, DL, 0, AC, SI);
5308 
5309   // Gather dead cases.
5310   SmallVector<ConstantInt *, 8> DeadCases;
5311   SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
5312   SmallVector<BasicBlock *, 8> UniqueSuccessors;
5313   for (auto &Case : SI->cases()) {
5314     auto *Successor = Case.getCaseSuccessor();
5315     if (DTU) {
5316       if (!NumPerSuccessorCases.count(Successor))
5317         UniqueSuccessors.push_back(Successor);
5318       ++NumPerSuccessorCases[Successor];
5319     }
5320     const APInt &CaseVal = Case.getCaseValue()->getValue();
5321     if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
5322         (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
5323       DeadCases.push_back(Case.getCaseValue());
5324       if (DTU)
5325         --NumPerSuccessorCases[Successor];
5326       LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
5327                         << " is dead.\n");
5328     }
5329   }
5330 
5331   // If we can prove that the cases must cover all possible values, the
5332   // default destination becomes dead and we can remove it.  If we know some
5333   // of the bits in the value, we can use that to more precisely compute the
5334   // number of possible unique case values.
5335   bool HasDefault =
5336       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5337   const unsigned NumUnknownBits =
5338       Known.getBitWidth() - (Known.Zero | Known.One).countPopulation();
5339   assert(NumUnknownBits <= Known.getBitWidth());
5340   if (HasDefault && DeadCases.empty() &&
5341       NumUnknownBits < 64 /* avoid overflow */ &&
5342       SI->getNumCases() == (1ULL << NumUnknownBits)) {
5343     createUnreachableSwitchDefault(SI, DTU);
5344     return true;
5345   }
5346 
5347   if (DeadCases.empty())
5348     return false;
5349 
5350   SwitchInstProfUpdateWrapper SIW(*SI);
5351   for (ConstantInt *DeadCase : DeadCases) {
5352     SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
5353     assert(CaseI != SI->case_default() &&
5354            "Case was not found. Probably mistake in DeadCases forming.");
5355     // Prune unused values from PHI nodes.
5356     CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
5357     SIW.removeCase(CaseI);
5358   }
5359 
5360   if (DTU) {
5361     std::vector<DominatorTree::UpdateType> Updates;
5362     for (auto *Successor : UniqueSuccessors)
5363       if (NumPerSuccessorCases[Successor] == 0)
5364         Updates.push_back({DominatorTree::Delete, SI->getParent(), Successor});
5365     DTU->applyUpdates(Updates);
5366   }
5367 
5368   return true;
5369 }
5370 
5371 /// If BB would be eligible for simplification by
5372 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
5373 /// by an unconditional branch), look at the phi node for BB in the successor
5374 /// block and see if the incoming value is equal to CaseValue. If so, return
5375 /// the phi node, and set PhiIndex to BB's index in the phi node.
5376 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
5377                                               BasicBlock *BB, int *PhiIndex) {
5378   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
5379     return nullptr; // BB must be empty to be a candidate for simplification.
5380   if (!BB->getSinglePredecessor())
5381     return nullptr; // BB must be dominated by the switch.
5382 
5383   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
5384   if (!Branch || !Branch->isUnconditional())
5385     return nullptr; // Terminator must be unconditional branch.
5386 
5387   BasicBlock *Succ = Branch->getSuccessor(0);
5388 
5389   for (PHINode &PHI : Succ->phis()) {
5390     int Idx = PHI.getBasicBlockIndex(BB);
5391     assert(Idx >= 0 && "PHI has no entry for predecessor?");
5392 
5393     Value *InValue = PHI.getIncomingValue(Idx);
5394     if (InValue != CaseValue)
5395       continue;
5396 
5397     *PhiIndex = Idx;
5398     return &PHI;
5399   }
5400 
5401   return nullptr;
5402 }
5403 
5404 /// Try to forward the condition of a switch instruction to a phi node
5405 /// dominated by the switch, if that would mean that some of the destination
5406 /// blocks of the switch can be folded away. Return true if a change is made.
5407 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
5408   using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
5409 
5410   ForwardingNodesMap ForwardingNodes;
5411   BasicBlock *SwitchBlock = SI->getParent();
5412   bool Changed = false;
5413   for (auto &Case : SI->cases()) {
5414     ConstantInt *CaseValue = Case.getCaseValue();
5415     BasicBlock *CaseDest = Case.getCaseSuccessor();
5416 
5417     // Replace phi operands in successor blocks that are using the constant case
5418     // value rather than the switch condition variable:
5419     //   switchbb:
5420     //   switch i32 %x, label %default [
5421     //     i32 17, label %succ
5422     //   ...
5423     //   succ:
5424     //     %r = phi i32 ... [ 17, %switchbb ] ...
5425     // -->
5426     //     %r = phi i32 ... [ %x, %switchbb ] ...
5427 
5428     for (PHINode &Phi : CaseDest->phis()) {
5429       // This only works if there is exactly 1 incoming edge from the switch to
5430       // a phi. If there is >1, that means multiple cases of the switch map to 1
5431       // value in the phi, and that phi value is not the switch condition. Thus,
5432       // this transform would not make sense (the phi would be invalid because
5433       // a phi can't have different incoming values from the same block).
5434       int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
5435       if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
5436           count(Phi.blocks(), SwitchBlock) == 1) {
5437         Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
5438         Changed = true;
5439       }
5440     }
5441 
5442     // Collect phi nodes that are indirectly using this switch's case constants.
5443     int PhiIdx;
5444     if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
5445       ForwardingNodes[Phi].push_back(PhiIdx);
5446   }
5447 
5448   for (auto &ForwardingNode : ForwardingNodes) {
5449     PHINode *Phi = ForwardingNode.first;
5450     SmallVectorImpl<int> &Indexes = ForwardingNode.second;
5451     if (Indexes.size() < 2)
5452       continue;
5453 
5454     for (int Index : Indexes)
5455       Phi->setIncomingValue(Index, SI->getCondition());
5456     Changed = true;
5457   }
5458 
5459   return Changed;
5460 }
5461 
5462 /// Return true if the backend will be able to handle
5463 /// initializing an array of constants like C.
5464 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
5465   if (C->isThreadDependent())
5466     return false;
5467   if (C->isDLLImportDependent())
5468     return false;
5469 
5470   if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
5471       !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
5472       !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
5473     return false;
5474 
5475   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
5476     // Pointer casts and in-bounds GEPs will not prohibit the backend from
5477     // materializing the array of constants.
5478     Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets());
5479     if (StrippedC == C || !ValidLookupTableConstant(StrippedC, TTI))
5480       return false;
5481   }
5482 
5483   if (!TTI.shouldBuildLookupTablesForConstant(C))
5484     return false;
5485 
5486   return true;
5487 }
5488 
5489 /// If V is a Constant, return it. Otherwise, try to look up
5490 /// its constant value in ConstantPool, returning 0 if it's not there.
5491 static Constant *
5492 LookupConstant(Value *V,
5493                const SmallDenseMap<Value *, Constant *> &ConstantPool) {
5494   if (Constant *C = dyn_cast<Constant>(V))
5495     return C;
5496   return ConstantPool.lookup(V);
5497 }
5498 
5499 /// Try to fold instruction I into a constant. This works for
5500 /// simple instructions such as binary operations where both operands are
5501 /// constant or can be replaced by constants from the ConstantPool. Returns the
5502 /// resulting constant on success, 0 otherwise.
5503 static Constant *
5504 ConstantFold(Instruction *I, const DataLayout &DL,
5505              const SmallDenseMap<Value *, Constant *> &ConstantPool) {
5506   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
5507     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
5508     if (!A)
5509       return nullptr;
5510     if (A->isAllOnesValue())
5511       return LookupConstant(Select->getTrueValue(), ConstantPool);
5512     if (A->isNullValue())
5513       return LookupConstant(Select->getFalseValue(), ConstantPool);
5514     return nullptr;
5515   }
5516 
5517   SmallVector<Constant *, 4> COps;
5518   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
5519     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
5520       COps.push_back(A);
5521     else
5522       return nullptr;
5523   }
5524 
5525   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
5526     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
5527                                            COps[1], DL);
5528   }
5529 
5530   return ConstantFoldInstOperands(I, COps, DL);
5531 }
5532 
5533 /// Try to determine the resulting constant values in phi nodes
5534 /// at the common destination basic block, *CommonDest, for one of the case
5535 /// destionations CaseDest corresponding to value CaseVal (0 for the default
5536 /// case), of a switch instruction SI.
5537 static bool
5538 getCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
5539                BasicBlock **CommonDest,
5540                SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
5541                const DataLayout &DL, const TargetTransformInfo &TTI) {
5542   // The block from which we enter the common destination.
5543   BasicBlock *Pred = SI->getParent();
5544 
5545   // If CaseDest is empty except for some side-effect free instructions through
5546   // which we can constant-propagate the CaseVal, continue to its successor.
5547   SmallDenseMap<Value *, Constant *> ConstantPool;
5548   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
5549   for (Instruction &I : CaseDest->instructionsWithoutDebug(false)) {
5550     if (I.isTerminator()) {
5551       // If the terminator is a simple branch, continue to the next block.
5552       if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
5553         return false;
5554       Pred = CaseDest;
5555       CaseDest = I.getSuccessor(0);
5556     } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
5557       // Instruction is side-effect free and constant.
5558 
5559       // If the instruction has uses outside this block or a phi node slot for
5560       // the block, it is not safe to bypass the instruction since it would then
5561       // no longer dominate all its uses.
5562       for (auto &Use : I.uses()) {
5563         User *User = Use.getUser();
5564         if (Instruction *I = dyn_cast<Instruction>(User))
5565           if (I->getParent() == CaseDest)
5566             continue;
5567         if (PHINode *Phi = dyn_cast<PHINode>(User))
5568           if (Phi->getIncomingBlock(Use) == CaseDest)
5569             continue;
5570         return false;
5571       }
5572 
5573       ConstantPool.insert(std::make_pair(&I, C));
5574     } else {
5575       break;
5576     }
5577   }
5578 
5579   // If we did not have a CommonDest before, use the current one.
5580   if (!*CommonDest)
5581     *CommonDest = CaseDest;
5582   // If the destination isn't the common one, abort.
5583   if (CaseDest != *CommonDest)
5584     return false;
5585 
5586   // Get the values for this case from phi nodes in the destination block.
5587   for (PHINode &PHI : (*CommonDest)->phis()) {
5588     int Idx = PHI.getBasicBlockIndex(Pred);
5589     if (Idx == -1)
5590       continue;
5591 
5592     Constant *ConstVal =
5593         LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
5594     if (!ConstVal)
5595       return false;
5596 
5597     // Be conservative about which kinds of constants we support.
5598     if (!ValidLookupTableConstant(ConstVal, TTI))
5599       return false;
5600 
5601     Res.push_back(std::make_pair(&PHI, ConstVal));
5602   }
5603 
5604   return Res.size() > 0;
5605 }
5606 
5607 // Helper function used to add CaseVal to the list of cases that generate
5608 // Result. Returns the updated number of cases that generate this result.
5609 static size_t mapCaseToResult(ConstantInt *CaseVal,
5610                               SwitchCaseResultVectorTy &UniqueResults,
5611                               Constant *Result) {
5612   for (auto &I : UniqueResults) {
5613     if (I.first == Result) {
5614       I.second.push_back(CaseVal);
5615       return I.second.size();
5616     }
5617   }
5618   UniqueResults.push_back(
5619       std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
5620   return 1;
5621 }
5622 
5623 // Helper function that initializes a map containing
5624 // results for the PHI node of the common destination block for a switch
5625 // instruction. Returns false if multiple PHI nodes have been found or if
5626 // there is not a common destination block for the switch.
5627 static bool initializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
5628                                   BasicBlock *&CommonDest,
5629                                   SwitchCaseResultVectorTy &UniqueResults,
5630                                   Constant *&DefaultResult,
5631                                   const DataLayout &DL,
5632                                   const TargetTransformInfo &TTI,
5633                                   uintptr_t MaxUniqueResults) {
5634   for (auto &I : SI->cases()) {
5635     ConstantInt *CaseVal = I.getCaseValue();
5636 
5637     // Resulting value at phi nodes for this case value.
5638     SwitchCaseResultsTy Results;
5639     if (!getCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
5640                         DL, TTI))
5641       return false;
5642 
5643     // Only one value per case is permitted.
5644     if (Results.size() > 1)
5645       return false;
5646 
5647     // Add the case->result mapping to UniqueResults.
5648     const size_t NumCasesForResult =
5649         mapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
5650 
5651     // Early out if there are too many cases for this result.
5652     if (NumCasesForResult > MaxSwitchCasesPerResult)
5653       return false;
5654 
5655     // Early out if there are too many unique results.
5656     if (UniqueResults.size() > MaxUniqueResults)
5657       return false;
5658 
5659     // Check the PHI consistency.
5660     if (!PHI)
5661       PHI = Results[0].first;
5662     else if (PHI != Results[0].first)
5663       return false;
5664   }
5665   // Find the default result value.
5666   SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
5667   BasicBlock *DefaultDest = SI->getDefaultDest();
5668   getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
5669                  DL, TTI);
5670   // If the default value is not found abort unless the default destination
5671   // is unreachable.
5672   DefaultResult =
5673       DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
5674   if ((!DefaultResult &&
5675        !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
5676     return false;
5677 
5678   return true;
5679 }
5680 
5681 // Helper function that checks if it is possible to transform a switch with only
5682 // two cases (or two cases + default) that produces a result into a select.
5683 // TODO: Handle switches with more than 2 cases that map to the same result.
5684 static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector,
5685                                  Constant *DefaultResult, Value *Condition,
5686                                  IRBuilder<> &Builder) {
5687   // If we are selecting between only two cases transform into a simple
5688   // select or a two-way select if default is possible.
5689   // Example:
5690   // switch (a) {                  %0 = icmp eq i32 %a, 10
5691   //   case 10: return 42;         %1 = select i1 %0, i32 42, i32 4
5692   //   case 20: return 2;   ---->  %2 = icmp eq i32 %a, 20
5693   //   default: return 4;          %3 = select i1 %2, i32 2, i32 %1
5694   // }
5695   if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
5696       ResultVector[1].second.size() == 1) {
5697     ConstantInt *FirstCase = ResultVector[0].second[0];
5698     ConstantInt *SecondCase = ResultVector[1].second[0];
5699     Value *SelectValue = ResultVector[1].first;
5700     if (DefaultResult) {
5701       Value *ValueCompare =
5702           Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
5703       SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
5704                                          DefaultResult, "switch.select");
5705     }
5706     Value *ValueCompare =
5707         Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
5708     return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
5709                                 SelectValue, "switch.select");
5710   }
5711 
5712   // Handle the degenerate case where two cases have the same result value.
5713   if (ResultVector.size() == 1 && DefaultResult) {
5714     ArrayRef<ConstantInt *> CaseValues = ResultVector[0].second;
5715     unsigned CaseCount = CaseValues.size();
5716     // n bits group cases map to the same result:
5717     // case 0,4      -> Cond & 0b1..1011 == 0 ? result : default
5718     // case 0,2,4,6  -> Cond & 0b1..1001 == 0 ? result : default
5719     // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default
5720     if (isPowerOf2_32(CaseCount)) {
5721       ConstantInt *MinCaseVal = CaseValues[0];
5722       // Find mininal value.
5723       for (auto Case : CaseValues)
5724         if (Case->getValue().slt(MinCaseVal->getValue()))
5725           MinCaseVal = Case;
5726 
5727       // Mark the bits case number touched.
5728       APInt BitMask = APInt::getZero(MinCaseVal->getBitWidth());
5729       for (auto Case : CaseValues)
5730         BitMask |= (Case->getValue() - MinCaseVal->getValue());
5731 
5732       // Check if cases with the same result can cover all number
5733       // in touched bits.
5734       if (BitMask.countPopulation() == Log2_32(CaseCount)) {
5735         if (!MinCaseVal->isNullValue())
5736           Condition = Builder.CreateSub(Condition, MinCaseVal);
5737         Value *And = Builder.CreateAnd(Condition, ~BitMask, "switch.and");
5738         Value *Cmp = Builder.CreateICmpEQ(
5739             And, Constant::getNullValue(And->getType()), "switch.selectcmp");
5740         return Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
5741       }
5742     }
5743 
5744     // Handle the degenerate case where two cases have the same value.
5745     if (CaseValues.size() == 2) {
5746       Value *Cmp1 = Builder.CreateICmpEQ(Condition, CaseValues[0],
5747                                          "switch.selectcmp.case1");
5748       Value *Cmp2 = Builder.CreateICmpEQ(Condition, CaseValues[1],
5749                                          "switch.selectcmp.case2");
5750       Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp");
5751       return Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
5752     }
5753   }
5754 
5755   return nullptr;
5756 }
5757 
5758 // Helper function to cleanup a switch instruction that has been converted into
5759 // a select, fixing up PHI nodes and basic blocks.
5760 static void removeSwitchAfterSelectFold(SwitchInst *SI, PHINode *PHI,
5761                                         Value *SelectValue,
5762                                         IRBuilder<> &Builder,
5763                                         DomTreeUpdater *DTU) {
5764   std::vector<DominatorTree::UpdateType> Updates;
5765 
5766   BasicBlock *SelectBB = SI->getParent();
5767   BasicBlock *DestBB = PHI->getParent();
5768 
5769   if (DTU && !is_contained(predecessors(DestBB), SelectBB))
5770     Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
5771   Builder.CreateBr(DestBB);
5772 
5773   // Remove the switch.
5774 
5775   while (PHI->getBasicBlockIndex(SelectBB) >= 0)
5776     PHI->removeIncomingValue(SelectBB);
5777   PHI->addIncoming(SelectValue, SelectBB);
5778 
5779   SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
5780   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5781     BasicBlock *Succ = SI->getSuccessor(i);
5782 
5783     if (Succ == DestBB)
5784       continue;
5785     Succ->removePredecessor(SelectBB);
5786     if (DTU && RemovedSuccessors.insert(Succ).second)
5787       Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
5788   }
5789   SI->eraseFromParent();
5790   if (DTU)
5791     DTU->applyUpdates(Updates);
5792 }
5793 
5794 /// If a switch is only used to initialize one or more phi nodes in a common
5795 /// successor block with only two different constant values, try to replace the
5796 /// switch with a select. Returns true if the fold was made.
5797 static bool trySwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
5798                               DomTreeUpdater *DTU, const DataLayout &DL,
5799                               const TargetTransformInfo &TTI) {
5800   Value *const Cond = SI->getCondition();
5801   PHINode *PHI = nullptr;
5802   BasicBlock *CommonDest = nullptr;
5803   Constant *DefaultResult;
5804   SwitchCaseResultVectorTy UniqueResults;
5805   // Collect all the cases that will deliver the same value from the switch.
5806   if (!initializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
5807                              DL, TTI, /*MaxUniqueResults*/ 2))
5808     return false;
5809 
5810   assert(PHI != nullptr && "PHI for value select not found");
5811   Builder.SetInsertPoint(SI);
5812   Value *SelectValue =
5813       foldSwitchToSelect(UniqueResults, DefaultResult, Cond, Builder);
5814   if (!SelectValue)
5815     return false;
5816 
5817   removeSwitchAfterSelectFold(SI, PHI, SelectValue, Builder, DTU);
5818   return true;
5819 }
5820 
5821 namespace {
5822 
5823 /// This class represents a lookup table that can be used to replace a switch.
5824 class SwitchLookupTable {
5825 public:
5826   /// Create a lookup table to use as a switch replacement with the contents
5827   /// of Values, using DefaultValue to fill any holes in the table.
5828   SwitchLookupTable(
5829       Module &M, uint64_t TableSize, ConstantInt *Offset,
5830       const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5831       Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
5832 
5833   /// Build instructions with Builder to retrieve the value at
5834   /// the position given by Index in the lookup table.
5835   Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
5836 
5837   /// Return true if a table with TableSize elements of
5838   /// type ElementType would fit in a target-legal register.
5839   static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
5840                                  Type *ElementType);
5841 
5842 private:
5843   // Depending on the contents of the table, it can be represented in
5844   // different ways.
5845   enum {
5846     // For tables where each element contains the same value, we just have to
5847     // store that single value and return it for each lookup.
5848     SingleValueKind,
5849 
5850     // For tables where there is a linear relationship between table index
5851     // and values. We calculate the result with a simple multiplication
5852     // and addition instead of a table lookup.
5853     LinearMapKind,
5854 
5855     // For small tables with integer elements, we can pack them into a bitmap
5856     // that fits into a target-legal register. Values are retrieved by
5857     // shift and mask operations.
5858     BitMapKind,
5859 
5860     // The table is stored as an array of values. Values are retrieved by load
5861     // instructions from the table.
5862     ArrayKind
5863   } Kind;
5864 
5865   // For SingleValueKind, this is the single value.
5866   Constant *SingleValue = nullptr;
5867 
5868   // For BitMapKind, this is the bitmap.
5869   ConstantInt *BitMap = nullptr;
5870   IntegerType *BitMapElementTy = nullptr;
5871 
5872   // For LinearMapKind, these are the constants used to derive the value.
5873   ConstantInt *LinearOffset = nullptr;
5874   ConstantInt *LinearMultiplier = nullptr;
5875 
5876   // For ArrayKind, this is the array.
5877   GlobalVariable *Array = nullptr;
5878 };
5879 
5880 } // end anonymous namespace
5881 
5882 SwitchLookupTable::SwitchLookupTable(
5883     Module &M, uint64_t TableSize, ConstantInt *Offset,
5884     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5885     Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
5886   assert(Values.size() && "Can't build lookup table without values!");
5887   assert(TableSize >= Values.size() && "Can't fit values in table!");
5888 
5889   // If all values in the table are equal, this is that value.
5890   SingleValue = Values.begin()->second;
5891 
5892   Type *ValueType = Values.begin()->second->getType();
5893 
5894   // Build up the table contents.
5895   SmallVector<Constant *, 64> TableContents(TableSize);
5896   for (size_t I = 0, E = Values.size(); I != E; ++I) {
5897     ConstantInt *CaseVal = Values[I].first;
5898     Constant *CaseRes = Values[I].second;
5899     assert(CaseRes->getType() == ValueType);
5900 
5901     uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
5902     TableContents[Idx] = CaseRes;
5903 
5904     if (CaseRes != SingleValue)
5905       SingleValue = nullptr;
5906   }
5907 
5908   // Fill in any holes in the table with the default result.
5909   if (Values.size() < TableSize) {
5910     assert(DefaultValue &&
5911            "Need a default value to fill the lookup table holes.");
5912     assert(DefaultValue->getType() == ValueType);
5913     for (uint64_t I = 0; I < TableSize; ++I) {
5914       if (!TableContents[I])
5915         TableContents[I] = DefaultValue;
5916     }
5917 
5918     if (DefaultValue != SingleValue)
5919       SingleValue = nullptr;
5920   }
5921 
5922   // If each element in the table contains the same value, we only need to store
5923   // that single value.
5924   if (SingleValue) {
5925     Kind = SingleValueKind;
5926     return;
5927   }
5928 
5929   // Check if we can derive the value with a linear transformation from the
5930   // table index.
5931   if (isa<IntegerType>(ValueType)) {
5932     bool LinearMappingPossible = true;
5933     APInt PrevVal;
5934     APInt DistToPrev;
5935     assert(TableSize >= 2 && "Should be a SingleValue table.");
5936     // Check if there is the same distance between two consecutive values.
5937     for (uint64_t I = 0; I < TableSize; ++I) {
5938       ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
5939       if (!ConstVal) {
5940         // This is an undef. We could deal with it, but undefs in lookup tables
5941         // are very seldom. It's probably not worth the additional complexity.
5942         LinearMappingPossible = false;
5943         break;
5944       }
5945       const APInt &Val = ConstVal->getValue();
5946       if (I != 0) {
5947         APInt Dist = Val - PrevVal;
5948         if (I == 1) {
5949           DistToPrev = Dist;
5950         } else if (Dist != DistToPrev) {
5951           LinearMappingPossible = false;
5952           break;
5953         }
5954       }
5955       PrevVal = Val;
5956     }
5957     if (LinearMappingPossible) {
5958       LinearOffset = cast<ConstantInt>(TableContents[0]);
5959       LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
5960       Kind = LinearMapKind;
5961       ++NumLinearMaps;
5962       return;
5963     }
5964   }
5965 
5966   // If the type is integer and the table fits in a register, build a bitmap.
5967   if (WouldFitInRegister(DL, TableSize, ValueType)) {
5968     IntegerType *IT = cast<IntegerType>(ValueType);
5969     APInt TableInt(TableSize * IT->getBitWidth(), 0);
5970     for (uint64_t I = TableSize; I > 0; --I) {
5971       TableInt <<= IT->getBitWidth();
5972       // Insert values into the bitmap. Undef values are set to zero.
5973       if (!isa<UndefValue>(TableContents[I - 1])) {
5974         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5975         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
5976       }
5977     }
5978     BitMap = ConstantInt::get(M.getContext(), TableInt);
5979     BitMapElementTy = IT;
5980     Kind = BitMapKind;
5981     ++NumBitMaps;
5982     return;
5983   }
5984 
5985   // Store the table in an array.
5986   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
5987   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
5988 
5989   Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true,
5990                              GlobalVariable::PrivateLinkage, Initializer,
5991                              "switch.table." + FuncName);
5992   Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
5993   // Set the alignment to that of an array items. We will be only loading one
5994   // value out of it.
5995   Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType)));
5996   Kind = ArrayKind;
5997 }
5998 
5999 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
6000   switch (Kind) {
6001   case SingleValueKind:
6002     return SingleValue;
6003   case LinearMapKind: {
6004     // Derive the result value from the input value.
6005     Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
6006                                           false, "switch.idx.cast");
6007     if (!LinearMultiplier->isOne())
6008       Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
6009     if (!LinearOffset->isZero())
6010       Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
6011     return Result;
6012   }
6013   case BitMapKind: {
6014     // Type of the bitmap (e.g. i59).
6015     IntegerType *MapTy = BitMap->getType();
6016 
6017     // Cast Index to the same type as the bitmap.
6018     // Note: The Index is <= the number of elements in the table, so
6019     // truncating it to the width of the bitmask is safe.
6020     Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
6021 
6022     // Multiply the shift amount by the element width.
6023     ShiftAmt = Builder.CreateMul(
6024         ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
6025         "switch.shiftamt");
6026 
6027     // Shift down.
6028     Value *DownShifted =
6029         Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
6030     // Mask off.
6031     return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
6032   }
6033   case ArrayKind: {
6034     // Make sure the table index will not overflow when treated as signed.
6035     IntegerType *IT = cast<IntegerType>(Index->getType());
6036     uint64_t TableSize =
6037         Array->getInitializer()->getType()->getArrayNumElements();
6038     if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
6039       Index = Builder.CreateZExt(
6040           Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
6041           "switch.tableidx.zext");
6042 
6043     Value *GEPIndices[] = {Builder.getInt32(0), Index};
6044     Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
6045                                            GEPIndices, "switch.gep");
6046     return Builder.CreateLoad(
6047         cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
6048         "switch.load");
6049   }
6050   }
6051   llvm_unreachable("Unknown lookup table kind!");
6052 }
6053 
6054 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
6055                                            uint64_t TableSize,
6056                                            Type *ElementType) {
6057   auto *IT = dyn_cast<IntegerType>(ElementType);
6058   if (!IT)
6059     return false;
6060   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
6061   // are <= 15, we could try to narrow the type.
6062 
6063   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
6064   if (TableSize >= UINT_MAX / IT->getBitWidth())
6065     return false;
6066   return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
6067 }
6068 
6069 static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI,
6070                                       const DataLayout &DL) {
6071   // Allow any legal type.
6072   if (TTI.isTypeLegal(Ty))
6073     return true;
6074 
6075   auto *IT = dyn_cast<IntegerType>(Ty);
6076   if (!IT)
6077     return false;
6078 
6079   // Also allow power of 2 integer types that have at least 8 bits and fit in
6080   // a register. These types are common in frontend languages and targets
6081   // usually support loads of these types.
6082   // TODO: We could relax this to any integer that fits in a register and rely
6083   // on ABI alignment and padding in the table to allow the load to be widened.
6084   // Or we could widen the constants and truncate the load.
6085   unsigned BitWidth = IT->getBitWidth();
6086   return BitWidth >= 8 && isPowerOf2_32(BitWidth) &&
6087          DL.fitsInLegalInteger(IT->getBitWidth());
6088 }
6089 
6090 /// Determine whether a lookup table should be built for this switch, based on
6091 /// the number of cases, size of the table, and the types of the results.
6092 // TODO: We could support larger than legal types by limiting based on the
6093 // number of loads required and/or table size. If the constants are small we
6094 // could use smaller table entries and extend after the load.
6095 static bool
6096 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
6097                        const TargetTransformInfo &TTI, const DataLayout &DL,
6098                        const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
6099   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
6100     return false; // TableSize overflowed, or mul below might overflow.
6101 
6102   bool AllTablesFitInRegister = true;
6103   bool HasIllegalType = false;
6104   for (const auto &I : ResultTypes) {
6105     Type *Ty = I.second;
6106 
6107     // Saturate this flag to true.
6108     HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL);
6109 
6110     // Saturate this flag to false.
6111     AllTablesFitInRegister =
6112         AllTablesFitInRegister &&
6113         SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
6114 
6115     // If both flags saturate, we're done. NOTE: This *only* works with
6116     // saturating flags, and all flags have to saturate first due to the
6117     // non-deterministic behavior of iterating over a dense map.
6118     if (HasIllegalType && !AllTablesFitInRegister)
6119       break;
6120   }
6121 
6122   // If each table would fit in a register, we should build it anyway.
6123   if (AllTablesFitInRegister)
6124     return true;
6125 
6126   // Don't build a table that doesn't fit in-register if it has illegal types.
6127   if (HasIllegalType)
6128     return false;
6129 
6130   // The table density should be at least 40%. This is the same criterion as for
6131   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
6132   // FIXME: Find the best cut-off.
6133   return SI->getNumCases() * 10 >= TableSize * 4;
6134 }
6135 
6136 /// Try to reuse the switch table index compare. Following pattern:
6137 /// \code
6138 ///     if (idx < tablesize)
6139 ///        r = table[idx]; // table does not contain default_value
6140 ///     else
6141 ///        r = default_value;
6142 ///     if (r != default_value)
6143 ///        ...
6144 /// \endcode
6145 /// Is optimized to:
6146 /// \code
6147 ///     cond = idx < tablesize;
6148 ///     if (cond)
6149 ///        r = table[idx];
6150 ///     else
6151 ///        r = default_value;
6152 ///     if (cond)
6153 ///        ...
6154 /// \endcode
6155 /// Jump threading will then eliminate the second if(cond).
6156 static void reuseTableCompare(
6157     User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
6158     Constant *DefaultValue,
6159     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
6160   ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
6161   if (!CmpInst)
6162     return;
6163 
6164   // We require that the compare is in the same block as the phi so that jump
6165   // threading can do its work afterwards.
6166   if (CmpInst->getParent() != PhiBlock)
6167     return;
6168 
6169   Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
6170   if (!CmpOp1)
6171     return;
6172 
6173   Value *RangeCmp = RangeCheckBranch->getCondition();
6174   Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
6175   Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
6176 
6177   // Check if the compare with the default value is constant true or false.
6178   Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
6179                                                  DefaultValue, CmpOp1, true);
6180   if (DefaultConst != TrueConst && DefaultConst != FalseConst)
6181     return;
6182 
6183   // Check if the compare with the case values is distinct from the default
6184   // compare result.
6185   for (auto ValuePair : Values) {
6186     Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
6187                                                 ValuePair.second, CmpOp1, true);
6188     if (!CaseConst || CaseConst == DefaultConst ||
6189         (CaseConst != TrueConst && CaseConst != FalseConst))
6190       return;
6191   }
6192 
6193   // Check if the branch instruction dominates the phi node. It's a simple
6194   // dominance check, but sufficient for our needs.
6195   // Although this check is invariant in the calling loops, it's better to do it
6196   // at this late stage. Practically we do it at most once for a switch.
6197   BasicBlock *BranchBlock = RangeCheckBranch->getParent();
6198   for (BasicBlock *Pred : predecessors(PhiBlock)) {
6199     if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
6200       return;
6201   }
6202 
6203   if (DefaultConst == FalseConst) {
6204     // The compare yields the same result. We can replace it.
6205     CmpInst->replaceAllUsesWith(RangeCmp);
6206     ++NumTableCmpReuses;
6207   } else {
6208     // The compare yields the same result, just inverted. We can replace it.
6209     Value *InvertedTableCmp = BinaryOperator::CreateXor(
6210         RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
6211         RangeCheckBranch);
6212     CmpInst->replaceAllUsesWith(InvertedTableCmp);
6213     ++NumTableCmpReuses;
6214   }
6215 }
6216 
6217 /// If the switch is only used to initialize one or more phi nodes in a common
6218 /// successor block with different constant values, replace the switch with
6219 /// lookup tables.
6220 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
6221                                 DomTreeUpdater *DTU, const DataLayout &DL,
6222                                 const TargetTransformInfo &TTI) {
6223   assert(SI->getNumCases() > 1 && "Degenerate switch?");
6224 
6225   BasicBlock *BB = SI->getParent();
6226   Function *Fn = BB->getParent();
6227   // Only build lookup table when we have a target that supports it or the
6228   // attribute is not set.
6229   if (!TTI.shouldBuildLookupTables() ||
6230       (Fn->getFnAttribute("no-jump-tables").getValueAsBool()))
6231     return false;
6232 
6233   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
6234   // split off a dense part and build a lookup table for that.
6235 
6236   // FIXME: This creates arrays of GEPs to constant strings, which means each
6237   // GEP needs a runtime relocation in PIC code. We should just build one big
6238   // string and lookup indices into that.
6239 
6240   // Ignore switches with less than three cases. Lookup tables will not make
6241   // them faster, so we don't analyze them.
6242   if (SI->getNumCases() < 3)
6243     return false;
6244 
6245   // Figure out the corresponding result for each case value and phi node in the
6246   // common destination, as well as the min and max case values.
6247   assert(!SI->cases().empty());
6248   SwitchInst::CaseIt CI = SI->case_begin();
6249   ConstantInt *MinCaseVal = CI->getCaseValue();
6250   ConstantInt *MaxCaseVal = CI->getCaseValue();
6251 
6252   BasicBlock *CommonDest = nullptr;
6253 
6254   using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
6255   SmallDenseMap<PHINode *, ResultListTy> ResultLists;
6256 
6257   SmallDenseMap<PHINode *, Constant *> DefaultResults;
6258   SmallDenseMap<PHINode *, Type *> ResultTypes;
6259   SmallVector<PHINode *, 4> PHIs;
6260 
6261   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
6262     ConstantInt *CaseVal = CI->getCaseValue();
6263     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
6264       MinCaseVal = CaseVal;
6265     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
6266       MaxCaseVal = CaseVal;
6267 
6268     // Resulting value at phi nodes for this case value.
6269     using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
6270     ResultsTy Results;
6271     if (!getCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
6272                         Results, DL, TTI))
6273       return false;
6274 
6275     // Append the result from this case to the list for each phi.
6276     for (const auto &I : Results) {
6277       PHINode *PHI = I.first;
6278       Constant *Value = I.second;
6279       if (!ResultLists.count(PHI))
6280         PHIs.push_back(PHI);
6281       ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
6282     }
6283   }
6284 
6285   // Keep track of the result types.
6286   for (PHINode *PHI : PHIs) {
6287     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
6288   }
6289 
6290   uint64_t NumResults = ResultLists[PHIs[0]].size();
6291   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
6292   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
6293   bool TableHasHoles = (NumResults < TableSize);
6294 
6295   // If the table has holes, we need a constant result for the default case
6296   // or a bitmask that fits in a register.
6297   SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
6298   bool HasDefaultResults =
6299       getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
6300                      DefaultResultsList, DL, TTI);
6301 
6302   bool NeedMask = (TableHasHoles && !HasDefaultResults);
6303   if (NeedMask) {
6304     // As an extra penalty for the validity test we require more cases.
6305     if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
6306       return false;
6307     if (!DL.fitsInLegalInteger(TableSize))
6308       return false;
6309   }
6310 
6311   for (const auto &I : DefaultResultsList) {
6312     PHINode *PHI = I.first;
6313     Constant *Result = I.second;
6314     DefaultResults[PHI] = Result;
6315   }
6316 
6317   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
6318     return false;
6319 
6320   std::vector<DominatorTree::UpdateType> Updates;
6321 
6322   // Create the BB that does the lookups.
6323   Module &Mod = *CommonDest->getParent()->getParent();
6324   BasicBlock *LookupBB = BasicBlock::Create(
6325       Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
6326 
6327   // Compute the table index value.
6328   Builder.SetInsertPoint(SI);
6329   Value *TableIndex;
6330   if (MinCaseVal->isNullValue())
6331     TableIndex = SI->getCondition();
6332   else
6333     TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
6334                                    "switch.tableidx");
6335 
6336   // Compute the maximum table size representable by the integer type we are
6337   // switching upon.
6338   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
6339   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
6340   assert(MaxTableSize >= TableSize &&
6341          "It is impossible for a switch to have more entries than the max "
6342          "representable value of its input integer type's size.");
6343 
6344   // If the default destination is unreachable, or if the lookup table covers
6345   // all values of the conditional variable, branch directly to the lookup table
6346   // BB. Otherwise, check that the condition is within the case range.
6347   const bool DefaultIsReachable =
6348       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
6349   const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
6350   BranchInst *RangeCheckBranch = nullptr;
6351 
6352   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
6353     Builder.CreateBr(LookupBB);
6354     if (DTU)
6355       Updates.push_back({DominatorTree::Insert, BB, LookupBB});
6356     // Note: We call removeProdecessor later since we need to be able to get the
6357     // PHI value for the default case in case we're using a bit mask.
6358   } else {
6359     Value *Cmp = Builder.CreateICmpULT(
6360         TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
6361     RangeCheckBranch =
6362         Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
6363     if (DTU)
6364       Updates.push_back({DominatorTree::Insert, BB, LookupBB});
6365   }
6366 
6367   // Populate the BB that does the lookups.
6368   Builder.SetInsertPoint(LookupBB);
6369 
6370   if (NeedMask) {
6371     // Before doing the lookup, we do the hole check. The LookupBB is therefore
6372     // re-purposed to do the hole check, and we create a new LookupBB.
6373     BasicBlock *MaskBB = LookupBB;
6374     MaskBB->setName("switch.hole_check");
6375     LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
6376                                   CommonDest->getParent(), CommonDest);
6377 
6378     // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
6379     // unnecessary illegal types.
6380     uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
6381     APInt MaskInt(TableSizePowOf2, 0);
6382     APInt One(TableSizePowOf2, 1);
6383     // Build bitmask; fill in a 1 bit for every case.
6384     const ResultListTy &ResultList = ResultLists[PHIs[0]];
6385     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
6386       uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
6387                          .getLimitedValue();
6388       MaskInt |= One << Idx;
6389     }
6390     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
6391 
6392     // Get the TableIndex'th bit of the bitmask.
6393     // If this bit is 0 (meaning hole) jump to the default destination,
6394     // else continue with table lookup.
6395     IntegerType *MapTy = TableMask->getType();
6396     Value *MaskIndex =
6397         Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
6398     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
6399     Value *LoBit = Builder.CreateTrunc(
6400         Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
6401     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
6402     if (DTU) {
6403       Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
6404       Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
6405     }
6406     Builder.SetInsertPoint(LookupBB);
6407     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
6408   }
6409 
6410   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
6411     // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
6412     // do not delete PHINodes here.
6413     SI->getDefaultDest()->removePredecessor(BB,
6414                                             /*KeepOneInputPHIs=*/true);
6415     if (DTU)
6416       Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
6417   }
6418 
6419   for (PHINode *PHI : PHIs) {
6420     const ResultListTy &ResultList = ResultLists[PHI];
6421 
6422     // If using a bitmask, use any value to fill the lookup table holes.
6423     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
6424     StringRef FuncName = Fn->getName();
6425     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
6426                             FuncName);
6427 
6428     Value *Result = Table.BuildLookup(TableIndex, Builder);
6429 
6430     // Do a small peephole optimization: re-use the switch table compare if
6431     // possible.
6432     if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
6433       BasicBlock *PhiBlock = PHI->getParent();
6434       // Search for compare instructions which use the phi.
6435       for (auto *User : PHI->users()) {
6436         reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
6437       }
6438     }
6439 
6440     PHI->addIncoming(Result, LookupBB);
6441   }
6442 
6443   Builder.CreateBr(CommonDest);
6444   if (DTU)
6445     Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
6446 
6447   // Remove the switch.
6448   SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
6449   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
6450     BasicBlock *Succ = SI->getSuccessor(i);
6451 
6452     if (Succ == SI->getDefaultDest())
6453       continue;
6454     Succ->removePredecessor(BB);
6455     if (DTU && RemovedSuccessors.insert(Succ).second)
6456       Updates.push_back({DominatorTree::Delete, BB, Succ});
6457   }
6458   SI->eraseFromParent();
6459 
6460   if (DTU)
6461     DTU->applyUpdates(Updates);
6462 
6463   ++NumLookupTables;
6464   if (NeedMask)
6465     ++NumLookupTablesHoles;
6466   return true;
6467 }
6468 
6469 static bool isSwitchDense(ArrayRef<int64_t> Values) {
6470   // See also SelectionDAGBuilder::isDense(), which this function was based on.
6471   uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
6472   uint64_t Range = Diff + 1;
6473   uint64_t NumCases = Values.size();
6474   // 40% is the default density for building a jump table in optsize/minsize mode.
6475   uint64_t MinDensity = 40;
6476 
6477   return NumCases * 100 >= Range * MinDensity;
6478 }
6479 
6480 /// Try to transform a switch that has "holes" in it to a contiguous sequence
6481 /// of cases.
6482 ///
6483 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
6484 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
6485 ///
6486 /// This converts a sparse switch into a dense switch which allows better
6487 /// lowering and could also allow transforming into a lookup table.
6488 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
6489                               const DataLayout &DL,
6490                               const TargetTransformInfo &TTI) {
6491   auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
6492   if (CondTy->getIntegerBitWidth() > 64 ||
6493       !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
6494     return false;
6495   // Only bother with this optimization if there are more than 3 switch cases;
6496   // SDAG will only bother creating jump tables for 4 or more cases.
6497   if (SI->getNumCases() < 4)
6498     return false;
6499 
6500   // This transform is agnostic to the signedness of the input or case values. We
6501   // can treat the case values as signed or unsigned. We can optimize more common
6502   // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
6503   // as signed.
6504   SmallVector<int64_t,4> Values;
6505   for (auto &C : SI->cases())
6506     Values.push_back(C.getCaseValue()->getValue().getSExtValue());
6507   llvm::sort(Values);
6508 
6509   // If the switch is already dense, there's nothing useful to do here.
6510   if (isSwitchDense(Values))
6511     return false;
6512 
6513   // First, transform the values such that they start at zero and ascend.
6514   int64_t Base = Values[0];
6515   for (auto &V : Values)
6516     V -= (uint64_t)(Base);
6517 
6518   // Now we have signed numbers that have been shifted so that, given enough
6519   // precision, there are no negative values. Since the rest of the transform
6520   // is bitwise only, we switch now to an unsigned representation.
6521 
6522   // This transform can be done speculatively because it is so cheap - it
6523   // results in a single rotate operation being inserted.
6524   // FIXME: It's possible that optimizing a switch on powers of two might also
6525   // be beneficial - flag values are often powers of two and we could use a CLZ
6526   // as the key function.
6527 
6528   // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than
6529   // one element and LLVM disallows duplicate cases, Shift is guaranteed to be
6530   // less than 64.
6531   unsigned Shift = 64;
6532   for (auto &V : Values)
6533     Shift = std::min(Shift, countTrailingZeros((uint64_t)V));
6534   assert(Shift < 64);
6535   if (Shift > 0)
6536     for (auto &V : Values)
6537       V = (int64_t)((uint64_t)V >> Shift);
6538 
6539   if (!isSwitchDense(Values))
6540     // Transform didn't create a dense switch.
6541     return false;
6542 
6543   // The obvious transform is to shift the switch condition right and emit a
6544   // check that the condition actually cleanly divided by GCD, i.e.
6545   //   C & (1 << Shift - 1) == 0
6546   // inserting a new CFG edge to handle the case where it didn't divide cleanly.
6547   //
6548   // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
6549   // shift and puts the shifted-off bits in the uppermost bits. If any of these
6550   // are nonzero then the switch condition will be very large and will hit the
6551   // default case.
6552 
6553   auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
6554   Builder.SetInsertPoint(SI);
6555   auto *ShiftC = ConstantInt::get(Ty, Shift);
6556   auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
6557   auto *LShr = Builder.CreateLShr(Sub, ShiftC);
6558   auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
6559   auto *Rot = Builder.CreateOr(LShr, Shl);
6560   SI->replaceUsesOfWith(SI->getCondition(), Rot);
6561 
6562   for (auto Case : SI->cases()) {
6563     auto *Orig = Case.getCaseValue();
6564     auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
6565     Case.setValue(
6566         cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
6567   }
6568   return true;
6569 }
6570 
6571 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
6572   BasicBlock *BB = SI->getParent();
6573 
6574   if (isValueEqualityComparison(SI)) {
6575     // If we only have one predecessor, and if it is a branch on this value,
6576     // see if that predecessor totally determines the outcome of this switch.
6577     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6578       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
6579         return requestResimplify();
6580 
6581     Value *Cond = SI->getCondition();
6582     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
6583       if (SimplifySwitchOnSelect(SI, Select))
6584         return requestResimplify();
6585 
6586     // If the block only contains the switch, see if we can fold the block
6587     // away into any preds.
6588     if (SI == &*BB->instructionsWithoutDebug(false).begin())
6589       if (FoldValueComparisonIntoPredecessors(SI, Builder))
6590         return requestResimplify();
6591   }
6592 
6593   // Try to transform the switch into an icmp and a branch.
6594   // The conversion from switch to comparison may lose information on
6595   // impossible switch values, so disable it early in the pipeline.
6596   if (Options.ConvertSwitchRangeToICmp && TurnSwitchRangeIntoICmp(SI, Builder))
6597     return requestResimplify();
6598 
6599   // Remove unreachable cases.
6600   if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
6601     return requestResimplify();
6602 
6603   if (trySwitchToSelect(SI, Builder, DTU, DL, TTI))
6604     return requestResimplify();
6605 
6606   if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
6607     return requestResimplify();
6608 
6609   // The conversion from switch to lookup tables results in difficult-to-analyze
6610   // code and makes pruning branches much harder. This is a problem if the
6611   // switch expression itself can still be restricted as a result of inlining or
6612   // CVP. Therefore, only apply this transformation during late stages of the
6613   // optimisation pipeline.
6614   if (Options.ConvertSwitchToLookupTable &&
6615       SwitchToLookupTable(SI, Builder, DTU, DL, TTI))
6616     return requestResimplify();
6617 
6618   if (ReduceSwitchRange(SI, Builder, DL, TTI))
6619     return requestResimplify();
6620 
6621   return false;
6622 }
6623 
6624 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
6625   BasicBlock *BB = IBI->getParent();
6626   bool Changed = false;
6627 
6628   // Eliminate redundant destinations.
6629   SmallPtrSet<Value *, 8> Succs;
6630   SmallSetVector<BasicBlock *, 8> RemovedSuccs;
6631   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
6632     BasicBlock *Dest = IBI->getDestination(i);
6633     if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
6634       if (!Dest->hasAddressTaken())
6635         RemovedSuccs.insert(Dest);
6636       Dest->removePredecessor(BB);
6637       IBI->removeDestination(i);
6638       --i;
6639       --e;
6640       Changed = true;
6641     }
6642   }
6643 
6644   if (DTU) {
6645     std::vector<DominatorTree::UpdateType> Updates;
6646     Updates.reserve(RemovedSuccs.size());
6647     for (auto *RemovedSucc : RemovedSuccs)
6648       Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
6649     DTU->applyUpdates(Updates);
6650   }
6651 
6652   if (IBI->getNumDestinations() == 0) {
6653     // If the indirectbr has no successors, change it to unreachable.
6654     new UnreachableInst(IBI->getContext(), IBI);
6655     EraseTerminatorAndDCECond(IBI);
6656     return true;
6657   }
6658 
6659   if (IBI->getNumDestinations() == 1) {
6660     // If the indirectbr has one successor, change it to a direct branch.
6661     BranchInst::Create(IBI->getDestination(0), IBI);
6662     EraseTerminatorAndDCECond(IBI);
6663     return true;
6664   }
6665 
6666   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
6667     if (SimplifyIndirectBrOnSelect(IBI, SI))
6668       return requestResimplify();
6669   }
6670   return Changed;
6671 }
6672 
6673 /// Given an block with only a single landing pad and a unconditional branch
6674 /// try to find another basic block which this one can be merged with.  This
6675 /// handles cases where we have multiple invokes with unique landing pads, but
6676 /// a shared handler.
6677 ///
6678 /// We specifically choose to not worry about merging non-empty blocks
6679 /// here.  That is a PRE/scheduling problem and is best solved elsewhere.  In
6680 /// practice, the optimizer produces empty landing pad blocks quite frequently
6681 /// when dealing with exception dense code.  (see: instcombine, gvn, if-else
6682 /// sinking in this file)
6683 ///
6684 /// This is primarily a code size optimization.  We need to avoid performing
6685 /// any transform which might inhibit optimization (such as our ability to
6686 /// specialize a particular handler via tail commoning).  We do this by not
6687 /// merging any blocks which require us to introduce a phi.  Since the same
6688 /// values are flowing through both blocks, we don't lose any ability to
6689 /// specialize.  If anything, we make such specialization more likely.
6690 ///
6691 /// TODO - This transformation could remove entries from a phi in the target
6692 /// block when the inputs in the phi are the same for the two blocks being
6693 /// merged.  In some cases, this could result in removal of the PHI entirely.
6694 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
6695                                  BasicBlock *BB, DomTreeUpdater *DTU) {
6696   auto Succ = BB->getUniqueSuccessor();
6697   assert(Succ);
6698   // If there's a phi in the successor block, we'd likely have to introduce
6699   // a phi into the merged landing pad block.
6700   if (isa<PHINode>(*Succ->begin()))
6701     return false;
6702 
6703   for (BasicBlock *OtherPred : predecessors(Succ)) {
6704     if (BB == OtherPred)
6705       continue;
6706     BasicBlock::iterator I = OtherPred->begin();
6707     LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
6708     if (!LPad2 || !LPad2->isIdenticalTo(LPad))
6709       continue;
6710     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6711       ;
6712     BranchInst *BI2 = dyn_cast<BranchInst>(I);
6713     if (!BI2 || !BI2->isIdenticalTo(BI))
6714       continue;
6715 
6716     std::vector<DominatorTree::UpdateType> Updates;
6717 
6718     // We've found an identical block.  Update our predecessors to take that
6719     // path instead and make ourselves dead.
6720     SmallSetVector<BasicBlock *, 16> UniquePreds(pred_begin(BB), pred_end(BB));
6721     for (BasicBlock *Pred : UniquePreds) {
6722       InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
6723       assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
6724              "unexpected successor");
6725       II->setUnwindDest(OtherPred);
6726       if (DTU) {
6727         Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
6728         Updates.push_back({DominatorTree::Delete, Pred, BB});
6729       }
6730     }
6731 
6732     // The debug info in OtherPred doesn't cover the merged control flow that
6733     // used to go through BB.  We need to delete it or update it.
6734     for (Instruction &Inst : llvm::make_early_inc_range(*OtherPred))
6735       if (isa<DbgInfoIntrinsic>(Inst))
6736         Inst.eraseFromParent();
6737 
6738     SmallSetVector<BasicBlock *, 16> UniqueSuccs(succ_begin(BB), succ_end(BB));
6739     for (BasicBlock *Succ : UniqueSuccs) {
6740       Succ->removePredecessor(BB);
6741       if (DTU)
6742         Updates.push_back({DominatorTree::Delete, BB, Succ});
6743     }
6744 
6745     IRBuilder<> Builder(BI);
6746     Builder.CreateUnreachable();
6747     BI->eraseFromParent();
6748     if (DTU)
6749       DTU->applyUpdates(Updates);
6750     return true;
6751   }
6752   return false;
6753 }
6754 
6755 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) {
6756   return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder)
6757                                    : simplifyCondBranch(Branch, Builder);
6758 }
6759 
6760 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI,
6761                                           IRBuilder<> &Builder) {
6762   BasicBlock *BB = BI->getParent();
6763   BasicBlock *Succ = BI->getSuccessor(0);
6764 
6765   // If the Terminator is the only non-phi instruction, simplify the block.
6766   // If LoopHeader is provided, check if the block or its successor is a loop
6767   // header. (This is for early invocations before loop simplify and
6768   // vectorization to keep canonical loop forms for nested loops. These blocks
6769   // can be eliminated when the pass is invoked later in the back-end.)
6770   // Note that if BB has only one predecessor then we do not introduce new
6771   // backedge, so we can eliminate BB.
6772   bool NeedCanonicalLoop =
6773       Options.NeedCanonicalLoop &&
6774       (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
6775        (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
6776   BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(true)->getIterator();
6777   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
6778       !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
6779     return true;
6780 
6781   // If the only instruction in the block is a seteq/setne comparison against a
6782   // constant, try to simplify the block.
6783   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
6784     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
6785       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6786         ;
6787       if (I->isTerminator() &&
6788           tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
6789         return true;
6790     }
6791 
6792   // See if we can merge an empty landing pad block with another which is
6793   // equivalent.
6794   if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
6795     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6796       ;
6797     if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB, DTU))
6798       return true;
6799   }
6800 
6801   // If this basic block is ONLY a compare and a branch, and if a predecessor
6802   // branches to us and our successor, fold the comparison into the
6803   // predecessor and use logical operations to update the incoming value
6804   // for PHI nodes in common successor.
6805   if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI,
6806                              Options.BonusInstThreshold))
6807     return requestResimplify();
6808   return false;
6809 }
6810 
6811 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
6812   BasicBlock *PredPred = nullptr;
6813   for (auto *P : predecessors(BB)) {
6814     BasicBlock *PPred = P->getSinglePredecessor();
6815     if (!PPred || (PredPred && PredPred != PPred))
6816       return nullptr;
6817     PredPred = PPred;
6818   }
6819   return PredPred;
6820 }
6821 
6822 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
6823   assert(
6824       !isa<ConstantInt>(BI->getCondition()) &&
6825       BI->getSuccessor(0) != BI->getSuccessor(1) &&
6826       "Tautological conditional branch should have been eliminated already.");
6827 
6828   BasicBlock *BB = BI->getParent();
6829   if (!Options.SimplifyCondBranch)
6830     return false;
6831 
6832   // Conditional branch
6833   if (isValueEqualityComparison(BI)) {
6834     // If we only have one predecessor, and if it is a branch on this value,
6835     // see if that predecessor totally determines the outcome of this
6836     // switch.
6837     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6838       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
6839         return requestResimplify();
6840 
6841     // This block must be empty, except for the setcond inst, if it exists.
6842     // Ignore dbg and pseudo intrinsics.
6843     auto I = BB->instructionsWithoutDebug(true).begin();
6844     if (&*I == BI) {
6845       if (FoldValueComparisonIntoPredecessors(BI, Builder))
6846         return requestResimplify();
6847     } else if (&*I == cast<Instruction>(BI->getCondition())) {
6848       ++I;
6849       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
6850         return requestResimplify();
6851     }
6852   }
6853 
6854   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
6855   if (SimplifyBranchOnICmpChain(BI, Builder, DL))
6856     return true;
6857 
6858   // If this basic block has dominating predecessor blocks and the dominating
6859   // blocks' conditions imply BI's condition, we know the direction of BI.
6860   Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
6861   if (Imp) {
6862     // Turn this into a branch on constant.
6863     auto *OldCond = BI->getCondition();
6864     ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
6865                              : ConstantInt::getFalse(BB->getContext());
6866     BI->setCondition(TorF);
6867     RecursivelyDeleteTriviallyDeadInstructions(OldCond);
6868     return requestResimplify();
6869   }
6870 
6871   // If this basic block is ONLY a compare and a branch, and if a predecessor
6872   // branches to us and one of our successors, fold the comparison into the
6873   // predecessor and use logical operations to pick the right destination.
6874   if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI,
6875                              Options.BonusInstThreshold))
6876     return requestResimplify();
6877 
6878   // We have a conditional branch to two blocks that are only reachable
6879   // from BI.  We know that the condbr dominates the two blocks, so see if
6880   // there is any identical code in the "then" and "else" blocks.  If so, we
6881   // can hoist it up to the branching block.
6882   if (BI->getSuccessor(0)->getSinglePredecessor()) {
6883     if (BI->getSuccessor(1)->getSinglePredecessor()) {
6884       if (HoistCommon &&
6885           HoistThenElseCodeToIf(BI, TTI, !Options.HoistCommonInsts))
6886         return requestResimplify();
6887     } else {
6888       // If Successor #1 has multiple preds, we may be able to conditionally
6889       // execute Successor #0 if it branches to Successor #1.
6890       Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
6891       if (Succ0TI->getNumSuccessors() == 1 &&
6892           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
6893         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
6894           return requestResimplify();
6895     }
6896   } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
6897     // If Successor #0 has multiple preds, we may be able to conditionally
6898     // execute Successor #1 if it branches to Successor #0.
6899     Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
6900     if (Succ1TI->getNumSuccessors() == 1 &&
6901         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
6902       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
6903         return requestResimplify();
6904   }
6905 
6906   // If this is a branch on something for which we know the constant value in
6907   // predecessors (e.g. a phi node in the current block), thread control
6908   // through this block.
6909   if (FoldCondBranchOnValueKnownInPredecessor(BI, DTU, DL, Options.AC))
6910     return requestResimplify();
6911 
6912   // Scan predecessor blocks for conditional branches.
6913   for (BasicBlock *Pred : predecessors(BB))
6914     if (BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator()))
6915       if (PBI != BI && PBI->isConditional())
6916         if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
6917           return requestResimplify();
6918 
6919   // Look for diamond patterns.
6920   if (MergeCondStores)
6921     if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
6922       if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
6923         if (PBI != BI && PBI->isConditional())
6924           if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
6925             return requestResimplify();
6926 
6927   return false;
6928 }
6929 
6930 /// Check if passing a value to an instruction will cause undefined behavior.
6931 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
6932   Constant *C = dyn_cast<Constant>(V);
6933   if (!C)
6934     return false;
6935 
6936   if (I->use_empty())
6937     return false;
6938 
6939   if (C->isNullValue() || isa<UndefValue>(C)) {
6940     // Only look at the first use, avoid hurting compile time with long uselists
6941     auto *Use = cast<Instruction>(*I->user_begin());
6942     // Bail out if Use is not in the same BB as I or Use == I or Use comes
6943     // before I in the block. The latter two can be the case if Use is a PHI
6944     // node.
6945     if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I))
6946       return false;
6947 
6948     // Now make sure that there are no instructions in between that can alter
6949     // control flow (eg. calls)
6950     auto InstrRange =
6951         make_range(std::next(I->getIterator()), Use->getIterator());
6952     if (any_of(InstrRange, [](Instruction &I) {
6953           return !isGuaranteedToTransferExecutionToSuccessor(&I);
6954         }))
6955       return false;
6956 
6957     // Look through GEPs. A load from a GEP derived from NULL is still undefined
6958     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
6959       if (GEP->getPointerOperand() == I) {
6960         if (!GEP->isInBounds() || !GEP->hasAllZeroIndices())
6961           PtrValueMayBeModified = true;
6962         return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
6963       }
6964 
6965     // Look through bitcasts.
6966     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
6967       return passingValueIsAlwaysUndefined(V, BC, PtrValueMayBeModified);
6968 
6969     // Load from null is undefined.
6970     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
6971       if (!LI->isVolatile())
6972         return !NullPointerIsDefined(LI->getFunction(),
6973                                      LI->getPointerAddressSpace());
6974 
6975     // Store to null is undefined.
6976     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
6977       if (!SI->isVolatile())
6978         return (!NullPointerIsDefined(SI->getFunction(),
6979                                       SI->getPointerAddressSpace())) &&
6980                SI->getPointerOperand() == I;
6981 
6982     if (auto *CB = dyn_cast<CallBase>(Use)) {
6983       if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
6984         return false;
6985       // A call to null is undefined.
6986       if (CB->getCalledOperand() == I)
6987         return true;
6988 
6989       if (C->isNullValue()) {
6990         for (const llvm::Use &Arg : CB->args())
6991           if (Arg == I) {
6992             unsigned ArgIdx = CB->getArgOperandNo(&Arg);
6993             if (CB->isPassingUndefUB(ArgIdx) &&
6994                 CB->paramHasAttr(ArgIdx, Attribute::NonNull)) {
6995               // Passing null to a nonnnull+noundef argument is undefined.
6996               return !PtrValueMayBeModified;
6997             }
6998           }
6999       } else if (isa<UndefValue>(C)) {
7000         // Passing undef to a noundef argument is undefined.
7001         for (const llvm::Use &Arg : CB->args())
7002           if (Arg == I) {
7003             unsigned ArgIdx = CB->getArgOperandNo(&Arg);
7004             if (CB->isPassingUndefUB(ArgIdx)) {
7005               // Passing undef to a noundef argument is undefined.
7006               return true;
7007             }
7008           }
7009       }
7010     }
7011   }
7012   return false;
7013 }
7014 
7015 /// If BB has an incoming value that will always trigger undefined behavior
7016 /// (eg. null pointer dereference), remove the branch leading here.
7017 static bool removeUndefIntroducingPredecessor(BasicBlock *BB,
7018                                               DomTreeUpdater *DTU) {
7019   for (PHINode &PHI : BB->phis())
7020     for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
7021       if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
7022         BasicBlock *Predecessor = PHI.getIncomingBlock(i);
7023         Instruction *T = Predecessor->getTerminator();
7024         IRBuilder<> Builder(T);
7025         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
7026           BB->removePredecessor(Predecessor);
7027           // Turn uncoditional branches into unreachables and remove the dead
7028           // destination from conditional branches.
7029           if (BI->isUnconditional())
7030             Builder.CreateUnreachable();
7031           else {
7032             // Preserve guarding condition in assume, because it might not be
7033             // inferrable from any dominating condition.
7034             Value *Cond = BI->getCondition();
7035             if (BI->getSuccessor(0) == BB)
7036               Builder.CreateAssumption(Builder.CreateNot(Cond));
7037             else
7038               Builder.CreateAssumption(Cond);
7039             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
7040                                                        : BI->getSuccessor(0));
7041           }
7042           BI->eraseFromParent();
7043           if (DTU)
7044             DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
7045           return true;
7046         } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
7047           // Redirect all branches leading to UB into
7048           // a newly created unreachable block.
7049           BasicBlock *Unreachable = BasicBlock::Create(
7050               Predecessor->getContext(), "unreachable", BB->getParent(), BB);
7051           Builder.SetInsertPoint(Unreachable);
7052           // The new block contains only one instruction: Unreachable
7053           Builder.CreateUnreachable();
7054           for (auto &Case : SI->cases())
7055             if (Case.getCaseSuccessor() == BB) {
7056               BB->removePredecessor(Predecessor);
7057               Case.setSuccessor(Unreachable);
7058             }
7059           if (SI->getDefaultDest() == BB) {
7060             BB->removePredecessor(Predecessor);
7061             SI->setDefaultDest(Unreachable);
7062           }
7063 
7064           if (DTU)
7065             DTU->applyUpdates(
7066                 { { DominatorTree::Insert, Predecessor, Unreachable },
7067                   { DominatorTree::Delete, Predecessor, BB } });
7068           return true;
7069         }
7070       }
7071 
7072   return false;
7073 }
7074 
7075 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
7076   bool Changed = false;
7077 
7078   assert(BB && BB->getParent() && "Block not embedded in function!");
7079   assert(BB->getTerminator() && "Degenerate basic block encountered!");
7080 
7081   // Remove basic blocks that have no predecessors (except the entry block)...
7082   // or that just have themself as a predecessor.  These are unreachable.
7083   if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
7084       BB->getSinglePredecessor() == BB) {
7085     LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
7086     DeleteDeadBlock(BB, DTU);
7087     return true;
7088   }
7089 
7090   // Check to see if we can constant propagate this terminator instruction
7091   // away...
7092   Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
7093                                     /*TLI=*/nullptr, DTU);
7094 
7095   // Check for and eliminate duplicate PHI nodes in this block.
7096   Changed |= EliminateDuplicatePHINodes(BB);
7097 
7098   // Check for and remove branches that will always cause undefined behavior.
7099   if (removeUndefIntroducingPredecessor(BB, DTU))
7100     return requestResimplify();
7101 
7102   // Merge basic blocks into their predecessor if there is only one distinct
7103   // pred, and if there is only one distinct successor of the predecessor, and
7104   // if there are no PHI nodes.
7105   if (MergeBlockIntoPredecessor(BB, DTU))
7106     return true;
7107 
7108   if (SinkCommon && Options.SinkCommonInsts)
7109     if (SinkCommonCodeFromPredecessors(BB, DTU) ||
7110         MergeCompatibleInvokes(BB, DTU)) {
7111       // SinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
7112       // so we may now how duplicate PHI's.
7113       // Let's rerun EliminateDuplicatePHINodes() first,
7114       // before FoldTwoEntryPHINode() potentially converts them into select's,
7115       // after which we'd need a whole EarlyCSE pass run to cleanup them.
7116       return true;
7117     }
7118 
7119   IRBuilder<> Builder(BB);
7120 
7121   if (Options.FoldTwoEntryPHINode) {
7122     // If there is a trivial two-entry PHI node in this basic block, and we can
7123     // eliminate it, do so now.
7124     if (auto *PN = dyn_cast<PHINode>(BB->begin()))
7125       if (PN->getNumIncomingValues() == 2)
7126         if (FoldTwoEntryPHINode(PN, TTI, DTU, DL))
7127           return true;
7128   }
7129 
7130   Instruction *Terminator = BB->getTerminator();
7131   Builder.SetInsertPoint(Terminator);
7132   switch (Terminator->getOpcode()) {
7133   case Instruction::Br:
7134     Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder);
7135     break;
7136   case Instruction::Resume:
7137     Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
7138     break;
7139   case Instruction::CleanupRet:
7140     Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
7141     break;
7142   case Instruction::Switch:
7143     Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
7144     break;
7145   case Instruction::Unreachable:
7146     Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
7147     break;
7148   case Instruction::IndirectBr:
7149     Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
7150     break;
7151   }
7152 
7153   return Changed;
7154 }
7155 
7156 bool SimplifyCFGOpt::run(BasicBlock *BB) {
7157   bool Changed = false;
7158 
7159   // Repeated simplify BB as long as resimplification is requested.
7160   do {
7161     Resimplify = false;
7162 
7163     // Perform one round of simplifcation. Resimplify flag will be set if
7164     // another iteration is requested.
7165     Changed |= simplifyOnce(BB);
7166   } while (Resimplify);
7167 
7168   return Changed;
7169 }
7170 
7171 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
7172                        DomTreeUpdater *DTU, const SimplifyCFGOptions &Options,
7173                        ArrayRef<WeakVH> LoopHeaders) {
7174   return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), LoopHeaders,
7175                         Options)
7176       .run(BB);
7177 }
7178