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