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