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