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