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