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