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