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 // Simplify resume that is only used by a single (non-phi) landing pad.
3966 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
3967   BasicBlock *BB = RI->getParent();
3968   auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
3969   assert(RI->getValue() == LPInst &&
3970          "Resume must unwind the exception that caused control to here");
3971 
3972   // Check that there are no other instructions except for debug intrinsics.
3973   BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
3974   while (++I != E)
3975     if (!isa<DbgInfoIntrinsic>(I))
3976       return false;
3977 
3978   // Turn all invokes that unwind here into calls and delete the basic block.
3979   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3980     BasicBlock *Pred = *PI++;
3981     removeUnwindEdge(Pred);
3982   }
3983 
3984   // The landingpad is now unreachable.  Zap it.
3985   if (LoopHeaders)
3986     LoopHeaders->erase(BB);
3987   BB->eraseFromParent();
3988   return true;
3989 }
3990 
3991 static bool removeEmptyCleanup(CleanupReturnInst *RI) {
3992   // If this is a trivial cleanup pad that executes no instructions, it can be
3993   // eliminated.  If the cleanup pad continues to the caller, any predecessor
3994   // that is an EH pad will be updated to continue to the caller and any
3995   // predecessor that terminates with an invoke instruction will have its invoke
3996   // instruction converted to a call instruction.  If the cleanup pad being
3997   // simplified does not continue to the caller, each predecessor will be
3998   // updated to continue to the unwind destination of the cleanup pad being
3999   // simplified.
4000   BasicBlock *BB = RI->getParent();
4001   CleanupPadInst *CPInst = RI->getCleanupPad();
4002   if (CPInst->getParent() != BB)
4003     // This isn't an empty cleanup.
4004     return false;
4005 
4006   // We cannot kill the pad if it has multiple uses.  This typically arises
4007   // from unreachable basic blocks.
4008   if (!CPInst->hasOneUse())
4009     return false;
4010 
4011   // Check that there are no other instructions except for benign intrinsics.
4012   BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
4013   while (++I != E) {
4014     auto *II = dyn_cast<IntrinsicInst>(I);
4015     if (!II)
4016       return false;
4017 
4018     Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4019     switch (IntrinsicID) {
4020     case Intrinsic::dbg_declare:
4021     case Intrinsic::dbg_value:
4022     case Intrinsic::dbg_label:
4023     case Intrinsic::lifetime_end:
4024       break;
4025     default:
4026       return false;
4027     }
4028   }
4029 
4030   // If the cleanup return we are simplifying unwinds to the caller, this will
4031   // set UnwindDest to nullptr.
4032   BasicBlock *UnwindDest = RI->getUnwindDest();
4033   Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
4034 
4035   // We're about to remove BB from the control flow.  Before we do, sink any
4036   // PHINodes into the unwind destination.  Doing this before changing the
4037   // control flow avoids some potentially slow checks, since we can currently
4038   // be certain that UnwindDest and BB have no common predecessors (since they
4039   // are both EH pads).
4040   if (UnwindDest) {
4041     // First, go through the PHI nodes in UnwindDest and update any nodes that
4042     // reference the block we are removing
4043     for (BasicBlock::iterator I = UnwindDest->begin(),
4044                               IE = DestEHPad->getIterator();
4045          I != IE; ++I) {
4046       PHINode *DestPN = cast<PHINode>(I);
4047 
4048       int Idx = DestPN->getBasicBlockIndex(BB);
4049       // Since BB unwinds to UnwindDest, it has to be in the PHI node.
4050       assert(Idx != -1);
4051       // This PHI node has an incoming value that corresponds to a control
4052       // path through the cleanup pad we are removing.  If the incoming
4053       // value is in the cleanup pad, it must be a PHINode (because we
4054       // verified above that the block is otherwise empty).  Otherwise, the
4055       // value is either a constant or a value that dominates the cleanup
4056       // pad being removed.
4057       //
4058       // Because BB and UnwindDest are both EH pads, all of their
4059       // predecessors must unwind to these blocks, and since no instruction
4060       // can have multiple unwind destinations, there will be no overlap in
4061       // incoming blocks between SrcPN and DestPN.
4062       Value *SrcVal = DestPN->getIncomingValue(Idx);
4063       PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
4064 
4065       // Remove the entry for the block we are deleting.
4066       DestPN->removeIncomingValue(Idx, false);
4067 
4068       if (SrcPN && SrcPN->getParent() == BB) {
4069         // If the incoming value was a PHI node in the cleanup pad we are
4070         // removing, we need to merge that PHI node's incoming values into
4071         // DestPN.
4072         for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
4073              SrcIdx != SrcE; ++SrcIdx) {
4074           DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
4075                               SrcPN->getIncomingBlock(SrcIdx));
4076         }
4077       } else {
4078         // Otherwise, the incoming value came from above BB and
4079         // so we can just reuse it.  We must associate all of BB's
4080         // predecessors with this value.
4081         for (auto *pred : predecessors(BB)) {
4082           DestPN->addIncoming(SrcVal, pred);
4083         }
4084       }
4085     }
4086 
4087     // Sink any remaining PHI nodes directly into UnwindDest.
4088     Instruction *InsertPt = DestEHPad;
4089     for (BasicBlock::iterator I = BB->begin(),
4090                               IE = BB->getFirstNonPHI()->getIterator();
4091          I != IE;) {
4092       // The iterator must be incremented here because the instructions are
4093       // being moved to another block.
4094       PHINode *PN = cast<PHINode>(I++);
4095       if (PN->use_empty() || !PN->isUsedOutsideOfBlock(BB))
4096         // If the PHI node has no uses or all of its uses are in this basic
4097         // block (meaning they are debug or lifetime intrinsics), just leave
4098         // it.  It will be erased when we erase BB below.
4099         continue;
4100 
4101       // Otherwise, sink this PHI node into UnwindDest.
4102       // Any predecessors to UnwindDest which are not already represented
4103       // must be back edges which inherit the value from the path through
4104       // BB.  In this case, the PHI value must reference itself.
4105       for (auto *pred : predecessors(UnwindDest))
4106         if (pred != BB)
4107           PN->addIncoming(PN, pred);
4108       PN->moveBefore(InsertPt);
4109     }
4110   }
4111 
4112   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
4113     // The iterator must be updated here because we are removing this pred.
4114     BasicBlock *PredBB = *PI++;
4115     if (UnwindDest == nullptr) {
4116       removeUnwindEdge(PredBB);
4117     } else {
4118       Instruction *TI = PredBB->getTerminator();
4119       TI->replaceUsesOfWith(BB, UnwindDest);
4120     }
4121   }
4122 
4123   // The cleanup pad is now unreachable.  Zap it.
4124   BB->eraseFromParent();
4125   return true;
4126 }
4127 
4128 // Try to merge two cleanuppads together.
4129 static bool mergeCleanupPad(CleanupReturnInst *RI) {
4130   // Skip any cleanuprets which unwind to caller, there is nothing to merge
4131   // with.
4132   BasicBlock *UnwindDest = RI->getUnwindDest();
4133   if (!UnwindDest)
4134     return false;
4135 
4136   // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
4137   // be safe to merge without code duplication.
4138   if (UnwindDest->getSinglePredecessor() != RI->getParent())
4139     return false;
4140 
4141   // Verify that our cleanuppad's unwind destination is another cleanuppad.
4142   auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
4143   if (!SuccessorCleanupPad)
4144     return false;
4145 
4146   CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
4147   // Replace any uses of the successor cleanupad with the predecessor pad
4148   // The only cleanuppad uses should be this cleanupret, it's cleanupret and
4149   // funclet bundle operands.
4150   SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
4151   // Remove the old cleanuppad.
4152   SuccessorCleanupPad->eraseFromParent();
4153   // Now, we simply replace the cleanupret with a branch to the unwind
4154   // destination.
4155   BranchInst::Create(UnwindDest, RI->getParent());
4156   RI->eraseFromParent();
4157 
4158   return true;
4159 }
4160 
4161 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
4162   // It is possible to transiantly have an undef cleanuppad operand because we
4163   // have deleted some, but not all, dead blocks.
4164   // Eventually, this block will be deleted.
4165   if (isa<UndefValue>(RI->getOperand(0)))
4166     return false;
4167 
4168   if (mergeCleanupPad(RI))
4169     return true;
4170 
4171   if (removeEmptyCleanup(RI))
4172     return true;
4173 
4174   return false;
4175 }
4176 
4177 bool SimplifyCFGOpt::simplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
4178   BasicBlock *BB = RI->getParent();
4179   if (!BB->getFirstNonPHIOrDbg()->isTerminator())
4180     return false;
4181 
4182   // Find predecessors that end with branches.
4183   SmallVector<BasicBlock *, 8> UncondBranchPreds;
4184   SmallVector<BranchInst *, 8> CondBranchPreds;
4185   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
4186     BasicBlock *P = *PI;
4187     Instruction *PTI = P->getTerminator();
4188     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4189       if (BI->isUnconditional())
4190         UncondBranchPreds.push_back(P);
4191       else
4192         CondBranchPreds.push_back(BI);
4193     }
4194   }
4195 
4196   // If we found some, do the transformation!
4197   if (!UncondBranchPreds.empty() && DupRet) {
4198     while (!UncondBranchPreds.empty()) {
4199       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
4200       LLVM_DEBUG(dbgs() << "FOLDING: " << *BB
4201                         << "INTO UNCOND BRANCH PRED: " << *Pred);
4202       (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
4203     }
4204 
4205     // If we eliminated all predecessors of the block, delete the block now.
4206     if (pred_empty(BB)) {
4207       // We know there are no successors, so just nuke the block.
4208       if (LoopHeaders)
4209         LoopHeaders->erase(BB);
4210       BB->eraseFromParent();
4211     }
4212 
4213     return true;
4214   }
4215 
4216   // Check out all of the conditional branches going to this return
4217   // instruction.  If any of them just select between returns, change the
4218   // branch itself into a select/return pair.
4219   while (!CondBranchPreds.empty()) {
4220     BranchInst *BI = CondBranchPreds.pop_back_val();
4221 
4222     // Check to see if the non-BB successor is also a return block.
4223     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
4224         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
4225         SimplifyCondBranchToTwoReturns(BI, Builder))
4226       return true;
4227   }
4228   return false;
4229 }
4230 
4231 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
4232   BasicBlock *BB = UI->getParent();
4233 
4234   bool Changed = false;
4235 
4236   // If there are any instructions immediately before the unreachable that can
4237   // be removed, do so.
4238   while (UI->getIterator() != BB->begin()) {
4239     BasicBlock::iterator BBI = UI->getIterator();
4240     --BBI;
4241     // Do not delete instructions that can have side effects which might cause
4242     // the unreachable to not be reachable; specifically, calls and volatile
4243     // operations may have this effect.
4244     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4245       break;
4246 
4247     if (BBI->mayHaveSideEffects()) {
4248       if (auto *SI = dyn_cast<StoreInst>(BBI)) {
4249         if (SI->isVolatile())
4250           break;
4251       } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
4252         if (LI->isVolatile())
4253           break;
4254       } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
4255         if (RMWI->isVolatile())
4256           break;
4257       } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
4258         if (CXI->isVolatile())
4259           break;
4260       } else if (isa<CatchPadInst>(BBI)) {
4261         // A catchpad may invoke exception object constructors and such, which
4262         // in some languages can be arbitrary code, so be conservative by
4263         // default.
4264         // For CoreCLR, it just involves a type test, so can be removed.
4265         if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
4266             EHPersonality::CoreCLR)
4267           break;
4268       } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4269                  !isa<LandingPadInst>(BBI)) {
4270         break;
4271       }
4272       // Note that deleting LandingPad's here is in fact okay, although it
4273       // involves a bit of subtle reasoning. If this inst is a LandingPad,
4274       // all the predecessors of this block will be the unwind edges of Invokes,
4275       // and we can therefore guarantee this block will be erased.
4276     }
4277 
4278     // Delete this instruction (any uses are guaranteed to be dead)
4279     if (!BBI->use_empty())
4280       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
4281     BBI->eraseFromParent();
4282     Changed = true;
4283   }
4284 
4285   // If the unreachable instruction is the first in the block, take a gander
4286   // at all of the predecessors of this instruction, and simplify them.
4287   if (&BB->front() != UI)
4288     return Changed;
4289 
4290   SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
4291   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4292     Instruction *TI = Preds[i]->getTerminator();
4293     IRBuilder<> Builder(TI);
4294     if (auto *BI = dyn_cast<BranchInst>(TI)) {
4295       if (BI->isUnconditional()) {
4296         assert(BI->getSuccessor(0) == BB && "Incorrect CFG");
4297         new UnreachableInst(TI->getContext(), TI);
4298         TI->eraseFromParent();
4299         Changed = true;
4300       } else {
4301         Value* Cond = BI->getCondition();
4302         if (BI->getSuccessor(0) == BB) {
4303           Builder.CreateAssumption(Builder.CreateNot(Cond));
4304           Builder.CreateBr(BI->getSuccessor(1));
4305         } else {
4306           assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
4307           Builder.CreateAssumption(Cond);
4308           Builder.CreateBr(BI->getSuccessor(0));
4309         }
4310         EraseTerminatorAndDCECond(BI);
4311         Changed = true;
4312       }
4313     } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
4314       SwitchInstProfUpdateWrapper SU(*SI);
4315       for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
4316         if (i->getCaseSuccessor() != BB) {
4317           ++i;
4318           continue;
4319         }
4320         BB->removePredecessor(SU->getParent());
4321         i = SU.removeCase(i);
4322         e = SU->case_end();
4323         Changed = true;
4324       }
4325     } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4326       if (II->getUnwindDest() == BB) {
4327         removeUnwindEdge(TI->getParent());
4328         Changed = true;
4329       }
4330     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4331       if (CSI->getUnwindDest() == BB) {
4332         removeUnwindEdge(TI->getParent());
4333         Changed = true;
4334         continue;
4335       }
4336 
4337       for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4338                                              E = CSI->handler_end();
4339            I != E; ++I) {
4340         if (*I == BB) {
4341           CSI->removeHandler(I);
4342           --I;
4343           --E;
4344           Changed = true;
4345         }
4346       }
4347       if (CSI->getNumHandlers() == 0) {
4348         BasicBlock *CatchSwitchBB = CSI->getParent();
4349         if (CSI->hasUnwindDest()) {
4350           // Redirect preds to the unwind dest
4351           CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
4352         } else {
4353           // Rewrite all preds to unwind to caller (or from invoke to call).
4354           SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
4355           for (BasicBlock *EHPred : EHPreds)
4356             removeUnwindEdge(EHPred);
4357         }
4358         // The catchswitch is no longer reachable.
4359         new UnreachableInst(CSI->getContext(), CSI);
4360         CSI->eraseFromParent();
4361         Changed = true;
4362       }
4363     } else if (isa<CleanupReturnInst>(TI)) {
4364       new UnreachableInst(TI->getContext(), TI);
4365       TI->eraseFromParent();
4366       Changed = true;
4367     }
4368   }
4369 
4370   // If this block is now dead, remove it.
4371   if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
4372     // We know there are no successors, so just nuke the block.
4373     if (LoopHeaders)
4374       LoopHeaders->erase(BB);
4375     BB->eraseFromParent();
4376     return true;
4377   }
4378 
4379   return Changed;
4380 }
4381 
4382 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4383   assert(Cases.size() >= 1);
4384 
4385   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4386   for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4387     if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4388       return false;
4389   }
4390   return true;
4391 }
4392 
4393 static void createUnreachableSwitchDefault(SwitchInst *Switch) {
4394   LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
4395   BasicBlock *NewDefaultBlock =
4396      SplitBlockPredecessors(Switch->getDefaultDest(), Switch->getParent(), "");
4397   Switch->setDefaultDest(&*NewDefaultBlock);
4398   SplitBlock(&*NewDefaultBlock, &NewDefaultBlock->front());
4399   auto *NewTerminator = NewDefaultBlock->getTerminator();
4400   new UnreachableInst(Switch->getContext(), NewTerminator);
4401   EraseTerminatorAndDCECond(NewTerminator);
4402 }
4403 
4404 /// Turn a switch with two reachable destinations into an integer range
4405 /// comparison and branch.
4406 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
4407   assert(SI->getNumCases() > 1 && "Degenerate switch?");
4408 
4409   bool HasDefault =
4410       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4411 
4412   // Partition the cases into two sets with different destinations.
4413   BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4414   BasicBlock *DestB = nullptr;
4415   SmallVector<ConstantInt *, 16> CasesA;
4416   SmallVector<ConstantInt *, 16> CasesB;
4417 
4418   for (auto Case : SI->cases()) {
4419     BasicBlock *Dest = Case.getCaseSuccessor();
4420     if (!DestA)
4421       DestA = Dest;
4422     if (Dest == DestA) {
4423       CasesA.push_back(Case.getCaseValue());
4424       continue;
4425     }
4426     if (!DestB)
4427       DestB = Dest;
4428     if (Dest == DestB) {
4429       CasesB.push_back(Case.getCaseValue());
4430       continue;
4431     }
4432     return false; // More than two destinations.
4433   }
4434 
4435   assert(DestA && DestB &&
4436          "Single-destination switch should have been folded.");
4437   assert(DestA != DestB);
4438   assert(DestB != SI->getDefaultDest());
4439   assert(!CasesB.empty() && "There must be non-default cases.");
4440   assert(!CasesA.empty() || HasDefault);
4441 
4442   // Figure out if one of the sets of cases form a contiguous range.
4443   SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4444   BasicBlock *ContiguousDest = nullptr;
4445   BasicBlock *OtherDest = nullptr;
4446   if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4447     ContiguousCases = &CasesA;
4448     ContiguousDest = DestA;
4449     OtherDest = DestB;
4450   } else if (CasesAreContiguous(CasesB)) {
4451     ContiguousCases = &CasesB;
4452     ContiguousDest = DestB;
4453     OtherDest = DestA;
4454   } else
4455     return false;
4456 
4457   // Start building the compare and branch.
4458 
4459   Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
4460   Constant *NumCases =
4461       ConstantInt::get(Offset->getType(), ContiguousCases->size());
4462 
4463   Value *Sub = SI->getCondition();
4464   if (!Offset->isNullValue())
4465     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4466 
4467   Value *Cmp;
4468   // If NumCases overflowed, then all possible values jump to the successor.
4469   if (NumCases->isNullValue() && !ContiguousCases->empty())
4470     Cmp = ConstantInt::getTrue(SI->getContext());
4471   else
4472     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
4473   BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
4474 
4475   // Update weight for the newly-created conditional branch.
4476   if (HasBranchWeights(SI)) {
4477     SmallVector<uint64_t, 8> Weights;
4478     GetBranchWeights(SI, Weights);
4479     if (Weights.size() == 1 + SI->getNumCases()) {
4480       uint64_t TrueWeight = 0;
4481       uint64_t FalseWeight = 0;
4482       for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4483         if (SI->getSuccessor(I) == ContiguousDest)
4484           TrueWeight += Weights[I];
4485         else
4486           FalseWeight += Weights[I];
4487       }
4488       while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4489         TrueWeight /= 2;
4490         FalseWeight /= 2;
4491       }
4492       setBranchWeights(NewBI, TrueWeight, FalseWeight);
4493     }
4494   }
4495 
4496   // Prune obsolete incoming values off the successors' PHI nodes.
4497   for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4498     unsigned PreviousEdges = ContiguousCases->size();
4499     if (ContiguousDest == SI->getDefaultDest())
4500       ++PreviousEdges;
4501     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4502       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4503   }
4504   for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4505     unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
4506     if (OtherDest == SI->getDefaultDest())
4507       ++PreviousEdges;
4508     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4509       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4510   }
4511 
4512   // Clean up the default block - it may have phis or other instructions before
4513   // the unreachable terminator.
4514   if (!HasDefault)
4515     createUnreachableSwitchDefault(SI);
4516 
4517   // Drop the switch.
4518   SI->eraseFromParent();
4519 
4520   return true;
4521 }
4522 
4523 /// Compute masked bits for the condition of a switch
4524 /// and use it to remove dead cases.
4525 static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
4526                                      const DataLayout &DL) {
4527   Value *Cond = SI->getCondition();
4528   unsigned Bits = Cond->getType()->getIntegerBitWidth();
4529   KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
4530 
4531   // We can also eliminate cases by determining that their values are outside of
4532   // the limited range of the condition based on how many significant (non-sign)
4533   // bits are in the condition value.
4534   unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
4535   unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4536 
4537   // Gather dead cases.
4538   SmallVector<ConstantInt *, 8> DeadCases;
4539   for (auto &Case : SI->cases()) {
4540     const APInt &CaseVal = Case.getCaseValue()->getValue();
4541     if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
4542         (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
4543       DeadCases.push_back(Case.getCaseValue());
4544       LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
4545                         << " is dead.\n");
4546     }
4547   }
4548 
4549   // If we can prove that the cases must cover all possible values, the
4550   // default destination becomes dead and we can remove it.  If we know some
4551   // of the bits in the value, we can use that to more precisely compute the
4552   // number of possible unique case values.
4553   bool HasDefault =
4554       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4555   const unsigned NumUnknownBits =
4556       Bits - (Known.Zero | Known.One).countPopulation();
4557   assert(NumUnknownBits <= Bits);
4558   if (HasDefault && DeadCases.empty() &&
4559       NumUnknownBits < 64 /* avoid overflow */ &&
4560       SI->getNumCases() == (1ULL << NumUnknownBits)) {
4561     createUnreachableSwitchDefault(SI);
4562     return true;
4563   }
4564 
4565   if (DeadCases.empty())
4566     return false;
4567 
4568   SwitchInstProfUpdateWrapper SIW(*SI);
4569   for (ConstantInt *DeadCase : DeadCases) {
4570     SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
4571     assert(CaseI != SI->case_default() &&
4572            "Case was not found. Probably mistake in DeadCases forming.");
4573     // Prune unused values from PHI nodes.
4574     CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
4575     SIW.removeCase(CaseI);
4576   }
4577 
4578   return true;
4579 }
4580 
4581 /// If BB would be eligible for simplification by
4582 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
4583 /// by an unconditional branch), look at the phi node for BB in the successor
4584 /// block and see if the incoming value is equal to CaseValue. If so, return
4585 /// the phi node, and set PhiIndex to BB's index in the phi node.
4586 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
4587                                               BasicBlock *BB, int *PhiIndex) {
4588   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
4589     return nullptr; // BB must be empty to be a candidate for simplification.
4590   if (!BB->getSinglePredecessor())
4591     return nullptr; // BB must be dominated by the switch.
4592 
4593   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4594   if (!Branch || !Branch->isUnconditional())
4595     return nullptr; // Terminator must be unconditional branch.
4596 
4597   BasicBlock *Succ = Branch->getSuccessor(0);
4598 
4599   for (PHINode &PHI : Succ->phis()) {
4600     int Idx = PHI.getBasicBlockIndex(BB);
4601     assert(Idx >= 0 && "PHI has no entry for predecessor?");
4602 
4603     Value *InValue = PHI.getIncomingValue(Idx);
4604     if (InValue != CaseValue)
4605       continue;
4606 
4607     *PhiIndex = Idx;
4608     return &PHI;
4609   }
4610 
4611   return nullptr;
4612 }
4613 
4614 /// Try to forward the condition of a switch instruction to a phi node
4615 /// dominated by the switch, if that would mean that some of the destination
4616 /// blocks of the switch can be folded away. Return true if a change is made.
4617 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
4618   using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
4619 
4620   ForwardingNodesMap ForwardingNodes;
4621   BasicBlock *SwitchBlock = SI->getParent();
4622   bool Changed = false;
4623   for (auto &Case : SI->cases()) {
4624     ConstantInt *CaseValue = Case.getCaseValue();
4625     BasicBlock *CaseDest = Case.getCaseSuccessor();
4626 
4627     // Replace phi operands in successor blocks that are using the constant case
4628     // value rather than the switch condition variable:
4629     //   switchbb:
4630     //   switch i32 %x, label %default [
4631     //     i32 17, label %succ
4632     //   ...
4633     //   succ:
4634     //     %r = phi i32 ... [ 17, %switchbb ] ...
4635     // -->
4636     //     %r = phi i32 ... [ %x, %switchbb ] ...
4637 
4638     for (PHINode &Phi : CaseDest->phis()) {
4639       // This only works if there is exactly 1 incoming edge from the switch to
4640       // a phi. If there is >1, that means multiple cases of the switch map to 1
4641       // value in the phi, and that phi value is not the switch condition. Thus,
4642       // this transform would not make sense (the phi would be invalid because
4643       // a phi can't have different incoming values from the same block).
4644       int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
4645       if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
4646           count(Phi.blocks(), SwitchBlock) == 1) {
4647         Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
4648         Changed = true;
4649       }
4650     }
4651 
4652     // Collect phi nodes that are indirectly using this switch's case constants.
4653     int PhiIdx;
4654     if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
4655       ForwardingNodes[Phi].push_back(PhiIdx);
4656   }
4657 
4658   for (auto &ForwardingNode : ForwardingNodes) {
4659     PHINode *Phi = ForwardingNode.first;
4660     SmallVectorImpl<int> &Indexes = ForwardingNode.second;
4661     if (Indexes.size() < 2)
4662       continue;
4663 
4664     for (int Index : Indexes)
4665       Phi->setIncomingValue(Index, SI->getCondition());
4666     Changed = true;
4667   }
4668 
4669   return Changed;
4670 }
4671 
4672 /// Return true if the backend will be able to handle
4673 /// initializing an array of constants like C.
4674 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
4675   if (C->isThreadDependent())
4676     return false;
4677   if (C->isDLLImportDependent())
4678     return false;
4679 
4680   if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
4681       !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
4682       !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
4683     return false;
4684 
4685   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
4686     if (!CE->isGEPWithNoNotionalOverIndexing())
4687       return false;
4688     if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
4689       return false;
4690   }
4691 
4692   if (!TTI.shouldBuildLookupTablesForConstant(C))
4693     return false;
4694 
4695   return true;
4696 }
4697 
4698 /// If V is a Constant, return it. Otherwise, try to look up
4699 /// its constant value in ConstantPool, returning 0 if it's not there.
4700 static Constant *
4701 LookupConstant(Value *V,
4702                const SmallDenseMap<Value *, Constant *> &ConstantPool) {
4703   if (Constant *C = dyn_cast<Constant>(V))
4704     return C;
4705   return ConstantPool.lookup(V);
4706 }
4707 
4708 /// Try to fold instruction I into a constant. This works for
4709 /// simple instructions such as binary operations where both operands are
4710 /// constant or can be replaced by constants from the ConstantPool. Returns the
4711 /// resulting constant on success, 0 otherwise.
4712 static Constant *
4713 ConstantFold(Instruction *I, const DataLayout &DL,
4714              const SmallDenseMap<Value *, Constant *> &ConstantPool) {
4715   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
4716     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4717     if (!A)
4718       return nullptr;
4719     if (A->isAllOnesValue())
4720       return LookupConstant(Select->getTrueValue(), ConstantPool);
4721     if (A->isNullValue())
4722       return LookupConstant(Select->getFalseValue(), ConstantPool);
4723     return nullptr;
4724   }
4725 
4726   SmallVector<Constant *, 4> COps;
4727   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4728     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4729       COps.push_back(A);
4730     else
4731       return nullptr;
4732   }
4733 
4734   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
4735     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4736                                            COps[1], DL);
4737   }
4738 
4739   return ConstantFoldInstOperands(I, COps, DL);
4740 }
4741 
4742 /// Try to determine the resulting constant values in phi nodes
4743 /// at the common destination basic block, *CommonDest, for one of the case
4744 /// destionations CaseDest corresponding to value CaseVal (0 for the default
4745 /// case), of a switch instruction SI.
4746 static bool
4747 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
4748                BasicBlock **CommonDest,
4749                SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4750                const DataLayout &DL, const TargetTransformInfo &TTI) {
4751   // The block from which we enter the common destination.
4752   BasicBlock *Pred = SI->getParent();
4753 
4754   // If CaseDest is empty except for some side-effect free instructions through
4755   // which we can constant-propagate the CaseVal, continue to its successor.
4756   SmallDenseMap<Value *, Constant *> ConstantPool;
4757   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4758   for (Instruction &I :CaseDest->instructionsWithoutDebug()) {
4759     if (I.isTerminator()) {
4760       // If the terminator is a simple branch, continue to the next block.
4761       if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
4762         return false;
4763       Pred = CaseDest;
4764       CaseDest = I.getSuccessor(0);
4765     } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
4766       // Instruction is side-effect free and constant.
4767 
4768       // If the instruction has uses outside this block or a phi node slot for
4769       // the block, it is not safe to bypass the instruction since it would then
4770       // no longer dominate all its uses.
4771       for (auto &Use : I.uses()) {
4772         User *User = Use.getUser();
4773         if (Instruction *I = dyn_cast<Instruction>(User))
4774           if (I->getParent() == CaseDest)
4775             continue;
4776         if (PHINode *Phi = dyn_cast<PHINode>(User))
4777           if (Phi->getIncomingBlock(Use) == CaseDest)
4778             continue;
4779         return false;
4780       }
4781 
4782       ConstantPool.insert(std::make_pair(&I, C));
4783     } else {
4784       break;
4785     }
4786   }
4787 
4788   // If we did not have a CommonDest before, use the current one.
4789   if (!*CommonDest)
4790     *CommonDest = CaseDest;
4791   // If the destination isn't the common one, abort.
4792   if (CaseDest != *CommonDest)
4793     return false;
4794 
4795   // Get the values for this case from phi nodes in the destination block.
4796   for (PHINode &PHI : (*CommonDest)->phis()) {
4797     int Idx = PHI.getBasicBlockIndex(Pred);
4798     if (Idx == -1)
4799       continue;
4800 
4801     Constant *ConstVal =
4802         LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
4803     if (!ConstVal)
4804       return false;
4805 
4806     // Be conservative about which kinds of constants we support.
4807     if (!ValidLookupTableConstant(ConstVal, TTI))
4808       return false;
4809 
4810     Res.push_back(std::make_pair(&PHI, ConstVal));
4811   }
4812 
4813   return Res.size() > 0;
4814 }
4815 
4816 // Helper function used to add CaseVal to the list of cases that generate
4817 // Result. Returns the updated number of cases that generate this result.
4818 static uintptr_t MapCaseToResult(ConstantInt *CaseVal,
4819                                  SwitchCaseResultVectorTy &UniqueResults,
4820                                  Constant *Result) {
4821   for (auto &I : UniqueResults) {
4822     if (I.first == Result) {
4823       I.second.push_back(CaseVal);
4824       return I.second.size();
4825     }
4826   }
4827   UniqueResults.push_back(
4828       std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
4829   return 1;
4830 }
4831 
4832 // Helper function that initializes a map containing
4833 // results for the PHI node of the common destination block for a switch
4834 // instruction. Returns false if multiple PHI nodes have been found or if
4835 // there is not a common destination block for the switch.
4836 static bool
4837 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest,
4838                       SwitchCaseResultVectorTy &UniqueResults,
4839                       Constant *&DefaultResult, const DataLayout &DL,
4840                       const TargetTransformInfo &TTI,
4841                       uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
4842   for (auto &I : SI->cases()) {
4843     ConstantInt *CaseVal = I.getCaseValue();
4844 
4845     // Resulting value at phi nodes for this case value.
4846     SwitchCaseResultsTy Results;
4847     if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4848                         DL, TTI))
4849       return false;
4850 
4851     // Only one value per case is permitted.
4852     if (Results.size() > 1)
4853       return false;
4854 
4855     // Add the case->result mapping to UniqueResults.
4856     const uintptr_t NumCasesForResult =
4857         MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4858 
4859     // Early out if there are too many cases for this result.
4860     if (NumCasesForResult > MaxCasesPerResult)
4861       return false;
4862 
4863     // Early out if there are too many unique results.
4864     if (UniqueResults.size() > MaxUniqueResults)
4865       return false;
4866 
4867     // Check the PHI consistency.
4868     if (!PHI)
4869       PHI = Results[0].first;
4870     else if (PHI != Results[0].first)
4871       return false;
4872   }
4873   // Find the default result value.
4874   SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4875   BasicBlock *DefaultDest = SI->getDefaultDest();
4876   GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4877                  DL, TTI);
4878   // If the default value is not found abort unless the default destination
4879   // is unreachable.
4880   DefaultResult =
4881       DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4882   if ((!DefaultResult &&
4883        !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4884     return false;
4885 
4886   return true;
4887 }
4888 
4889 // Helper function that checks if it is possible to transform a switch with only
4890 // two cases (or two cases + default) that produces a result into a select.
4891 // Example:
4892 // switch (a) {
4893 //   case 10:                %0 = icmp eq i32 %a, 10
4894 //     return 10;            %1 = select i1 %0, i32 10, i32 4
4895 //   case 20:        ---->   %2 = icmp eq i32 %a, 20
4896 //     return 2;             %3 = select i1 %2, i32 2, i32 %1
4897 //   default:
4898 //     return 4;
4899 // }
4900 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4901                                    Constant *DefaultResult, Value *Condition,
4902                                    IRBuilder<> &Builder) {
4903   assert(ResultVector.size() == 2 &&
4904          "We should have exactly two unique results at this point");
4905   // If we are selecting between only two cases transform into a simple
4906   // select or a two-way select if default is possible.
4907   if (ResultVector[0].second.size() == 1 &&
4908       ResultVector[1].second.size() == 1) {
4909     ConstantInt *const FirstCase = ResultVector[0].second[0];
4910     ConstantInt *const SecondCase = ResultVector[1].second[0];
4911 
4912     bool DefaultCanTrigger = DefaultResult;
4913     Value *SelectValue = ResultVector[1].first;
4914     if (DefaultCanTrigger) {
4915       Value *const ValueCompare =
4916           Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4917       SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4918                                          DefaultResult, "switch.select");
4919     }
4920     Value *const ValueCompare =
4921         Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4922     return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
4923                                 SelectValue, "switch.select");
4924   }
4925 
4926   return nullptr;
4927 }
4928 
4929 // Helper function to cleanup a switch instruction that has been converted into
4930 // a select, fixing up PHI nodes and basic blocks.
4931 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4932                                               Value *SelectValue,
4933                                               IRBuilder<> &Builder) {
4934   BasicBlock *SelectBB = SI->getParent();
4935   while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4936     PHI->removeIncomingValue(SelectBB);
4937   PHI->addIncoming(SelectValue, SelectBB);
4938 
4939   Builder.CreateBr(PHI->getParent());
4940 
4941   // Remove the switch.
4942   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4943     BasicBlock *Succ = SI->getSuccessor(i);
4944 
4945     if (Succ == PHI->getParent())
4946       continue;
4947     Succ->removePredecessor(SelectBB);
4948   }
4949   SI->eraseFromParent();
4950 }
4951 
4952 /// If the switch is only used to initialize one or more
4953 /// phi nodes in a common successor block with only two different
4954 /// constant values, replace the switch with select.
4955 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
4956                            const DataLayout &DL,
4957                            const TargetTransformInfo &TTI) {
4958   Value *const Cond = SI->getCondition();
4959   PHINode *PHI = nullptr;
4960   BasicBlock *CommonDest = nullptr;
4961   Constant *DefaultResult;
4962   SwitchCaseResultVectorTy UniqueResults;
4963   // Collect all the cases that will deliver the same value from the switch.
4964   if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4965                              DL, TTI, 2, 1))
4966     return false;
4967   // Selects choose between maximum two values.
4968   if (UniqueResults.size() != 2)
4969     return false;
4970   assert(PHI != nullptr && "PHI for value select not found");
4971 
4972   Builder.SetInsertPoint(SI);
4973   Value *SelectValue =
4974       ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
4975   if (SelectValue) {
4976     RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4977     return true;
4978   }
4979   // The switch couldn't be converted into a select.
4980   return false;
4981 }
4982 
4983 namespace {
4984 
4985 /// This class represents a lookup table that can be used to replace a switch.
4986 class SwitchLookupTable {
4987 public:
4988   /// Create a lookup table to use as a switch replacement with the contents
4989   /// of Values, using DefaultValue to fill any holes in the table.
4990   SwitchLookupTable(
4991       Module &M, uint64_t TableSize, ConstantInt *Offset,
4992       const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4993       Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
4994 
4995   /// Build instructions with Builder to retrieve the value at
4996   /// the position given by Index in the lookup table.
4997   Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
4998 
4999   /// Return true if a table with TableSize elements of
5000   /// type ElementType would fit in a target-legal register.
5001   static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
5002                                  Type *ElementType);
5003 
5004 private:
5005   // Depending on the contents of the table, it can be represented in
5006   // different ways.
5007   enum {
5008     // For tables where each element contains the same value, we just have to
5009     // store that single value and return it for each lookup.
5010     SingleValueKind,
5011 
5012     // For tables where there is a linear relationship between table index
5013     // and values. We calculate the result with a simple multiplication
5014     // and addition instead of a table lookup.
5015     LinearMapKind,
5016 
5017     // For small tables with integer elements, we can pack them into a bitmap
5018     // that fits into a target-legal register. Values are retrieved by
5019     // shift and mask operations.
5020     BitMapKind,
5021 
5022     // The table is stored as an array of values. Values are retrieved by load
5023     // instructions from the table.
5024     ArrayKind
5025   } Kind;
5026 
5027   // For SingleValueKind, this is the single value.
5028   Constant *SingleValue = nullptr;
5029 
5030   // For BitMapKind, this is the bitmap.
5031   ConstantInt *BitMap = nullptr;
5032   IntegerType *BitMapElementTy = nullptr;
5033 
5034   // For LinearMapKind, these are the constants used to derive the value.
5035   ConstantInt *LinearOffset = nullptr;
5036   ConstantInt *LinearMultiplier = nullptr;
5037 
5038   // For ArrayKind, this is the array.
5039   GlobalVariable *Array = nullptr;
5040 };
5041 
5042 } // end anonymous namespace
5043 
5044 SwitchLookupTable::SwitchLookupTable(
5045     Module &M, uint64_t TableSize, ConstantInt *Offset,
5046     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5047     Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
5048   assert(Values.size() && "Can't build lookup table without values!");
5049   assert(TableSize >= Values.size() && "Can't fit values in table!");
5050 
5051   // If all values in the table are equal, this is that value.
5052   SingleValue = Values.begin()->second;
5053 
5054   Type *ValueType = Values.begin()->second->getType();
5055 
5056   // Build up the table contents.
5057   SmallVector<Constant *, 64> TableContents(TableSize);
5058   for (size_t I = 0, E = Values.size(); I != E; ++I) {
5059     ConstantInt *CaseVal = Values[I].first;
5060     Constant *CaseRes = Values[I].second;
5061     assert(CaseRes->getType() == ValueType);
5062 
5063     uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
5064     TableContents[Idx] = CaseRes;
5065 
5066     if (CaseRes != SingleValue)
5067       SingleValue = nullptr;
5068   }
5069 
5070   // Fill in any holes in the table with the default result.
5071   if (Values.size() < TableSize) {
5072     assert(DefaultValue &&
5073            "Need a default value to fill the lookup table holes.");
5074     assert(DefaultValue->getType() == ValueType);
5075     for (uint64_t I = 0; I < TableSize; ++I) {
5076       if (!TableContents[I])
5077         TableContents[I] = DefaultValue;
5078     }
5079 
5080     if (DefaultValue != SingleValue)
5081       SingleValue = nullptr;
5082   }
5083 
5084   // If each element in the table contains the same value, we only need to store
5085   // that single value.
5086   if (SingleValue) {
5087     Kind = SingleValueKind;
5088     return;
5089   }
5090 
5091   // Check if we can derive the value with a linear transformation from the
5092   // table index.
5093   if (isa<IntegerType>(ValueType)) {
5094     bool LinearMappingPossible = true;
5095     APInt PrevVal;
5096     APInt DistToPrev;
5097     assert(TableSize >= 2 && "Should be a SingleValue table.");
5098     // Check if there is the same distance between two consecutive values.
5099     for (uint64_t I = 0; I < TableSize; ++I) {
5100       ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
5101       if (!ConstVal) {
5102         // This is an undef. We could deal with it, but undefs in lookup tables
5103         // are very seldom. It's probably not worth the additional complexity.
5104         LinearMappingPossible = false;
5105         break;
5106       }
5107       const APInt &Val = ConstVal->getValue();
5108       if (I != 0) {
5109         APInt Dist = Val - PrevVal;
5110         if (I == 1) {
5111           DistToPrev = Dist;
5112         } else if (Dist != DistToPrev) {
5113           LinearMappingPossible = false;
5114           break;
5115         }
5116       }
5117       PrevVal = Val;
5118     }
5119     if (LinearMappingPossible) {
5120       LinearOffset = cast<ConstantInt>(TableContents[0]);
5121       LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
5122       Kind = LinearMapKind;
5123       ++NumLinearMaps;
5124       return;
5125     }
5126   }
5127 
5128   // If the type is integer and the table fits in a register, build a bitmap.
5129   if (WouldFitInRegister(DL, TableSize, ValueType)) {
5130     IntegerType *IT = cast<IntegerType>(ValueType);
5131     APInt TableInt(TableSize * IT->getBitWidth(), 0);
5132     for (uint64_t I = TableSize; I > 0; --I) {
5133       TableInt <<= IT->getBitWidth();
5134       // Insert values into the bitmap. Undef values are set to zero.
5135       if (!isa<UndefValue>(TableContents[I - 1])) {
5136         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5137         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
5138       }
5139     }
5140     BitMap = ConstantInt::get(M.getContext(), TableInt);
5141     BitMapElementTy = IT;
5142     Kind = BitMapKind;
5143     ++NumBitMaps;
5144     return;
5145   }
5146 
5147   // Store the table in an array.
5148   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
5149   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
5150 
5151   Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true,
5152                              GlobalVariable::PrivateLinkage, Initializer,
5153                              "switch.table." + FuncName);
5154   Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
5155   // Set the alignment to that of an array items. We will be only loading one
5156   // value out of it.
5157   Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType)));
5158   Kind = ArrayKind;
5159 }
5160 
5161 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
5162   switch (Kind) {
5163   case SingleValueKind:
5164     return SingleValue;
5165   case LinearMapKind: {
5166     // Derive the result value from the input value.
5167     Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
5168                                           false, "switch.idx.cast");
5169     if (!LinearMultiplier->isOne())
5170       Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
5171     if (!LinearOffset->isZero())
5172       Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
5173     return Result;
5174   }
5175   case BitMapKind: {
5176     // Type of the bitmap (e.g. i59).
5177     IntegerType *MapTy = BitMap->getType();
5178 
5179     // Cast Index to the same type as the bitmap.
5180     // Note: The Index is <= the number of elements in the table, so
5181     // truncating it to the width of the bitmask is safe.
5182     Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
5183 
5184     // Multiply the shift amount by the element width.
5185     ShiftAmt = Builder.CreateMul(
5186         ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
5187         "switch.shiftamt");
5188 
5189     // Shift down.
5190     Value *DownShifted =
5191         Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
5192     // Mask off.
5193     return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
5194   }
5195   case ArrayKind: {
5196     // Make sure the table index will not overflow when treated as signed.
5197     IntegerType *IT = cast<IntegerType>(Index->getType());
5198     uint64_t TableSize =
5199         Array->getInitializer()->getType()->getArrayNumElements();
5200     if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
5201       Index = Builder.CreateZExt(
5202           Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
5203           "switch.tableidx.zext");
5204 
5205     Value *GEPIndices[] = {Builder.getInt32(0), Index};
5206     Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
5207                                            GEPIndices, "switch.gep");
5208     return Builder.CreateLoad(
5209         cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
5210         "switch.load");
5211   }
5212   }
5213   llvm_unreachable("Unknown lookup table kind!");
5214 }
5215 
5216 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
5217                                            uint64_t TableSize,
5218                                            Type *ElementType) {
5219   auto *IT = dyn_cast<IntegerType>(ElementType);
5220   if (!IT)
5221     return false;
5222   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
5223   // are <= 15, we could try to narrow the type.
5224 
5225   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
5226   if (TableSize >= UINT_MAX / IT->getBitWidth())
5227     return false;
5228   return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
5229 }
5230 
5231 /// Determine whether a lookup table should be built for this switch, based on
5232 /// the number of cases, size of the table, and the types of the results.
5233 static bool
5234 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
5235                        const TargetTransformInfo &TTI, const DataLayout &DL,
5236                        const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
5237   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
5238     return false; // TableSize overflowed, or mul below might overflow.
5239 
5240   bool AllTablesFitInRegister = true;
5241   bool HasIllegalType = false;
5242   for (const auto &I : ResultTypes) {
5243     Type *Ty = I.second;
5244 
5245     // Saturate this flag to true.
5246     HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
5247 
5248     // Saturate this flag to false.
5249     AllTablesFitInRegister =
5250         AllTablesFitInRegister &&
5251         SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5252 
5253     // If both flags saturate, we're done. NOTE: This *only* works with
5254     // saturating flags, and all flags have to saturate first due to the
5255     // non-deterministic behavior of iterating over a dense map.
5256     if (HasIllegalType && !AllTablesFitInRegister)
5257       break;
5258   }
5259 
5260   // If each table would fit in a register, we should build it anyway.
5261   if (AllTablesFitInRegister)
5262     return true;
5263 
5264   // Don't build a table that doesn't fit in-register if it has illegal types.
5265   if (HasIllegalType)
5266     return false;
5267 
5268   // The table density should be at least 40%. This is the same criterion as for
5269   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
5270   // FIXME: Find the best cut-off.
5271   return SI->getNumCases() * 10 >= TableSize * 4;
5272 }
5273 
5274 /// Try to reuse the switch table index compare. Following pattern:
5275 /// \code
5276 ///     if (idx < tablesize)
5277 ///        r = table[idx]; // table does not contain default_value
5278 ///     else
5279 ///        r = default_value;
5280 ///     if (r != default_value)
5281 ///        ...
5282 /// \endcode
5283 /// Is optimized to:
5284 /// \code
5285 ///     cond = idx < tablesize;
5286 ///     if (cond)
5287 ///        r = table[idx];
5288 ///     else
5289 ///        r = default_value;
5290 ///     if (cond)
5291 ///        ...
5292 /// \endcode
5293 /// Jump threading will then eliminate the second if(cond).
5294 static void reuseTableCompare(
5295     User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
5296     Constant *DefaultValue,
5297     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5298   ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
5299   if (!CmpInst)
5300     return;
5301 
5302   // We require that the compare is in the same block as the phi so that jump
5303   // threading can do its work afterwards.
5304   if (CmpInst->getParent() != PhiBlock)
5305     return;
5306 
5307   Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5308   if (!CmpOp1)
5309     return;
5310 
5311   Value *RangeCmp = RangeCheckBranch->getCondition();
5312   Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5313   Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5314 
5315   // Check if the compare with the default value is constant true or false.
5316   Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5317                                                  DefaultValue, CmpOp1, true);
5318   if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5319     return;
5320 
5321   // Check if the compare with the case values is distinct from the default
5322   // compare result.
5323   for (auto ValuePair : Values) {
5324     Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5325                                                 ValuePair.second, CmpOp1, true);
5326     if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
5327       return;
5328     assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5329            "Expect true or false as compare result.");
5330   }
5331 
5332   // Check if the branch instruction dominates the phi node. It's a simple
5333   // dominance check, but sufficient for our needs.
5334   // Although this check is invariant in the calling loops, it's better to do it
5335   // at this late stage. Practically we do it at most once for a switch.
5336   BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5337   for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
5338     BasicBlock *Pred = *PI;
5339     if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5340       return;
5341   }
5342 
5343   if (DefaultConst == FalseConst) {
5344     // The compare yields the same result. We can replace it.
5345     CmpInst->replaceAllUsesWith(RangeCmp);
5346     ++NumTableCmpReuses;
5347   } else {
5348     // The compare yields the same result, just inverted. We can replace it.
5349     Value *InvertedTableCmp = BinaryOperator::CreateXor(
5350         RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5351         RangeCheckBranch);
5352     CmpInst->replaceAllUsesWith(InvertedTableCmp);
5353     ++NumTableCmpReuses;
5354   }
5355 }
5356 
5357 /// If the switch is only used to initialize one or more phi nodes in a common
5358 /// successor block with different constant values, replace the switch with
5359 /// lookup tables.
5360 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5361                                 const DataLayout &DL,
5362                                 const TargetTransformInfo &TTI) {
5363   assert(SI->getNumCases() > 1 && "Degenerate switch?");
5364 
5365   Function *Fn = SI->getParent()->getParent();
5366   // Only build lookup table when we have a target that supports it or the
5367   // attribute is not set.
5368   if (!TTI.shouldBuildLookupTables() ||
5369       (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
5370     return false;
5371 
5372   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5373   // split off a dense part and build a lookup table for that.
5374 
5375   // FIXME: This creates arrays of GEPs to constant strings, which means each
5376   // GEP needs a runtime relocation in PIC code. We should just build one big
5377   // string and lookup indices into that.
5378 
5379   // Ignore switches with less than three cases. Lookup tables will not make
5380   // them faster, so we don't analyze them.
5381   if (SI->getNumCases() < 3)
5382     return false;
5383 
5384   // Figure out the corresponding result for each case value and phi node in the
5385   // common destination, as well as the min and max case values.
5386   assert(!SI->cases().empty());
5387   SwitchInst::CaseIt CI = SI->case_begin();
5388   ConstantInt *MinCaseVal = CI->getCaseValue();
5389   ConstantInt *MaxCaseVal = CI->getCaseValue();
5390 
5391   BasicBlock *CommonDest = nullptr;
5392 
5393   using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
5394   SmallDenseMap<PHINode *, ResultListTy> ResultLists;
5395 
5396   SmallDenseMap<PHINode *, Constant *> DefaultResults;
5397   SmallDenseMap<PHINode *, Type *> ResultTypes;
5398   SmallVector<PHINode *, 4> PHIs;
5399 
5400   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
5401     ConstantInt *CaseVal = CI->getCaseValue();
5402     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5403       MinCaseVal = CaseVal;
5404     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5405       MaxCaseVal = CaseVal;
5406 
5407     // Resulting value at phi nodes for this case value.
5408     using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
5409     ResultsTy Results;
5410     if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
5411                         Results, DL, TTI))
5412       return false;
5413 
5414     // Append the result from this case to the list for each phi.
5415     for (const auto &I : Results) {
5416       PHINode *PHI = I.first;
5417       Constant *Value = I.second;
5418       if (!ResultLists.count(PHI))
5419         PHIs.push_back(PHI);
5420       ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5421     }
5422   }
5423 
5424   // Keep track of the result types.
5425   for (PHINode *PHI : PHIs) {
5426     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5427   }
5428 
5429   uint64_t NumResults = ResultLists[PHIs[0]].size();
5430   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5431   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5432   bool TableHasHoles = (NumResults < TableSize);
5433 
5434   // If the table has holes, we need a constant result for the default case
5435   // or a bitmask that fits in a register.
5436   SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
5437   bool HasDefaultResults =
5438       GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
5439                      DefaultResultsList, DL, TTI);
5440 
5441   bool NeedMask = (TableHasHoles && !HasDefaultResults);
5442   if (NeedMask) {
5443     // As an extra penalty for the validity test we require more cases.
5444     if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
5445       return false;
5446     if (!DL.fitsInLegalInteger(TableSize))
5447       return false;
5448   }
5449 
5450   for (const auto &I : DefaultResultsList) {
5451     PHINode *PHI = I.first;
5452     Constant *Result = I.second;
5453     DefaultResults[PHI] = Result;
5454   }
5455 
5456   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
5457     return false;
5458 
5459   // Create the BB that does the lookups.
5460   Module &Mod = *CommonDest->getParent()->getParent();
5461   BasicBlock *LookupBB = BasicBlock::Create(
5462       Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
5463 
5464   // Compute the table index value.
5465   Builder.SetInsertPoint(SI);
5466   Value *TableIndex;
5467   if (MinCaseVal->isNullValue())
5468     TableIndex = SI->getCondition();
5469   else
5470     TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
5471                                    "switch.tableidx");
5472 
5473   // Compute the maximum table size representable by the integer type we are
5474   // switching upon.
5475   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
5476   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
5477   assert(MaxTableSize >= TableSize &&
5478          "It is impossible for a switch to have more entries than the max "
5479          "representable value of its input integer type's size.");
5480 
5481   // If the default destination is unreachable, or if the lookup table covers
5482   // all values of the conditional variable, branch directly to the lookup table
5483   // BB. Otherwise, check that the condition is within the case range.
5484   const bool DefaultIsReachable =
5485       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5486   const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
5487   BranchInst *RangeCheckBranch = nullptr;
5488 
5489   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5490     Builder.CreateBr(LookupBB);
5491     // Note: We call removeProdecessor later since we need to be able to get the
5492     // PHI value for the default case in case we're using a bit mask.
5493   } else {
5494     Value *Cmp = Builder.CreateICmpULT(
5495         TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5496     RangeCheckBranch =
5497         Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
5498   }
5499 
5500   // Populate the BB that does the lookups.
5501   Builder.SetInsertPoint(LookupBB);
5502 
5503   if (NeedMask) {
5504     // Before doing the lookup, we do the hole check. The LookupBB is therefore
5505     // re-purposed to do the hole check, and we create a new LookupBB.
5506     BasicBlock *MaskBB = LookupBB;
5507     MaskBB->setName("switch.hole_check");
5508     LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5509                                   CommonDest->getParent(), CommonDest);
5510 
5511     // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
5512     // unnecessary illegal types.
5513     uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5514     APInt MaskInt(TableSizePowOf2, 0);
5515     APInt One(TableSizePowOf2, 1);
5516     // Build bitmask; fill in a 1 bit for every case.
5517     const ResultListTy &ResultList = ResultLists[PHIs[0]];
5518     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
5519       uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5520                          .getLimitedValue();
5521       MaskInt |= One << Idx;
5522     }
5523     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5524 
5525     // Get the TableIndex'th bit of the bitmask.
5526     // If this bit is 0 (meaning hole) jump to the default destination,
5527     // else continue with table lookup.
5528     IntegerType *MapTy = TableMask->getType();
5529     Value *MaskIndex =
5530         Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5531     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5532     Value *LoBit = Builder.CreateTrunc(
5533         Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
5534     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5535 
5536     Builder.SetInsertPoint(LookupBB);
5537     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
5538   }
5539 
5540   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5541     // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
5542     // do not delete PHINodes here.
5543     SI->getDefaultDest()->removePredecessor(SI->getParent(),
5544                                             /*KeepOneInputPHIs=*/true);
5545   }
5546 
5547   bool ReturnedEarly = false;
5548   for (PHINode *PHI : PHIs) {
5549     const ResultListTy &ResultList = ResultLists[PHI];
5550 
5551     // If using a bitmask, use any value to fill the lookup table holes.
5552     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
5553     StringRef FuncName = Fn->getName();
5554     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5555                             FuncName);
5556 
5557     Value *Result = Table.BuildLookup(TableIndex, Builder);
5558 
5559     // If the result is used to return immediately from the function, we want to
5560     // do that right here.
5561     if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5562         PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
5563       Builder.CreateRet(Result);
5564       ReturnedEarly = true;
5565       break;
5566     }
5567 
5568     // Do a small peephole optimization: re-use the switch table compare if
5569     // possible.
5570     if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5571       BasicBlock *PhiBlock = PHI->getParent();
5572       // Search for compare instructions which use the phi.
5573       for (auto *User : PHI->users()) {
5574         reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5575       }
5576     }
5577 
5578     PHI->addIncoming(Result, LookupBB);
5579   }
5580 
5581   if (!ReturnedEarly)
5582     Builder.CreateBr(CommonDest);
5583 
5584   // Remove the switch.
5585   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5586     BasicBlock *Succ = SI->getSuccessor(i);
5587 
5588     if (Succ == SI->getDefaultDest())
5589       continue;
5590     Succ->removePredecessor(SI->getParent());
5591   }
5592   SI->eraseFromParent();
5593 
5594   ++NumLookupTables;
5595   if (NeedMask)
5596     ++NumLookupTablesHoles;
5597   return true;
5598 }
5599 
5600 static bool isSwitchDense(ArrayRef<int64_t> Values) {
5601   // See also SelectionDAGBuilder::isDense(), which this function was based on.
5602   uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5603   uint64_t Range = Diff + 1;
5604   uint64_t NumCases = Values.size();
5605   // 40% is the default density for building a jump table in optsize/minsize mode.
5606   uint64_t MinDensity = 40;
5607 
5608   return NumCases * 100 >= Range * MinDensity;
5609 }
5610 
5611 /// Try to transform a switch that has "holes" in it to a contiguous sequence
5612 /// of cases.
5613 ///
5614 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5615 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5616 ///
5617 /// This converts a sparse switch into a dense switch which allows better
5618 /// lowering and could also allow transforming into a lookup table.
5619 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5620                               const DataLayout &DL,
5621                               const TargetTransformInfo &TTI) {
5622   auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5623   if (CondTy->getIntegerBitWidth() > 64 ||
5624       !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5625     return false;
5626   // Only bother with this optimization if there are more than 3 switch cases;
5627   // SDAG will only bother creating jump tables for 4 or more cases.
5628   if (SI->getNumCases() < 4)
5629     return false;
5630 
5631   // This transform is agnostic to the signedness of the input or case values. We
5632   // can treat the case values as signed or unsigned. We can optimize more common
5633   // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5634   // as signed.
5635   SmallVector<int64_t,4> Values;
5636   for (auto &C : SI->cases())
5637     Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5638   llvm::sort(Values);
5639 
5640   // If the switch is already dense, there's nothing useful to do here.
5641   if (isSwitchDense(Values))
5642     return false;
5643 
5644   // First, transform the values such that they start at zero and ascend.
5645   int64_t Base = Values[0];
5646   for (auto &V : Values)
5647     V -= (uint64_t)(Base);
5648 
5649   // Now we have signed numbers that have been shifted so that, given enough
5650   // precision, there are no negative values. Since the rest of the transform
5651   // is bitwise only, we switch now to an unsigned representation.
5652 
5653   // This transform can be done speculatively because it is so cheap - it
5654   // results in a single rotate operation being inserted.
5655   // FIXME: It's possible that optimizing a switch on powers of two might also
5656   // be beneficial - flag values are often powers of two and we could use a CLZ
5657   // as the key function.
5658 
5659   // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than
5660   // one element and LLVM disallows duplicate cases, Shift is guaranteed to be
5661   // less than 64.
5662   unsigned Shift = 64;
5663   for (auto &V : Values)
5664     Shift = std::min(Shift, countTrailingZeros((uint64_t)V));
5665   assert(Shift < 64);
5666   if (Shift > 0)
5667     for (auto &V : Values)
5668       V = (int64_t)((uint64_t)V >> Shift);
5669 
5670   if (!isSwitchDense(Values))
5671     // Transform didn't create a dense switch.
5672     return false;
5673 
5674   // The obvious transform is to shift the switch condition right and emit a
5675   // check that the condition actually cleanly divided by GCD, i.e.
5676   //   C & (1 << Shift - 1) == 0
5677   // inserting a new CFG edge to handle the case where it didn't divide cleanly.
5678   //
5679   // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
5680   // shift and puts the shifted-off bits in the uppermost bits. If any of these
5681   // are nonzero then the switch condition will be very large and will hit the
5682   // default case.
5683 
5684   auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
5685   Builder.SetInsertPoint(SI);
5686   auto *ShiftC = ConstantInt::get(Ty, Shift);
5687   auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
5688   auto *LShr = Builder.CreateLShr(Sub, ShiftC);
5689   auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
5690   auto *Rot = Builder.CreateOr(LShr, Shl);
5691   SI->replaceUsesOfWith(SI->getCondition(), Rot);
5692 
5693   for (auto Case : SI->cases()) {
5694     auto *Orig = Case.getCaseValue();
5695     auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
5696     Case.setValue(
5697         cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
5698   }
5699   return true;
5700 }
5701 
5702 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
5703   BasicBlock *BB = SI->getParent();
5704 
5705   if (isValueEqualityComparison(SI)) {
5706     // If we only have one predecessor, and if it is a branch on this value,
5707     // see if that predecessor totally determines the outcome of this switch.
5708     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5709       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
5710         return requestResimplify();
5711 
5712     Value *Cond = SI->getCondition();
5713     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
5714       if (SimplifySwitchOnSelect(SI, Select))
5715         return requestResimplify();
5716 
5717     // If the block only contains the switch, see if we can fold the block
5718     // away into any preds.
5719     if (SI == &*BB->instructionsWithoutDebug().begin())
5720       if (FoldValueComparisonIntoPredecessors(SI, Builder))
5721         return requestResimplify();
5722   }
5723 
5724   // Try to transform the switch into an icmp and a branch.
5725   if (TurnSwitchRangeIntoICmp(SI, Builder))
5726     return requestResimplify();
5727 
5728   // Remove unreachable cases.
5729   if (eliminateDeadSwitchCases(SI, Options.AC, DL))
5730     return requestResimplify();
5731 
5732   if (switchToSelect(SI, Builder, DL, TTI))
5733     return requestResimplify();
5734 
5735   if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
5736     return requestResimplify();
5737 
5738   // The conversion from switch to lookup tables results in difficult-to-analyze
5739   // code and makes pruning branches much harder. This is a problem if the
5740   // switch expression itself can still be restricted as a result of inlining or
5741   // CVP. Therefore, only apply this transformation during late stages of the
5742   // optimisation pipeline.
5743   if (Options.ConvertSwitchToLookupTable &&
5744       SwitchToLookupTable(SI, Builder, DL, TTI))
5745     return requestResimplify();
5746 
5747   if (ReduceSwitchRange(SI, Builder, DL, TTI))
5748     return requestResimplify();
5749 
5750   return false;
5751 }
5752 
5753 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
5754   BasicBlock *BB = IBI->getParent();
5755   bool Changed = false;
5756 
5757   // Eliminate redundant destinations.
5758   SmallPtrSet<Value *, 8> Succs;
5759   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
5760     BasicBlock *Dest = IBI->getDestination(i);
5761     if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
5762       Dest->removePredecessor(BB);
5763       IBI->removeDestination(i);
5764       --i;
5765       --e;
5766       Changed = true;
5767     }
5768   }
5769 
5770   if (IBI->getNumDestinations() == 0) {
5771     // If the indirectbr has no successors, change it to unreachable.
5772     new UnreachableInst(IBI->getContext(), IBI);
5773     EraseTerminatorAndDCECond(IBI);
5774     return true;
5775   }
5776 
5777   if (IBI->getNumDestinations() == 1) {
5778     // If the indirectbr has one successor, change it to a direct branch.
5779     BranchInst::Create(IBI->getDestination(0), IBI);
5780     EraseTerminatorAndDCECond(IBI);
5781     return true;
5782   }
5783 
5784   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
5785     if (SimplifyIndirectBrOnSelect(IBI, SI))
5786       return requestResimplify();
5787   }
5788   return Changed;
5789 }
5790 
5791 /// Given an block with only a single landing pad and a unconditional branch
5792 /// try to find another basic block which this one can be merged with.  This
5793 /// handles cases where we have multiple invokes with unique landing pads, but
5794 /// a shared handler.
5795 ///
5796 /// We specifically choose to not worry about merging non-empty blocks
5797 /// here.  That is a PRE/scheduling problem and is best solved elsewhere.  In
5798 /// practice, the optimizer produces empty landing pad blocks quite frequently
5799 /// when dealing with exception dense code.  (see: instcombine, gvn, if-else
5800 /// sinking in this file)
5801 ///
5802 /// This is primarily a code size optimization.  We need to avoid performing
5803 /// any transform which might inhibit optimization (such as our ability to
5804 /// specialize a particular handler via tail commoning).  We do this by not
5805 /// merging any blocks which require us to introduce a phi.  Since the same
5806 /// values are flowing through both blocks, we don't lose any ability to
5807 /// specialize.  If anything, we make such specialization more likely.
5808 ///
5809 /// TODO - This transformation could remove entries from a phi in the target
5810 /// block when the inputs in the phi are the same for the two blocks being
5811 /// merged.  In some cases, this could result in removal of the PHI entirely.
5812 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5813                                  BasicBlock *BB) {
5814   auto Succ = BB->getUniqueSuccessor();
5815   assert(Succ);
5816   // If there's a phi in the successor block, we'd likely have to introduce
5817   // a phi into the merged landing pad block.
5818   if (isa<PHINode>(*Succ->begin()))
5819     return false;
5820 
5821   for (BasicBlock *OtherPred : predecessors(Succ)) {
5822     if (BB == OtherPred)
5823       continue;
5824     BasicBlock::iterator I = OtherPred->begin();
5825     LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5826     if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5827       continue;
5828     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5829       ;
5830     BranchInst *BI2 = dyn_cast<BranchInst>(I);
5831     if (!BI2 || !BI2->isIdenticalTo(BI))
5832       continue;
5833 
5834     // We've found an identical block.  Update our predecessors to take that
5835     // path instead and make ourselves dead.
5836     SmallPtrSet<BasicBlock *, 16> Preds;
5837     Preds.insert(pred_begin(BB), pred_end(BB));
5838     for (BasicBlock *Pred : Preds) {
5839       InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
5840       assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
5841              "unexpected successor");
5842       II->setUnwindDest(OtherPred);
5843     }
5844 
5845     // The debug info in OtherPred doesn't cover the merged control flow that
5846     // used to go through BB.  We need to delete it or update it.
5847     for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
5848       Instruction &Inst = *I;
5849       I++;
5850       if (isa<DbgInfoIntrinsic>(Inst))
5851         Inst.eraseFromParent();
5852     }
5853 
5854     SmallPtrSet<BasicBlock *, 16> Succs;
5855     Succs.insert(succ_begin(BB), succ_end(BB));
5856     for (BasicBlock *Succ : Succs) {
5857       Succ->removePredecessor(BB);
5858     }
5859 
5860     IRBuilder<> Builder(BI);
5861     Builder.CreateUnreachable();
5862     BI->eraseFromParent();
5863     return true;
5864   }
5865   return false;
5866 }
5867 
5868 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) {
5869   return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder)
5870                                    : simplifyCondBranch(Branch, Builder);
5871 }
5872 
5873 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI,
5874                                           IRBuilder<> &Builder) {
5875   BasicBlock *BB = BI->getParent();
5876   BasicBlock *Succ = BI->getSuccessor(0);
5877 
5878   // If the Terminator is the only non-phi instruction, simplify the block.
5879   // If LoopHeader is provided, check if the block or its successor is a loop
5880   // header. (This is for early invocations before loop simplify and
5881   // vectorization to keep canonical loop forms for nested loops. These blocks
5882   // can be eliminated when the pass is invoked later in the back-end.)
5883   // Note that if BB has only one predecessor then we do not introduce new
5884   // backedge, so we can eliminate BB.
5885   bool NeedCanonicalLoop =
5886       Options.NeedCanonicalLoop &&
5887       (LoopHeaders && BB->hasNPredecessorsOrMore(2) &&
5888        (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
5889   BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
5890   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
5891       !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB))
5892     return true;
5893 
5894   // If the only instruction in the block is a seteq/setne comparison against a
5895   // constant, try to simplify the block.
5896   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5897     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5898       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5899         ;
5900       if (I->isTerminator() &&
5901           tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
5902         return true;
5903     }
5904 
5905   // See if we can merge an empty landing pad block with another which is
5906   // equivalent.
5907   if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
5908     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5909       ;
5910     if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
5911       return true;
5912   }
5913 
5914   // If this basic block is ONLY a compare and a branch, and if a predecessor
5915   // branches to us and our successor, fold the comparison into the
5916   // predecessor and use logical operations to update the incoming value
5917   // for PHI nodes in common successor.
5918   if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold))
5919     return requestResimplify();
5920   return false;
5921 }
5922 
5923 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5924   BasicBlock *PredPred = nullptr;
5925   for (auto *P : predecessors(BB)) {
5926     BasicBlock *PPred = P->getSinglePredecessor();
5927     if (!PPred || (PredPred && PredPred != PPred))
5928       return nullptr;
5929     PredPred = PPred;
5930   }
5931   return PredPred;
5932 }
5933 
5934 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
5935   BasicBlock *BB = BI->getParent();
5936   const Function *Fn = BB->getParent();
5937   if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
5938     return false;
5939 
5940   // Conditional branch
5941   if (isValueEqualityComparison(BI)) {
5942     // If we only have one predecessor, and if it is a branch on this value,
5943     // see if that predecessor totally determines the outcome of this
5944     // switch.
5945     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5946       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
5947         return requestResimplify();
5948 
5949     // This block must be empty, except for the setcond inst, if it exists.
5950     // Ignore dbg intrinsics.
5951     auto I = BB->instructionsWithoutDebug().begin();
5952     if (&*I == BI) {
5953       if (FoldValueComparisonIntoPredecessors(BI, Builder))
5954         return requestResimplify();
5955     } else if (&*I == cast<Instruction>(BI->getCondition())) {
5956       ++I;
5957       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
5958         return requestResimplify();
5959     }
5960   }
5961 
5962   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
5963   if (SimplifyBranchOnICmpChain(BI, Builder, DL))
5964     return true;
5965 
5966   // If this basic block has dominating predecessor blocks and the dominating
5967   // blocks' conditions imply BI's condition, we know the direction of BI.
5968   Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
5969   if (Imp) {
5970     // Turn this into a branch on constant.
5971     auto *OldCond = BI->getCondition();
5972     ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
5973                              : ConstantInt::getFalse(BB->getContext());
5974     BI->setCondition(TorF);
5975     RecursivelyDeleteTriviallyDeadInstructions(OldCond);
5976     return requestResimplify();
5977   }
5978 
5979   // If this basic block is ONLY a compare and a branch, and if a predecessor
5980   // branches to us and one of our successors, fold the comparison into the
5981   // predecessor and use logical operations to pick the right destination.
5982   if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold))
5983     return requestResimplify();
5984 
5985   // We have a conditional branch to two blocks that are only reachable
5986   // from BI.  We know that the condbr dominates the two blocks, so see if
5987   // there is any identical code in the "then" and "else" blocks.  If so, we
5988   // can hoist it up to the branching block.
5989   if (BI->getSuccessor(0)->getSinglePredecessor()) {
5990     if (BI->getSuccessor(1)->getSinglePredecessor()) {
5991       if (HoistThenElseCodeToIf(BI, TTI))
5992         return requestResimplify();
5993     } else {
5994       // If Successor #1 has multiple preds, we may be able to conditionally
5995       // execute Successor #0 if it branches to Successor #1.
5996       Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
5997       if (Succ0TI->getNumSuccessors() == 1 &&
5998           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
5999         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
6000           return requestResimplify();
6001     }
6002   } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
6003     // If Successor #0 has multiple preds, we may be able to conditionally
6004     // execute Successor #1 if it branches to Successor #0.
6005     Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
6006     if (Succ1TI->getNumSuccessors() == 1 &&
6007         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
6008       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
6009         return requestResimplify();
6010   }
6011 
6012   // If this is a branch on a phi node in the current block, thread control
6013   // through this block if any PHI node entries are constants.
6014   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
6015     if (PN->getParent() == BI->getParent())
6016       if (FoldCondBranchOnPHI(BI, DL, Options.AC))
6017         return requestResimplify();
6018 
6019   // Scan predecessor blocks for conditional branches.
6020   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
6021     if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
6022       if (PBI != BI && PBI->isConditional())
6023         if (SimplifyCondBranchToCondBranch(PBI, BI, DL, TTI))
6024           return requestResimplify();
6025 
6026   // Look for diamond patterns.
6027   if (MergeCondStores)
6028     if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
6029       if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
6030         if (PBI != BI && PBI->isConditional())
6031           if (mergeConditionalStores(PBI, BI, DL, TTI))
6032             return requestResimplify();
6033 
6034   return false;
6035 }
6036 
6037 /// Check if passing a value to an instruction will cause undefined behavior.
6038 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
6039   Constant *C = dyn_cast<Constant>(V);
6040   if (!C)
6041     return false;
6042 
6043   if (I->use_empty())
6044     return false;
6045 
6046   if (C->isNullValue() || isa<UndefValue>(C)) {
6047     // Only look at the first use, avoid hurting compile time with long uselists
6048     User *Use = *I->user_begin();
6049 
6050     // Now make sure that there are no instructions in between that can alter
6051     // control flow (eg. calls)
6052     for (BasicBlock::iterator
6053              i = ++BasicBlock::iterator(I),
6054              UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
6055          i != UI; ++i)
6056       if (i == I->getParent()->end() || i->mayHaveSideEffects())
6057         return false;
6058 
6059     // Look through GEPs. A load from a GEP derived from NULL is still undefined
6060     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
6061       if (GEP->getPointerOperand() == I)
6062         return passingValueIsAlwaysUndefined(V, GEP);
6063 
6064     // Look through bitcasts.
6065     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
6066       return passingValueIsAlwaysUndefined(V, BC);
6067 
6068     // Load from null is undefined.
6069     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
6070       if (!LI->isVolatile())
6071         return !NullPointerIsDefined(LI->getFunction(),
6072                                      LI->getPointerAddressSpace());
6073 
6074     // Store to null is undefined.
6075     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
6076       if (!SI->isVolatile())
6077         return (!NullPointerIsDefined(SI->getFunction(),
6078                                       SI->getPointerAddressSpace())) &&
6079                SI->getPointerOperand() == I;
6080 
6081     // A call to null is undefined.
6082     if (auto CS = CallSite(Use))
6083       return !NullPointerIsDefined(CS->getFunction()) &&
6084              CS.getCalledValue() == I;
6085   }
6086   return false;
6087 }
6088 
6089 /// If BB has an incoming value that will always trigger undefined behavior
6090 /// (eg. null pointer dereference), remove the branch leading here.
6091 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
6092   for (PHINode &PHI : BB->phis())
6093     for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
6094       if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
6095         Instruction *T = PHI.getIncomingBlock(i)->getTerminator();
6096         IRBuilder<> Builder(T);
6097         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
6098           BB->removePredecessor(PHI.getIncomingBlock(i));
6099           // Turn uncoditional branches into unreachables and remove the dead
6100           // destination from conditional branches.
6101           if (BI->isUnconditional())
6102             Builder.CreateUnreachable();
6103           else
6104             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
6105                                                        : BI->getSuccessor(0));
6106           BI->eraseFromParent();
6107           return true;
6108         }
6109         // TODO: SwitchInst.
6110       }
6111 
6112   return false;
6113 }
6114 
6115 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
6116   bool Changed = false;
6117 
6118   assert(BB && BB->getParent() && "Block not embedded in function!");
6119   assert(BB->getTerminator() && "Degenerate basic block encountered!");
6120 
6121   // Remove basic blocks that have no predecessors (except the entry block)...
6122   // or that just have themself as a predecessor.  These are unreachable.
6123   if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
6124       BB->getSinglePredecessor() == BB) {
6125     LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
6126     DeleteDeadBlock(BB);
6127     return true;
6128   }
6129 
6130   // Check to see if we can constant propagate this terminator instruction
6131   // away...
6132   Changed |= ConstantFoldTerminator(BB, true);
6133 
6134   // Check for and eliminate duplicate PHI nodes in this block.
6135   Changed |= EliminateDuplicatePHINodes(BB);
6136 
6137   // Check for and remove branches that will always cause undefined behavior.
6138   Changed |= removeUndefIntroducingPredecessor(BB);
6139 
6140   // Merge basic blocks into their predecessor if there is only one distinct
6141   // pred, and if there is only one distinct successor of the predecessor, and
6142   // if there are no PHI nodes.
6143   if (MergeBlockIntoPredecessor(BB))
6144     return true;
6145 
6146   if (SinkCommon && Options.SinkCommonInsts)
6147     Changed |= SinkCommonCodeFromPredecessors(BB);
6148 
6149   IRBuilder<> Builder(BB);
6150 
6151   // If there is a trivial two-entry PHI node in this basic block, and we can
6152   // eliminate it, do so now.
6153   if (auto *PN = dyn_cast<PHINode>(BB->begin()))
6154     if (PN->getNumIncomingValues() == 2)
6155       Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
6156 
6157   Instruction *Terminator = BB->getTerminator();
6158   Builder.SetInsertPoint(Terminator);
6159   switch (Terminator->getOpcode()) {
6160   case Instruction::Br:
6161     Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder);
6162     break;
6163   case Instruction::Ret:
6164     Changed |= simplifyReturn(cast<ReturnInst>(Terminator), Builder);
6165     break;
6166   case Instruction::Resume:
6167     Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
6168     break;
6169   case Instruction::CleanupRet:
6170     Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
6171     break;
6172   case Instruction::Switch:
6173     Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
6174     break;
6175   case Instruction::Unreachable:
6176     Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
6177     break;
6178   case Instruction::IndirectBr:
6179     Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
6180     break;
6181   }
6182 
6183   return Changed;
6184 }
6185 
6186 bool SimplifyCFGOpt::run(BasicBlock *BB) {
6187   bool Changed = false;
6188 
6189   // Repeated simplify BB as long as resimplification is requested.
6190   do {
6191     Resimplify = false;
6192 
6193     // Perform one round of simplifcation. Resimplify flag will be set if
6194     // another iteration is requested.
6195     Changed |= simplifyOnce(BB);
6196   } while (Resimplify);
6197 
6198   return Changed;
6199 }
6200 
6201 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
6202                        const SimplifyCFGOptions &Options,
6203                        SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
6204   return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders,
6205                         Options)
6206       .run(BB);
6207 }
6208