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