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