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