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