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