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