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