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