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 (Instruction *Terminator = BB->getTerminator()) {
1588           if (Instruction *LastNonTerminator = Terminator->getPrevNode()) {
1589             Insts.push_back(LastNonTerminator);
1590             continue;
1591           }
1592         }
1593         // Block wasn't big enough.
1594         Fail = true;
1595         return;
1596       }
1597     }
1598 
1599     bool isValid() const {
1600       return !Fail;
1601     }
1602 
1603     void operator -- () {
1604       if (Fail)
1605         return;
1606       for (auto *&Inst : Insts) {
1607         Inst = Inst->getPrevNode();
1608         // Already at beginning of block.
1609         if (!Inst) {
1610           Fail = true;
1611           return;
1612         }
1613       }
1614     }
1615 
1616     ArrayRef<Instruction*> operator * () const {
1617       return Insts;
1618     }
1619   };
1620 }
1621 
1622 /// Given an unconditional branch that goes to BBEnd,
1623 /// check whether BBEnd has only two predecessors and the other predecessor
1624 /// ends with an unconditional branch. If it is true, sink any common code
1625 /// in the two predecessors to BBEnd.
1626 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1627   assert(BI1->isUnconditional());
1628   BasicBlock *BBEnd = BI1->getSuccessor(0);
1629 
1630   // We support two situations:
1631   //   (1) all incoming arcs are unconditional
1632   //   (2) one incoming arc is conditional
1633   //
1634   // (2) is very common in switch defaults and
1635   // else-if patterns;
1636   //
1637   //   if (a) f(1);
1638   //   else if (b) f(2);
1639   //
1640   // produces:
1641   //
1642   //       [if]
1643   //      /    \
1644   //    [f(1)] [if]
1645   //      |     | \
1646   //      |     |  \
1647   //      |  [f(2)]|
1648   //       \    | /
1649   //        [ end ]
1650   //
1651   // [end] has two unconditional predecessor arcs and one conditional. The
1652   // conditional refers to the implicit empty 'else' arc. This conditional
1653   // arc can also be caused by an empty default block in a switch.
1654   //
1655   // In this case, we attempt to sink code from all *unconditional* arcs.
1656   // If we can sink instructions from these arcs (determined during the scan
1657   // phase below) we insert a common successor for all unconditional arcs and
1658   // connect that to [end], to enable sinking:
1659   //
1660   //       [if]
1661   //      /    \
1662   //    [x(1)] [if]
1663   //      |     | \
1664   //      |     |  \
1665   //      |  [x(2)] |
1666   //       \   /    |
1667   //   [sink.split] |
1668   //         \     /
1669   //         [ end ]
1670   //
1671   SmallVector<BasicBlock*,4> UnconditionalPreds;
1672   Instruction *Cond = nullptr;
1673   for (auto *B : predecessors(BBEnd)) {
1674     auto *T = B->getTerminator();
1675     if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
1676       UnconditionalPreds.push_back(B);
1677     else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
1678       Cond = T;
1679     else
1680       return false;
1681   }
1682   if (UnconditionalPreds.size() < 2)
1683     return false;
1684 
1685   bool Changed = false;
1686   // We take a two-step approach to tail sinking. First we scan from the end of
1687   // each block upwards in lockstep. If the n'th instruction from the end of each
1688   // block can be sunk, those instructions are added to ValuesToSink and we
1689   // carry on. If we can sink an instruction but need to PHI-merge some operands
1690   // (because they're not identical in each instruction) we add these to
1691   // PHIOperands.
1692   unsigned ScanIdx = 0;
1693   SmallPtrSet<Value*,4> InstructionsToSink;
1694   DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
1695   LockstepReverseIterator LRI(UnconditionalPreds);
1696   while (LRI.isValid() &&
1697          canSinkInstructions(*LRI, PHIOperands)) {
1698     DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0] << "\n");
1699     InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
1700     ++ScanIdx;
1701     --LRI;
1702   }
1703 
1704   auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
1705     unsigned NumPHIdValues = 0;
1706     for (auto *I : *LRI)
1707       for (auto *V : PHIOperands[I])
1708         if (InstructionsToSink.count(V) == 0)
1709           ++NumPHIdValues;
1710     DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
1711     unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
1712     if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
1713         NumPHIInsts++;
1714 
1715     return NumPHIInsts <= 1;
1716   };
1717 
1718   if (ScanIdx > 0 && Cond) {
1719     // Check if we would actually sink anything first! This mutates the CFG and
1720     // adds an extra block. The goal in doing this is to allow instructions that
1721     // couldn't be sunk before to be sunk - obviously, speculatable instructions
1722     // (such as trunc, add) can be sunk and predicated already. So we check that
1723     // we're going to sink at least one non-speculatable instruction.
1724     LRI.reset();
1725     unsigned Idx = 0;
1726     bool Profitable = false;
1727     while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
1728       if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
1729         Profitable = true;
1730         break;
1731       }
1732       --LRI;
1733       ++Idx;
1734     }
1735     if (!Profitable)
1736       return false;
1737 
1738     DEBUG(dbgs() << "SINK: Splitting edge\n");
1739     // We have a conditional edge and we're going to sink some instructions.
1740     // Insert a new block postdominating all blocks we're going to sink from.
1741     if (!SplitBlockPredecessors(BI1->getSuccessor(0), UnconditionalPreds,
1742                                 ".sink.split"))
1743       // Edges couldn't be split.
1744       return false;
1745     Changed = true;
1746   }
1747 
1748   // Now that we've analyzed all potential sinking candidates, perform the
1749   // actual sink. We iteratively sink the last non-terminator of the source
1750   // blocks into their common successor unless doing so would require too
1751   // many PHI instructions to be generated (currently only one PHI is allowed
1752   // per sunk instruction).
1753   //
1754   // We can use InstructionsToSink to discount values needing PHI-merging that will
1755   // actually be sunk in a later iteration. This allows us to be more
1756   // aggressive in what we sink. This does allow a false positive where we
1757   // sink presuming a later value will also be sunk, but stop half way through
1758   // and never actually sink it which means we produce more PHIs than intended.
1759   // This is unlikely in practice though.
1760   for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1761     DEBUG(dbgs() << "SINK: Sink: "
1762                  << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
1763                  << "\n");
1764 
1765     // Because we've sunk every instruction in turn, the current instruction to
1766     // sink is always at index 0.
1767     LRI.reset();
1768     if (!ProfitableToSinkInstruction(LRI)) {
1769       // Too many PHIs would be created.
1770       DEBUG(dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
1771       break;
1772     }
1773 
1774     if (!sinkLastInstruction(UnconditionalPreds))
1775       return Changed;
1776     NumSinkCommons++;
1777     Changed = true;
1778   }
1779   return Changed;
1780 }
1781 
1782 /// \brief Determine if we can hoist sink a sole store instruction out of a
1783 /// conditional block.
1784 ///
1785 /// We are looking for code like the following:
1786 ///   BrBB:
1787 ///     store i32 %add, i32* %arrayidx2
1788 ///     ... // No other stores or function calls (we could be calling a memory
1789 ///     ... // function).
1790 ///     %cmp = icmp ult %x, %y
1791 ///     br i1 %cmp, label %EndBB, label %ThenBB
1792 ///   ThenBB:
1793 ///     store i32 %add5, i32* %arrayidx2
1794 ///     br label EndBB
1795 ///   EndBB:
1796 ///     ...
1797 ///   We are going to transform this into:
1798 ///   BrBB:
1799 ///     store i32 %add, i32* %arrayidx2
1800 ///     ... //
1801 ///     %cmp = icmp ult %x, %y
1802 ///     %add.add5 = select i1 %cmp, i32 %add, %add5
1803 ///     store i32 %add.add5, i32* %arrayidx2
1804 ///     ...
1805 ///
1806 /// \return The pointer to the value of the previous store if the store can be
1807 ///         hoisted into the predecessor block. 0 otherwise.
1808 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1809                                      BasicBlock *StoreBB, BasicBlock *EndBB) {
1810   StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1811   if (!StoreToHoist)
1812     return nullptr;
1813 
1814   // Volatile or atomic.
1815   if (!StoreToHoist->isSimple())
1816     return nullptr;
1817 
1818   Value *StorePtr = StoreToHoist->getPointerOperand();
1819 
1820   // Look for a store to the same pointer in BrBB.
1821   unsigned MaxNumInstToLookAt = 9;
1822   for (Instruction &CurI : reverse(*BrBB)) {
1823     if (!MaxNumInstToLookAt)
1824       break;
1825     // Skip debug info.
1826     if (isa<DbgInfoIntrinsic>(CurI))
1827       continue;
1828     --MaxNumInstToLookAt;
1829 
1830     // Could be calling an instruction that affects memory like free().
1831     if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
1832       return nullptr;
1833 
1834     if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
1835       // Found the previous store make sure it stores to the same location.
1836       if (SI->getPointerOperand() == StorePtr)
1837         // Found the previous store, return its value operand.
1838         return SI->getValueOperand();
1839       return nullptr; // Unknown store.
1840     }
1841   }
1842 
1843   return nullptr;
1844 }
1845 
1846 /// \brief Speculate a conditional basic block flattening the CFG.
1847 ///
1848 /// Note that this is a very risky transform currently. Speculating
1849 /// instructions like this is most often not desirable. Instead, there is an MI
1850 /// pass which can do it with full awareness of the resource constraints.
1851 /// However, some cases are "obvious" and we should do directly. An example of
1852 /// this is speculating a single, reasonably cheap instruction.
1853 ///
1854 /// There is only one distinct advantage to flattening the CFG at the IR level:
1855 /// it makes very common but simplistic optimizations such as are common in
1856 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1857 /// modeling their effects with easier to reason about SSA value graphs.
1858 ///
1859 ///
1860 /// An illustration of this transform is turning this IR:
1861 /// \code
1862 ///   BB:
1863 ///     %cmp = icmp ult %x, %y
1864 ///     br i1 %cmp, label %EndBB, label %ThenBB
1865 ///   ThenBB:
1866 ///     %sub = sub %x, %y
1867 ///     br label BB2
1868 ///   EndBB:
1869 ///     %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1870 ///     ...
1871 /// \endcode
1872 ///
1873 /// Into this IR:
1874 /// \code
1875 ///   BB:
1876 ///     %cmp = icmp ult %x, %y
1877 ///     %sub = sub %x, %y
1878 ///     %cond = select i1 %cmp, 0, %sub
1879 ///     ...
1880 /// \endcode
1881 ///
1882 /// \returns true if the conditional block is removed.
1883 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1884                                    const TargetTransformInfo &TTI) {
1885   // Be conservative for now. FP select instruction can often be expensive.
1886   Value *BrCond = BI->getCondition();
1887   if (isa<FCmpInst>(BrCond))
1888     return false;
1889 
1890   BasicBlock *BB = BI->getParent();
1891   BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1892 
1893   // If ThenBB is actually on the false edge of the conditional branch, remember
1894   // to swap the select operands later.
1895   bool Invert = false;
1896   if (ThenBB != BI->getSuccessor(0)) {
1897     assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1898     Invert = true;
1899   }
1900   assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1901 
1902   // Keep a count of how many times instructions are used within CondBB when
1903   // they are candidates for sinking into CondBB. Specifically:
1904   // - They are defined in BB, and
1905   // - They have no side effects, and
1906   // - All of their uses are in CondBB.
1907   SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1908 
1909   unsigned SpeculationCost = 0;
1910   Value *SpeculatedStoreValue = nullptr;
1911   StoreInst *SpeculatedStore = nullptr;
1912   for (BasicBlock::iterator BBI = ThenBB->begin(),
1913                             BBE = std::prev(ThenBB->end());
1914        BBI != BBE; ++BBI) {
1915     Instruction *I = &*BBI;
1916     // Skip debug info.
1917     if (isa<DbgInfoIntrinsic>(I))
1918       continue;
1919 
1920     // Only speculatively execute a single instruction (not counting the
1921     // terminator) for now.
1922     ++SpeculationCost;
1923     if (SpeculationCost > 1)
1924       return false;
1925 
1926     // Don't hoist the instruction if it's unsafe or expensive.
1927     if (!isSafeToSpeculativelyExecute(I) &&
1928         !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1929                                   I, BB, ThenBB, EndBB))))
1930       return false;
1931     if (!SpeculatedStoreValue &&
1932         ComputeSpeculationCost(I, TTI) >
1933             PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
1934       return false;
1935 
1936     // Store the store speculation candidate.
1937     if (SpeculatedStoreValue)
1938       SpeculatedStore = cast<StoreInst>(I);
1939 
1940     // Do not hoist the instruction if any of its operands are defined but not
1941     // used in BB. The transformation will prevent the operand from
1942     // being sunk into the use block.
1943     for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
1944       Instruction *OpI = dyn_cast<Instruction>(*i);
1945       if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
1946         continue; // Not a candidate for sinking.
1947 
1948       ++SinkCandidateUseCounts[OpI];
1949     }
1950   }
1951 
1952   // Consider any sink candidates which are only used in CondBB as costs for
1953   // speculation. Note, while we iterate over a DenseMap here, we are summing
1954   // and so iteration order isn't significant.
1955   for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
1956            I = SinkCandidateUseCounts.begin(),
1957            E = SinkCandidateUseCounts.end();
1958        I != E; ++I)
1959     if (I->first->getNumUses() == I->second) {
1960       ++SpeculationCost;
1961       if (SpeculationCost > 1)
1962         return false;
1963     }
1964 
1965   // Check that the PHI nodes can be converted to selects.
1966   bool HaveRewritablePHIs = false;
1967   for (BasicBlock::iterator I = EndBB->begin();
1968        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1969     Value *OrigV = PN->getIncomingValueForBlock(BB);
1970     Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1971 
1972     // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1973     // Skip PHIs which are trivial.
1974     if (ThenV == OrigV)
1975       continue;
1976 
1977     // Don't convert to selects if we could remove undefined behavior instead.
1978     if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1979         passingValueIsAlwaysUndefined(ThenV, PN))
1980       return false;
1981 
1982     HaveRewritablePHIs = true;
1983     ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1984     ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1985     if (!OrigCE && !ThenCE)
1986       continue; // Known safe and cheap.
1987 
1988     if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1989         (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
1990       return false;
1991     unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1992     unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
1993     unsigned MaxCost =
1994         2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
1995     if (OrigCost + ThenCost > MaxCost)
1996       return false;
1997 
1998     // Account for the cost of an unfolded ConstantExpr which could end up
1999     // getting expanded into Instructions.
2000     // FIXME: This doesn't account for how many operations are combined in the
2001     // constant expression.
2002     ++SpeculationCost;
2003     if (SpeculationCost > 1)
2004       return false;
2005   }
2006 
2007   // If there are no PHIs to process, bail early. This helps ensure idempotence
2008   // as well.
2009   if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
2010     return false;
2011 
2012   // If we get here, we can hoist the instruction and if-convert.
2013   DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
2014 
2015   // Insert a select of the value of the speculated store.
2016   if (SpeculatedStoreValue) {
2017     IRBuilder<NoFolder> Builder(BI);
2018     Value *TrueV = SpeculatedStore->getValueOperand();
2019     Value *FalseV = SpeculatedStoreValue;
2020     if (Invert)
2021       std::swap(TrueV, FalseV);
2022     Value *S = Builder.CreateSelect(
2023         BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
2024     SpeculatedStore->setOperand(0, S);
2025   }
2026 
2027   // Metadata can be dependent on the condition we are hoisting above.
2028   // Conservatively strip all metadata on the instruction.
2029   for (auto &I : *ThenBB)
2030     I.dropUnknownNonDebugMetadata();
2031 
2032   // Hoist the instructions.
2033   BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
2034                            ThenBB->begin(), std::prev(ThenBB->end()));
2035 
2036   // Insert selects and rewrite the PHI operands.
2037   IRBuilder<NoFolder> Builder(BI);
2038   for (BasicBlock::iterator I = EndBB->begin();
2039        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2040     unsigned OrigI = PN->getBasicBlockIndex(BB);
2041     unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
2042     Value *OrigV = PN->getIncomingValue(OrigI);
2043     Value *ThenV = PN->getIncomingValue(ThenI);
2044 
2045     // Skip PHIs which are trivial.
2046     if (OrigV == ThenV)
2047       continue;
2048 
2049     // Create a select whose true value is the speculatively executed value and
2050     // false value is the preexisting value. Swap them if the branch
2051     // destinations were inverted.
2052     Value *TrueV = ThenV, *FalseV = OrigV;
2053     if (Invert)
2054       std::swap(TrueV, FalseV);
2055     Value *V = Builder.CreateSelect(
2056         BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
2057     PN->setIncomingValue(OrigI, V);
2058     PN->setIncomingValue(ThenI, V);
2059   }
2060 
2061   ++NumSpeculations;
2062   return true;
2063 }
2064 
2065 /// Return true if we can thread a branch across this block.
2066 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2067   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
2068   unsigned Size = 0;
2069 
2070   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2071     if (isa<DbgInfoIntrinsic>(BBI))
2072       continue;
2073     if (Size > 10)
2074       return false; // Don't clone large BB's.
2075     ++Size;
2076 
2077     // We can only support instructions that do not define values that are
2078     // live outside of the current basic block.
2079     for (User *U : BBI->users()) {
2080       Instruction *UI = cast<Instruction>(U);
2081       if (UI->getParent() != BB || isa<PHINode>(UI))
2082         return false;
2083     }
2084 
2085     // Looks ok, continue checking.
2086   }
2087 
2088   return true;
2089 }
2090 
2091 /// If we have a conditional branch on a PHI node value that is defined in the
2092 /// same block as the branch and if any PHI entries are constants, thread edges
2093 /// corresponding to that entry to be branches to their ultimate destination.
2094 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
2095   BasicBlock *BB = BI->getParent();
2096   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
2097   // NOTE: we currently cannot transform this case if the PHI node is used
2098   // outside of the block.
2099   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
2100     return false;
2101 
2102   // Degenerate case of a single entry PHI.
2103   if (PN->getNumIncomingValues() == 1) {
2104     FoldSingleEntryPHINodes(PN->getParent());
2105     return true;
2106   }
2107 
2108   // Now we know that this block has multiple preds and two succs.
2109   if (!BlockIsSimpleEnoughToThreadThrough(BB))
2110     return false;
2111 
2112   // Can't fold blocks that contain noduplicate or convergent calls.
2113   if (any_of(*BB, [](const Instruction &I) {
2114         const CallInst *CI = dyn_cast<CallInst>(&I);
2115         return CI && (CI->cannotDuplicate() || CI->isConvergent());
2116       }))
2117     return false;
2118 
2119   // Okay, this is a simple enough basic block.  See if any phi values are
2120   // constants.
2121   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2122     ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
2123     if (!CB || !CB->getType()->isIntegerTy(1))
2124       continue;
2125 
2126     // Okay, we now know that all edges from PredBB should be revectored to
2127     // branch to RealDest.
2128     BasicBlock *PredBB = PN->getIncomingBlock(i);
2129     BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
2130 
2131     if (RealDest == BB)
2132       continue; // Skip self loops.
2133     // Skip if the predecessor's terminator is an indirect branch.
2134     if (isa<IndirectBrInst>(PredBB->getTerminator()))
2135       continue;
2136 
2137     // The dest block might have PHI nodes, other predecessors and other
2138     // difficult cases.  Instead of being smart about this, just insert a new
2139     // block that jumps to the destination block, effectively splitting
2140     // the edge we are about to create.
2141     BasicBlock *EdgeBB =
2142         BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
2143                            RealDest->getParent(), RealDest);
2144     BranchInst::Create(RealDest, EdgeBB);
2145 
2146     // Update PHI nodes.
2147     AddPredecessorToBlock(RealDest, EdgeBB, BB);
2148 
2149     // BB may have instructions that are being threaded over.  Clone these
2150     // instructions into EdgeBB.  We know that there will be no uses of the
2151     // cloned instructions outside of EdgeBB.
2152     BasicBlock::iterator InsertPt = EdgeBB->begin();
2153     DenseMap<Value *, Value *> TranslateMap; // Track translated values.
2154     for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2155       if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
2156         TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
2157         continue;
2158       }
2159       // Clone the instruction.
2160       Instruction *N = BBI->clone();
2161       if (BBI->hasName())
2162         N->setName(BBI->getName() + ".c");
2163 
2164       // Update operands due to translation.
2165       for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
2166         DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
2167         if (PI != TranslateMap.end())
2168           *i = PI->second;
2169       }
2170 
2171       // Check for trivial simplification.
2172       if (Value *V = SimplifyInstruction(N, DL)) {
2173         if (!BBI->use_empty())
2174           TranslateMap[&*BBI] = V;
2175         if (!N->mayHaveSideEffects()) {
2176           delete N; // Instruction folded away, don't need actual inst
2177           N = nullptr;
2178         }
2179       } else {
2180         if (!BBI->use_empty())
2181           TranslateMap[&*BBI] = N;
2182       }
2183       // Insert the new instruction into its new home.
2184       if (N)
2185         EdgeBB->getInstList().insert(InsertPt, N);
2186     }
2187 
2188     // Loop over all of the edges from PredBB to BB, changing them to branch
2189     // to EdgeBB instead.
2190     TerminatorInst *PredBBTI = PredBB->getTerminator();
2191     for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
2192       if (PredBBTI->getSuccessor(i) == BB) {
2193         BB->removePredecessor(PredBB);
2194         PredBBTI->setSuccessor(i, EdgeBB);
2195       }
2196 
2197     // Recurse, simplifying any other constants.
2198     return FoldCondBranchOnPHI(BI, DL) | true;
2199   }
2200 
2201   return false;
2202 }
2203 
2204 /// Given a BB that starts with the specified two-entry PHI node,
2205 /// see if we can eliminate it.
2206 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
2207                                 const DataLayout &DL) {
2208   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
2209   // statement", which has a very simple dominance structure.  Basically, we
2210   // are trying to find the condition that is being branched on, which
2211   // subsequently causes this merge to happen.  We really want control
2212   // dependence information for this check, but simplifycfg can't keep it up
2213   // to date, and this catches most of the cases we care about anyway.
2214   BasicBlock *BB = PN->getParent();
2215   BasicBlock *IfTrue, *IfFalse;
2216   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
2217   if (!IfCond ||
2218       // Don't bother if the branch will be constant folded trivially.
2219       isa<ConstantInt>(IfCond))
2220     return false;
2221 
2222   // Okay, we found that we can merge this two-entry phi node into a select.
2223   // Doing so would require us to fold *all* two entry phi nodes in this block.
2224   // At some point this becomes non-profitable (particularly if the target
2225   // doesn't support cmov's).  Only do this transformation if there are two or
2226   // fewer PHI nodes in this block.
2227   unsigned NumPhis = 0;
2228   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
2229     if (NumPhis > 2)
2230       return false;
2231 
2232   // Loop over the PHI's seeing if we can promote them all to select
2233   // instructions.  While we are at it, keep track of the instructions
2234   // that need to be moved to the dominating block.
2235   SmallPtrSet<Instruction *, 4> AggressiveInsts;
2236   unsigned MaxCostVal0 = PHINodeFoldingThreshold,
2237            MaxCostVal1 = PHINodeFoldingThreshold;
2238   MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
2239   MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
2240 
2241   for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
2242     PHINode *PN = cast<PHINode>(II++);
2243     if (Value *V = SimplifyInstruction(PN, DL)) {
2244       PN->replaceAllUsesWith(V);
2245       PN->eraseFromParent();
2246       continue;
2247     }
2248 
2249     if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
2250                              MaxCostVal0, TTI) ||
2251         !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
2252                              MaxCostVal1, TTI))
2253       return false;
2254   }
2255 
2256   // If we folded the first phi, PN dangles at this point.  Refresh it.  If
2257   // we ran out of PHIs then we simplified them all.
2258   PN = dyn_cast<PHINode>(BB->begin());
2259   if (!PN)
2260     return true;
2261 
2262   // Don't fold i1 branches on PHIs which contain binary operators.  These can
2263   // often be turned into switches and other things.
2264   if (PN->getType()->isIntegerTy(1) &&
2265       (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
2266        isa<BinaryOperator>(PN->getIncomingValue(1)) ||
2267        isa<BinaryOperator>(IfCond)))
2268     return false;
2269 
2270   // If all PHI nodes are promotable, check to make sure that all instructions
2271   // in the predecessor blocks can be promoted as well. If not, we won't be able
2272   // to get rid of the control flow, so it's not worth promoting to select
2273   // instructions.
2274   BasicBlock *DomBlock = nullptr;
2275   BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
2276   BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
2277   if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
2278     IfBlock1 = nullptr;
2279   } else {
2280     DomBlock = *pred_begin(IfBlock1);
2281     for (BasicBlock::iterator I = IfBlock1->begin(); !isa<TerminatorInst>(I);
2282          ++I)
2283       if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
2284         // This is not an aggressive instruction that we can promote.
2285         // Because of this, we won't be able to get rid of the control flow, so
2286         // the xform is not worth it.
2287         return false;
2288       }
2289   }
2290 
2291   if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
2292     IfBlock2 = nullptr;
2293   } else {
2294     DomBlock = *pred_begin(IfBlock2);
2295     for (BasicBlock::iterator I = IfBlock2->begin(); !isa<TerminatorInst>(I);
2296          ++I)
2297       if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
2298         // This is not an aggressive instruction that we can promote.
2299         // Because of this, we won't be able to get rid of the control flow, so
2300         // the xform is not worth it.
2301         return false;
2302       }
2303   }
2304 
2305   DEBUG(dbgs() << "FOUND IF CONDITION!  " << *IfCond << "  T: "
2306                << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n");
2307 
2308   // If we can still promote the PHI nodes after this gauntlet of tests,
2309   // do all of the PHI's now.
2310   Instruction *InsertPt = DomBlock->getTerminator();
2311   IRBuilder<NoFolder> Builder(InsertPt);
2312 
2313   // Move all 'aggressive' instructions, which are defined in the
2314   // conditional parts of the if's up to the dominating block.
2315   if (IfBlock1) {
2316     for (auto &I : *IfBlock1)
2317       I.dropUnknownNonDebugMetadata();
2318     DomBlock->getInstList().splice(InsertPt->getIterator(),
2319                                    IfBlock1->getInstList(), IfBlock1->begin(),
2320                                    IfBlock1->getTerminator()->getIterator());
2321   }
2322   if (IfBlock2) {
2323     for (auto &I : *IfBlock2)
2324       I.dropUnknownNonDebugMetadata();
2325     DomBlock->getInstList().splice(InsertPt->getIterator(),
2326                                    IfBlock2->getInstList(), IfBlock2->begin(),
2327                                    IfBlock2->getTerminator()->getIterator());
2328   }
2329 
2330   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
2331     // Change the PHI node into a select instruction.
2332     Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
2333     Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
2334 
2335     Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
2336     PN->replaceAllUsesWith(Sel);
2337     Sel->takeName(PN);
2338     PN->eraseFromParent();
2339   }
2340 
2341   // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
2342   // has been flattened.  Change DomBlock to jump directly to our new block to
2343   // avoid other simplifycfg's kicking in on the diamond.
2344   TerminatorInst *OldTI = DomBlock->getTerminator();
2345   Builder.SetInsertPoint(OldTI);
2346   Builder.CreateBr(BB);
2347   OldTI->eraseFromParent();
2348   return true;
2349 }
2350 
2351 /// If we found a conditional branch that goes to two returning blocks,
2352 /// try to merge them together into one return,
2353 /// introducing a select if the return values disagree.
2354 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
2355                                            IRBuilder<> &Builder) {
2356   assert(BI->isConditional() && "Must be a conditional branch");
2357   BasicBlock *TrueSucc = BI->getSuccessor(0);
2358   BasicBlock *FalseSucc = BI->getSuccessor(1);
2359   ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2360   ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
2361 
2362   // Check to ensure both blocks are empty (just a return) or optionally empty
2363   // with PHI nodes.  If there are other instructions, merging would cause extra
2364   // computation on one path or the other.
2365   if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
2366     return false;
2367   if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
2368     return false;
2369 
2370   Builder.SetInsertPoint(BI);
2371   // Okay, we found a branch that is going to two return nodes.  If
2372   // there is no return value for this function, just change the
2373   // branch into a return.
2374   if (FalseRet->getNumOperands() == 0) {
2375     TrueSucc->removePredecessor(BI->getParent());
2376     FalseSucc->removePredecessor(BI->getParent());
2377     Builder.CreateRetVoid();
2378     EraseTerminatorInstAndDCECond(BI);
2379     return true;
2380   }
2381 
2382   // Otherwise, figure out what the true and false return values are
2383   // so we can insert a new select instruction.
2384   Value *TrueValue = TrueRet->getReturnValue();
2385   Value *FalseValue = FalseRet->getReturnValue();
2386 
2387   // Unwrap any PHI nodes in the return blocks.
2388   if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2389     if (TVPN->getParent() == TrueSucc)
2390       TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
2391   if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2392     if (FVPN->getParent() == FalseSucc)
2393       FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
2394 
2395   // In order for this transformation to be safe, we must be able to
2396   // unconditionally execute both operands to the return.  This is
2397   // normally the case, but we could have a potentially-trapping
2398   // constant expression that prevents this transformation from being
2399   // safe.
2400   if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2401     if (TCV->canTrap())
2402       return false;
2403   if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2404     if (FCV->canTrap())
2405       return false;
2406 
2407   // Okay, we collected all the mapped values and checked them for sanity, and
2408   // defined to really do this transformation.  First, update the CFG.
2409   TrueSucc->removePredecessor(BI->getParent());
2410   FalseSucc->removePredecessor(BI->getParent());
2411 
2412   // Insert select instructions where needed.
2413   Value *BrCond = BI->getCondition();
2414   if (TrueValue) {
2415     // Insert a select if the results differ.
2416     if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2417     } else if (isa<UndefValue>(TrueValue)) {
2418       TrueValue = FalseValue;
2419     } else {
2420       TrueValue =
2421           Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
2422     }
2423   }
2424 
2425   Value *RI =
2426       !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2427 
2428   (void)RI;
2429 
2430   DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2431                << "\n  " << *BI << "NewRet = " << *RI
2432                << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
2433 
2434   EraseTerminatorInstAndDCECond(BI);
2435 
2436   return true;
2437 }
2438 
2439 /// Return true if the given instruction is available
2440 /// in its predecessor block. If yes, the instruction will be removed.
2441 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
2442   if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2443     return false;
2444   for (Instruction &I : *PB) {
2445     Instruction *PBI = &I;
2446     // Check whether Inst and PBI generate the same value.
2447     if (Inst->isIdenticalTo(PBI)) {
2448       Inst->replaceAllUsesWith(PBI);
2449       Inst->eraseFromParent();
2450       return true;
2451     }
2452   }
2453   return false;
2454 }
2455 
2456 /// Return true if either PBI or BI has branch weight available, and store
2457 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
2458 /// not have branch weight, use 1:1 as its weight.
2459 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
2460                                    uint64_t &PredTrueWeight,
2461                                    uint64_t &PredFalseWeight,
2462                                    uint64_t &SuccTrueWeight,
2463                                    uint64_t &SuccFalseWeight) {
2464   bool PredHasWeights =
2465       PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
2466   bool SuccHasWeights =
2467       BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
2468   if (PredHasWeights || SuccHasWeights) {
2469     if (!PredHasWeights)
2470       PredTrueWeight = PredFalseWeight = 1;
2471     if (!SuccHasWeights)
2472       SuccTrueWeight = SuccFalseWeight = 1;
2473     return true;
2474   } else {
2475     return false;
2476   }
2477 }
2478 
2479 /// If this basic block is simple enough, and if a predecessor branches to us
2480 /// and one of our successors, fold the block into the predecessor and use
2481 /// logical operations to pick the right destination.
2482 bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
2483   BasicBlock *BB = BI->getParent();
2484 
2485   Instruction *Cond = nullptr;
2486   if (BI->isConditional())
2487     Cond = dyn_cast<Instruction>(BI->getCondition());
2488   else {
2489     // For unconditional branch, check for a simple CFG pattern, where
2490     // BB has a single predecessor and BB's successor is also its predecessor's
2491     // successor. If such pattern exisits, check for CSE between BB and its
2492     // predecessor.
2493     if (BasicBlock *PB = BB->getSinglePredecessor())
2494       if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2495         if (PBI->isConditional() &&
2496             (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2497              BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2498           for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2499             Instruction *Curr = &*I++;
2500             if (isa<CmpInst>(Curr)) {
2501               Cond = Curr;
2502               break;
2503             }
2504             // Quit if we can't remove this instruction.
2505             if (!checkCSEInPredecessor(Curr, PB))
2506               return false;
2507           }
2508         }
2509 
2510     if (!Cond)
2511       return false;
2512   }
2513 
2514   if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2515       Cond->getParent() != BB || !Cond->hasOneUse())
2516     return false;
2517 
2518   // Make sure the instruction after the condition is the cond branch.
2519   BasicBlock::iterator CondIt = ++Cond->getIterator();
2520 
2521   // Ignore dbg intrinsics.
2522   while (isa<DbgInfoIntrinsic>(CondIt))
2523     ++CondIt;
2524 
2525   if (&*CondIt != BI)
2526     return false;
2527 
2528   // Only allow this transformation if computing the condition doesn't involve
2529   // too many instructions and these involved instructions can be executed
2530   // unconditionally. We denote all involved instructions except the condition
2531   // as "bonus instructions", and only allow this transformation when the
2532   // number of the bonus instructions does not exceed a certain threshold.
2533   unsigned NumBonusInsts = 0;
2534   for (auto I = BB->begin(); Cond != &*I; ++I) {
2535     // Ignore dbg intrinsics.
2536     if (isa<DbgInfoIntrinsic>(I))
2537       continue;
2538     if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
2539       return false;
2540     // I has only one use and can be executed unconditionally.
2541     Instruction *User = dyn_cast<Instruction>(I->user_back());
2542     if (User == nullptr || User->getParent() != BB)
2543       return false;
2544     // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2545     // to use any other instruction, User must be an instruction between next(I)
2546     // and Cond.
2547     ++NumBonusInsts;
2548     // Early exits once we reach the limit.
2549     if (NumBonusInsts > BonusInstThreshold)
2550       return false;
2551   }
2552 
2553   // Cond is known to be a compare or binary operator.  Check to make sure that
2554   // neither operand is a potentially-trapping constant expression.
2555   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2556     if (CE->canTrap())
2557       return false;
2558   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2559     if (CE->canTrap())
2560       return false;
2561 
2562   // Finally, don't infinitely unroll conditional loops.
2563   BasicBlock *TrueDest = BI->getSuccessor(0);
2564   BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2565   if (TrueDest == BB || FalseDest == BB)
2566     return false;
2567 
2568   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2569     BasicBlock *PredBlock = *PI;
2570     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2571 
2572     // Check that we have two conditional branches.  If there is a PHI node in
2573     // the common successor, verify that the same value flows in from both
2574     // blocks.
2575     SmallVector<PHINode *, 4> PHIs;
2576     if (!PBI || PBI->isUnconditional() ||
2577         (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
2578         (!BI->isConditional() &&
2579          !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2580       continue;
2581 
2582     // Determine if the two branches share a common destination.
2583     Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2584     bool InvertPredCond = false;
2585 
2586     if (BI->isConditional()) {
2587       if (PBI->getSuccessor(0) == TrueDest) {
2588         Opc = Instruction::Or;
2589       } else if (PBI->getSuccessor(1) == FalseDest) {
2590         Opc = Instruction::And;
2591       } else if (PBI->getSuccessor(0) == FalseDest) {
2592         Opc = Instruction::And;
2593         InvertPredCond = true;
2594       } else if (PBI->getSuccessor(1) == TrueDest) {
2595         Opc = Instruction::Or;
2596         InvertPredCond = true;
2597       } else {
2598         continue;
2599       }
2600     } else {
2601       if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2602         continue;
2603     }
2604 
2605     DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2606     IRBuilder<> Builder(PBI);
2607 
2608     // If we need to invert the condition in the pred block to match, do so now.
2609     if (InvertPredCond) {
2610       Value *NewCond = PBI->getCondition();
2611 
2612       if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2613         CmpInst *CI = cast<CmpInst>(NewCond);
2614         CI->setPredicate(CI->getInversePredicate());
2615       } else {
2616         NewCond =
2617             Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
2618       }
2619 
2620       PBI->setCondition(NewCond);
2621       PBI->swapSuccessors();
2622     }
2623 
2624     // If we have bonus instructions, clone them into the predecessor block.
2625     // Note that there may be multiple predecessor blocks, so we cannot move
2626     // bonus instructions to a predecessor block.
2627     ValueToValueMapTy VMap; // maps original values to cloned values
2628     // We already make sure Cond is the last instruction before BI. Therefore,
2629     // all instructions before Cond other than DbgInfoIntrinsic are bonus
2630     // instructions.
2631     for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
2632       if (isa<DbgInfoIntrinsic>(BonusInst))
2633         continue;
2634       Instruction *NewBonusInst = BonusInst->clone();
2635       RemapInstruction(NewBonusInst, VMap,
2636                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
2637       VMap[&*BonusInst] = NewBonusInst;
2638 
2639       // If we moved a load, we cannot any longer claim any knowledge about
2640       // its potential value. The previous information might have been valid
2641       // only given the branch precondition.
2642       // For an analogous reason, we must also drop all the metadata whose
2643       // semantics we don't understand.
2644       NewBonusInst->dropUnknownNonDebugMetadata();
2645 
2646       PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2647       NewBonusInst->takeName(&*BonusInst);
2648       BonusInst->setName(BonusInst->getName() + ".old");
2649     }
2650 
2651     // Clone Cond into the predecessor basic block, and or/and the
2652     // two conditions together.
2653     Instruction *New = Cond->clone();
2654     RemapInstruction(New, VMap,
2655                      RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
2656     PredBlock->getInstList().insert(PBI->getIterator(), New);
2657     New->takeName(Cond);
2658     Cond->setName(New->getName() + ".old");
2659 
2660     if (BI->isConditional()) {
2661       Instruction *NewCond = cast<Instruction>(
2662           Builder.CreateBinOp(Opc, PBI->getCondition(), New, "or.cond"));
2663       PBI->setCondition(NewCond);
2664 
2665       uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2666       bool HasWeights =
2667           extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
2668                                  SuccTrueWeight, SuccFalseWeight);
2669       SmallVector<uint64_t, 8> NewWeights;
2670 
2671       if (PBI->getSuccessor(0) == BB) {
2672         if (HasWeights) {
2673           // PBI: br i1 %x, BB, FalseDest
2674           // BI:  br i1 %y, TrueDest, FalseDest
2675           // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2676           NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2677           // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2678           //               TrueWeight for PBI * FalseWeight for BI.
2679           // We assume that total weights of a BranchInst can fit into 32 bits.
2680           // Therefore, we will not have overflow using 64-bit arithmetic.
2681           NewWeights.push_back(PredFalseWeight *
2682                                    (SuccFalseWeight + SuccTrueWeight) +
2683                                PredTrueWeight * SuccFalseWeight);
2684         }
2685         AddPredecessorToBlock(TrueDest, PredBlock, BB);
2686         PBI->setSuccessor(0, TrueDest);
2687       }
2688       if (PBI->getSuccessor(1) == BB) {
2689         if (HasWeights) {
2690           // PBI: br i1 %x, TrueDest, BB
2691           // BI:  br i1 %y, TrueDest, FalseDest
2692           // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2693           //              FalseWeight for PBI * TrueWeight for BI.
2694           NewWeights.push_back(PredTrueWeight *
2695                                    (SuccFalseWeight + SuccTrueWeight) +
2696                                PredFalseWeight * SuccTrueWeight);
2697           // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2698           NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2699         }
2700         AddPredecessorToBlock(FalseDest, PredBlock, BB);
2701         PBI->setSuccessor(1, FalseDest);
2702       }
2703       if (NewWeights.size() == 2) {
2704         // Halve the weights if any of them cannot fit in an uint32_t
2705         FitWeights(NewWeights);
2706 
2707         SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
2708                                            NewWeights.end());
2709         PBI->setMetadata(
2710             LLVMContext::MD_prof,
2711             MDBuilder(BI->getContext()).createBranchWeights(MDWeights));
2712       } else
2713         PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2714     } else {
2715       // Update PHI nodes in the common successors.
2716       for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2717         ConstantInt *PBI_C = cast<ConstantInt>(
2718             PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2719         assert(PBI_C->getType()->isIntegerTy(1));
2720         Instruction *MergedCond = nullptr;
2721         if (PBI->getSuccessor(0) == TrueDest) {
2722           // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2723           // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2724           //       is false: !PBI_Cond and BI_Value
2725           Instruction *NotCond = cast<Instruction>(
2726               Builder.CreateNot(PBI->getCondition(), "not.cond"));
2727           MergedCond = cast<Instruction>(
2728               Builder.CreateBinOp(Instruction::And, NotCond, New, "and.cond"));
2729           if (PBI_C->isOne())
2730             MergedCond = cast<Instruction>(Builder.CreateBinOp(
2731                 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
2732         } else {
2733           // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2734           // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2735           //       is false: PBI_Cond and BI_Value
2736           MergedCond = cast<Instruction>(Builder.CreateBinOp(
2737               Instruction::And, PBI->getCondition(), New, "and.cond"));
2738           if (PBI_C->isOne()) {
2739             Instruction *NotCond = cast<Instruction>(
2740                 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2741             MergedCond = cast<Instruction>(Builder.CreateBinOp(
2742                 Instruction::Or, NotCond, MergedCond, "or.cond"));
2743           }
2744         }
2745         // Update PHI Node.
2746         PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2747                                   MergedCond);
2748       }
2749       // Change PBI from Conditional to Unconditional.
2750       BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2751       EraseTerminatorInstAndDCECond(PBI);
2752       PBI = New_PBI;
2753     }
2754 
2755     // TODO: If BB is reachable from all paths through PredBlock, then we
2756     // could replace PBI's branch probabilities with BI's.
2757 
2758     // Copy any debug value intrinsics into the end of PredBlock.
2759     for (Instruction &I : *BB)
2760       if (isa<DbgInfoIntrinsic>(I))
2761         I.clone()->insertBefore(PBI);
2762 
2763     return true;
2764   }
2765   return false;
2766 }
2767 
2768 // If there is only one store in BB1 and BB2, return it, otherwise return
2769 // nullptr.
2770 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2771   StoreInst *S = nullptr;
2772   for (auto *BB : {BB1, BB2}) {
2773     if (!BB)
2774       continue;
2775     for (auto &I : *BB)
2776       if (auto *SI = dyn_cast<StoreInst>(&I)) {
2777         if (S)
2778           // Multiple stores seen.
2779           return nullptr;
2780         else
2781           S = SI;
2782       }
2783   }
2784   return S;
2785 }
2786 
2787 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2788                                               Value *AlternativeV = nullptr) {
2789   // PHI is going to be a PHI node that allows the value V that is defined in
2790   // BB to be referenced in BB's only successor.
2791   //
2792   // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2793   // doesn't matter to us what the other operand is (it'll never get used). We
2794   // could just create a new PHI with an undef incoming value, but that could
2795   // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2796   // other PHI. So here we directly look for some PHI in BB's successor with V
2797   // as an incoming operand. If we find one, we use it, else we create a new
2798   // one.
2799   //
2800   // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2801   // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2802   // where OtherBB is the single other predecessor of BB's only successor.
2803   PHINode *PHI = nullptr;
2804   BasicBlock *Succ = BB->getSingleSuccessor();
2805 
2806   for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2807     if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2808       PHI = cast<PHINode>(I);
2809       if (!AlternativeV)
2810         break;
2811 
2812       assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2813       auto PredI = pred_begin(Succ);
2814       BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2815       if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2816         break;
2817       PHI = nullptr;
2818     }
2819   if (PHI)
2820     return PHI;
2821 
2822   // If V is not an instruction defined in BB, just return it.
2823   if (!AlternativeV &&
2824       (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2825     return V;
2826 
2827   PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
2828   PHI->addIncoming(V, BB);
2829   for (BasicBlock *PredBB : predecessors(Succ))
2830     if (PredBB != BB)
2831       PHI->addIncoming(
2832           AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
2833   return PHI;
2834 }
2835 
2836 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2837                                            BasicBlock *QTB, BasicBlock *QFB,
2838                                            BasicBlock *PostBB, Value *Address,
2839                                            bool InvertPCond, bool InvertQCond) {
2840   auto IsaBitcastOfPointerType = [](const Instruction &I) {
2841     return Operator::getOpcode(&I) == Instruction::BitCast &&
2842            I.getType()->isPointerTy();
2843   };
2844 
2845   // If we're not in aggressive mode, we only optimize if we have some
2846   // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2847   auto IsWorthwhile = [&](BasicBlock *BB) {
2848     if (!BB)
2849       return true;
2850     // Heuristic: if the block can be if-converted/phi-folded and the
2851     // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2852     // thread this store.
2853     unsigned N = 0;
2854     for (auto &I : *BB) {
2855       // Cheap instructions viable for folding.
2856       if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2857           isa<StoreInst>(I))
2858         ++N;
2859       // Free instructions.
2860       else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2861                IsaBitcastOfPointerType(I))
2862         continue;
2863       else
2864         return false;
2865     }
2866     return N <= PHINodeFoldingThreshold;
2867   };
2868 
2869   if (!MergeCondStoresAggressively &&
2870       (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
2871        !IsWorthwhile(QFB)))
2872     return false;
2873 
2874   // For every pointer, there must be exactly two stores, one coming from
2875   // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2876   // store (to any address) in PTB,PFB or QTB,QFB.
2877   // FIXME: We could relax this restriction with a bit more work and performance
2878   // testing.
2879   StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2880   StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2881   if (!PStore || !QStore)
2882     return false;
2883 
2884   // Now check the stores are compatible.
2885   if (!QStore->isUnordered() || !PStore->isUnordered())
2886     return false;
2887 
2888   // Check that sinking the store won't cause program behavior changes. Sinking
2889   // the store out of the Q blocks won't change any behavior as we're sinking
2890   // from a block to its unconditional successor. But we're moving a store from
2891   // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2892   // So we need to check that there are no aliasing loads or stores in
2893   // QBI, QTB and QFB. We also need to check there are no conflicting memory
2894   // operations between PStore and the end of its parent block.
2895   //
2896   // The ideal way to do this is to query AliasAnalysis, but we don't
2897   // preserve AA currently so that is dangerous. Be super safe and just
2898   // check there are no other memory operations at all.
2899   for (auto &I : *QFB->getSinglePredecessor())
2900     if (I.mayReadOrWriteMemory())
2901       return false;
2902   for (auto &I : *QFB)
2903     if (&I != QStore && I.mayReadOrWriteMemory())
2904       return false;
2905   if (QTB)
2906     for (auto &I : *QTB)
2907       if (&I != QStore && I.mayReadOrWriteMemory())
2908         return false;
2909   for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2910        I != E; ++I)
2911     if (&*I != PStore && I->mayReadOrWriteMemory())
2912       return false;
2913 
2914   // OK, we're going to sink the stores to PostBB. The store has to be
2915   // conditional though, so first create the predicate.
2916   Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2917                      ->getCondition();
2918   Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2919                      ->getCondition();
2920 
2921   Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2922                                                 PStore->getParent());
2923   Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2924                                                 QStore->getParent(), PPHI);
2925 
2926   IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2927 
2928   Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2929   Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2930 
2931   if (InvertPCond)
2932     PPred = QB.CreateNot(PPred);
2933   if (InvertQCond)
2934     QPred = QB.CreateNot(QPred);
2935   Value *CombinedPred = QB.CreateOr(PPred, QPred);
2936 
2937   auto *T =
2938       SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
2939   QB.SetInsertPoint(T);
2940   StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2941   AAMDNodes AAMD;
2942   PStore->getAAMetadata(AAMD, /*Merge=*/false);
2943   PStore->getAAMetadata(AAMD, /*Merge=*/true);
2944   SI->setAAMetadata(AAMD);
2945 
2946   QStore->eraseFromParent();
2947   PStore->eraseFromParent();
2948 
2949   return true;
2950 }
2951 
2952 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2953   // The intention here is to find diamonds or triangles (see below) where each
2954   // conditional block contains a store to the same address. Both of these
2955   // stores are conditional, so they can't be unconditionally sunk. But it may
2956   // be profitable to speculatively sink the stores into one merged store at the
2957   // end, and predicate the merged store on the union of the two conditions of
2958   // PBI and QBI.
2959   //
2960   // This can reduce the number of stores executed if both of the conditions are
2961   // true, and can allow the blocks to become small enough to be if-converted.
2962   // This optimization will also chain, so that ladders of test-and-set
2963   // sequences can be if-converted away.
2964   //
2965   // We only deal with simple diamonds or triangles:
2966   //
2967   //     PBI       or      PBI        or a combination of the two
2968   //    /   \               | \
2969   //   PTB  PFB             |  PFB
2970   //    \   /               | /
2971   //     QBI                QBI
2972   //    /  \                | \
2973   //   QTB  QFB             |  QFB
2974   //    \  /                | /
2975   //    PostBB            PostBB
2976   //
2977   // We model triangles as a type of diamond with a nullptr "true" block.
2978   // Triangles are canonicalized so that the fallthrough edge is represented by
2979   // a true condition, as in the diagram above.
2980   //
2981   BasicBlock *PTB = PBI->getSuccessor(0);
2982   BasicBlock *PFB = PBI->getSuccessor(1);
2983   BasicBlock *QTB = QBI->getSuccessor(0);
2984   BasicBlock *QFB = QBI->getSuccessor(1);
2985   BasicBlock *PostBB = QFB->getSingleSuccessor();
2986 
2987   bool InvertPCond = false, InvertQCond = false;
2988   // Canonicalize fallthroughs to the true branches.
2989   if (PFB == QBI->getParent()) {
2990     std::swap(PFB, PTB);
2991     InvertPCond = true;
2992   }
2993   if (QFB == PostBB) {
2994     std::swap(QFB, QTB);
2995     InvertQCond = true;
2996   }
2997 
2998   // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2999   // and QFB may not. Model fallthroughs as a nullptr block.
3000   if (PTB == QBI->getParent())
3001     PTB = nullptr;
3002   if (QTB == PostBB)
3003     QTB = nullptr;
3004 
3005   // Legality bailouts. We must have at least the non-fallthrough blocks and
3006   // the post-dominating block, and the non-fallthroughs must only have one
3007   // predecessor.
3008   auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
3009     return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
3010   };
3011   if (!PostBB ||
3012       !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
3013       !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3014     return false;
3015   if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3016       (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3017     return false;
3018   if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
3019     return false;
3020 
3021   // OK, this is a sequence of two diamonds or triangles.
3022   // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
3023   SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
3024   for (auto *BB : {PTB, PFB}) {
3025     if (!BB)
3026       continue;
3027     for (auto &I : *BB)
3028       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3029         PStoreAddresses.insert(SI->getPointerOperand());
3030   }
3031   for (auto *BB : {QTB, QFB}) {
3032     if (!BB)
3033       continue;
3034     for (auto &I : *BB)
3035       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3036         QStoreAddresses.insert(SI->getPointerOperand());
3037   }
3038 
3039   set_intersect(PStoreAddresses, QStoreAddresses);
3040   // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3041   // clear what it contains.
3042   auto &CommonAddresses = PStoreAddresses;
3043 
3044   bool Changed = false;
3045   for (auto *Address : CommonAddresses)
3046     Changed |= mergeConditionalStoreToAddress(
3047         PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
3048   return Changed;
3049 }
3050 
3051 /// If we have a conditional branch as a predecessor of another block,
3052 /// this function tries to simplify it.  We know
3053 /// that PBI and BI are both conditional branches, and BI is in one of the
3054 /// successor blocks of PBI - PBI branches to BI.
3055 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3056                                            const DataLayout &DL) {
3057   assert(PBI->isConditional() && BI->isConditional());
3058   BasicBlock *BB = BI->getParent();
3059 
3060   // If this block ends with a branch instruction, and if there is a
3061   // predecessor that ends on a branch of the same condition, make
3062   // this conditional branch redundant.
3063   if (PBI->getCondition() == BI->getCondition() &&
3064       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3065     // Okay, the outcome of this conditional branch is statically
3066     // knowable.  If this block had a single pred, handle specially.
3067     if (BB->getSinglePredecessor()) {
3068       // Turn this into a branch on constant.
3069       bool CondIsTrue = PBI->getSuccessor(0) == BB;
3070       BI->setCondition(
3071           ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
3072       return true; // Nuke the branch on constant.
3073     }
3074 
3075     // Otherwise, if there are multiple predecessors, insert a PHI that merges
3076     // in the constant and simplify the block result.  Subsequent passes of
3077     // simplifycfg will thread the block.
3078     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
3079       pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
3080       PHINode *NewPN = PHINode::Create(
3081           Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
3082           BI->getCondition()->getName() + ".pr", &BB->front());
3083       // Okay, we're going to insert the PHI node.  Since PBI is not the only
3084       // predecessor, compute the PHI'd conditional value for all of the preds.
3085       // Any predecessor where the condition is not computable we keep symbolic.
3086       for (pred_iterator PI = PB; PI != PE; ++PI) {
3087         BasicBlock *P = *PI;
3088         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
3089             PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
3090             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3091           bool CondIsTrue = PBI->getSuccessor(0) == BB;
3092           NewPN->addIncoming(
3093               ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
3094               P);
3095         } else {
3096           NewPN->addIncoming(BI->getCondition(), P);
3097         }
3098       }
3099 
3100       BI->setCondition(NewPN);
3101       return true;
3102     }
3103   }
3104 
3105   if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
3106     if (CE->canTrap())
3107       return false;
3108 
3109   // If both branches are conditional and both contain stores to the same
3110   // address, remove the stores from the conditionals and create a conditional
3111   // merged store at the end.
3112   if (MergeCondStores && mergeConditionalStores(PBI, BI))
3113     return true;
3114 
3115   // If this is a conditional branch in an empty block, and if any
3116   // predecessors are a conditional branch to one of our destinations,
3117   // fold the conditions into logical ops and one cond br.
3118   BasicBlock::iterator BBI = BB->begin();
3119   // Ignore dbg intrinsics.
3120   while (isa<DbgInfoIntrinsic>(BBI))
3121     ++BBI;
3122   if (&*BBI != BI)
3123     return false;
3124 
3125   int PBIOp, BIOp;
3126   if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3127     PBIOp = 0;
3128     BIOp = 0;
3129   } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3130     PBIOp = 0;
3131     BIOp = 1;
3132   } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3133     PBIOp = 1;
3134     BIOp = 0;
3135   } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3136     PBIOp = 1;
3137     BIOp = 1;
3138   } else {
3139     return false;
3140   }
3141 
3142   // Check to make sure that the other destination of this branch
3143   // isn't BB itself.  If so, this is an infinite loop that will
3144   // keep getting unwound.
3145   if (PBI->getSuccessor(PBIOp) == BB)
3146     return false;
3147 
3148   // Do not perform this transformation if it would require
3149   // insertion of a large number of select instructions. For targets
3150   // without predication/cmovs, this is a big pessimization.
3151 
3152   // Also do not perform this transformation if any phi node in the common
3153   // destination block can trap when reached by BB or PBB (PR17073). In that
3154   // case, it would be unsafe to hoist the operation into a select instruction.
3155 
3156   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
3157   unsigned NumPhis = 0;
3158   for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3159        ++II, ++NumPhis) {
3160     if (NumPhis > 2) // Disable this xform.
3161       return false;
3162 
3163     PHINode *PN = cast<PHINode>(II);
3164     Value *BIV = PN->getIncomingValueForBlock(BB);
3165     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3166       if (CE->canTrap())
3167         return false;
3168 
3169     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3170     Value *PBIV = PN->getIncomingValue(PBBIdx);
3171     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3172       if (CE->canTrap())
3173         return false;
3174   }
3175 
3176   // Finally, if everything is ok, fold the branches to logical ops.
3177   BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
3178 
3179   DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
3180                << "AND: " << *BI->getParent());
3181 
3182   // If OtherDest *is* BB, then BB is a basic block with a single conditional
3183   // branch in it, where one edge (OtherDest) goes back to itself but the other
3184   // exits.  We don't *know* that the program avoids the infinite loop
3185   // (even though that seems likely).  If we do this xform naively, we'll end up
3186   // recursively unpeeling the loop.  Since we know that (after the xform is
3187   // done) that the block *is* infinite if reached, we just make it an obviously
3188   // infinite loop with no cond branch.
3189   if (OtherDest == BB) {
3190     // Insert it at the end of the function, because it's either code,
3191     // or it won't matter if it's hot. :)
3192     BasicBlock *InfLoopBlock =
3193         BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
3194     BranchInst::Create(InfLoopBlock, InfLoopBlock);
3195     OtherDest = InfLoopBlock;
3196   }
3197 
3198   DEBUG(dbgs() << *PBI->getParent()->getParent());
3199 
3200   // BI may have other predecessors.  Because of this, we leave
3201   // it alone, but modify PBI.
3202 
3203   // Make sure we get to CommonDest on True&True directions.
3204   Value *PBICond = PBI->getCondition();
3205   IRBuilder<NoFolder> Builder(PBI);
3206   if (PBIOp)
3207     PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
3208 
3209   Value *BICond = BI->getCondition();
3210   if (BIOp)
3211     BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
3212 
3213   // Merge the conditions.
3214   Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
3215 
3216   // Modify PBI to branch on the new condition to the new dests.
3217   PBI->setCondition(Cond);
3218   PBI->setSuccessor(0, CommonDest);
3219   PBI->setSuccessor(1, OtherDest);
3220 
3221   // Update branch weight for PBI.
3222   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3223   uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
3224   bool HasWeights =
3225       extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3226                              SuccTrueWeight, SuccFalseWeight);
3227   if (HasWeights) {
3228     PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3229     PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3230     SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3231     SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3232     // The weight to CommonDest should be PredCommon * SuccTotal +
3233     //                                    PredOther * SuccCommon.
3234     // The weight to OtherDest should be PredOther * SuccOther.
3235     uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3236                                   PredOther * SuccCommon,
3237                               PredOther * SuccOther};
3238     // Halve the weights if any of them cannot fit in an uint32_t
3239     FitWeights(NewWeights);
3240 
3241     PBI->setMetadata(LLVMContext::MD_prof,
3242                      MDBuilder(BI->getContext())
3243                          .createBranchWeights(NewWeights[0], NewWeights[1]));
3244   }
3245 
3246   // OtherDest may have phi nodes.  If so, add an entry from PBI's
3247   // block that are identical to the entries for BI's block.
3248   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
3249 
3250   // We know that the CommonDest already had an edge from PBI to
3251   // it.  If it has PHIs though, the PHIs may have different
3252   // entries for BB and PBI's BB.  If so, insert a select to make
3253   // them agree.
3254   PHINode *PN;
3255   for (BasicBlock::iterator II = CommonDest->begin();
3256        (PN = dyn_cast<PHINode>(II)); ++II) {
3257     Value *BIV = PN->getIncomingValueForBlock(BB);
3258     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3259     Value *PBIV = PN->getIncomingValue(PBBIdx);
3260     if (BIV != PBIV) {
3261       // Insert a select in PBI to pick the right value.
3262       SelectInst *NV = cast<SelectInst>(
3263           Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
3264       PN->setIncomingValue(PBBIdx, NV);
3265       // Although the select has the same condition as PBI, the original branch
3266       // weights for PBI do not apply to the new select because the select's
3267       // 'logical' edges are incoming edges of the phi that is eliminated, not
3268       // the outgoing edges of PBI.
3269       if (HasWeights) {
3270         uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3271         uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3272         uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3273         uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3274         // The weight to PredCommonDest should be PredCommon * SuccTotal.
3275         // The weight to PredOtherDest should be PredOther * SuccCommon.
3276         uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3277                                   PredOther * SuccCommon};
3278 
3279         FitWeights(NewWeights);
3280 
3281         NV->setMetadata(LLVMContext::MD_prof,
3282                         MDBuilder(BI->getContext())
3283                             .createBranchWeights(NewWeights[0], NewWeights[1]));
3284       }
3285     }
3286   }
3287 
3288   DEBUG(dbgs() << "INTO: " << *PBI->getParent());
3289   DEBUG(dbgs() << *PBI->getParent()->getParent());
3290 
3291   // This basic block is probably dead.  We know it has at least
3292   // one fewer predecessor.
3293   return true;
3294 }
3295 
3296 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3297 // true or to FalseBB if Cond is false.
3298 // Takes care of updating the successors and removing the old terminator.
3299 // Also makes sure not to introduce new successors by assuming that edges to
3300 // non-successor TrueBBs and FalseBBs aren't reachable.
3301 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
3302                                        BasicBlock *TrueBB, BasicBlock *FalseBB,
3303                                        uint32_t TrueWeight,
3304                                        uint32_t FalseWeight) {
3305   // Remove any superfluous successor edges from the CFG.
3306   // First, figure out which successors to preserve.
3307   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3308   // successor.
3309   BasicBlock *KeepEdge1 = TrueBB;
3310   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
3311 
3312   // Then remove the rest.
3313   for (BasicBlock *Succ : OldTerm->successors()) {
3314     // Make sure only to keep exactly one copy of each edge.
3315     if (Succ == KeepEdge1)
3316       KeepEdge1 = nullptr;
3317     else if (Succ == KeepEdge2)
3318       KeepEdge2 = nullptr;
3319     else
3320       Succ->removePredecessor(OldTerm->getParent(),
3321                               /*DontDeleteUselessPHIs=*/true);
3322   }
3323 
3324   IRBuilder<> Builder(OldTerm);
3325   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3326 
3327   // Insert an appropriate new terminator.
3328   if (!KeepEdge1 && !KeepEdge2) {
3329     if (TrueBB == FalseBB)
3330       // We were only looking for one successor, and it was present.
3331       // Create an unconditional branch to it.
3332       Builder.CreateBr(TrueBB);
3333     else {
3334       // We found both of the successors we were looking for.
3335       // Create a conditional branch sharing the condition of the select.
3336       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3337       if (TrueWeight != FalseWeight)
3338         NewBI->setMetadata(LLVMContext::MD_prof,
3339                            MDBuilder(OldTerm->getContext())
3340                                .createBranchWeights(TrueWeight, FalseWeight));
3341     }
3342   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3343     // Neither of the selected blocks were successors, so this
3344     // terminator must be unreachable.
3345     new UnreachableInst(OldTerm->getContext(), OldTerm);
3346   } else {
3347     // One of the selected values was a successor, but the other wasn't.
3348     // Insert an unconditional branch to the one that was found;
3349     // the edge to the one that wasn't must be unreachable.
3350     if (!KeepEdge1)
3351       // Only TrueBB was found.
3352       Builder.CreateBr(TrueBB);
3353     else
3354       // Only FalseBB was found.
3355       Builder.CreateBr(FalseBB);
3356   }
3357 
3358   EraseTerminatorInstAndDCECond(OldTerm);
3359   return true;
3360 }
3361 
3362 // Replaces
3363 //   (switch (select cond, X, Y)) on constant X, Y
3364 // with a branch - conditional if X and Y lead to distinct BBs,
3365 // unconditional otherwise.
3366 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
3367   // Check for constant integer values in the select.
3368   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
3369   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
3370   if (!TrueVal || !FalseVal)
3371     return false;
3372 
3373   // Find the relevant condition and destinations.
3374   Value *Condition = Select->getCondition();
3375   BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
3376   BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
3377 
3378   // Get weight for TrueBB and FalseBB.
3379   uint32_t TrueWeight = 0, FalseWeight = 0;
3380   SmallVector<uint64_t, 8> Weights;
3381   bool HasWeights = HasBranchWeights(SI);
3382   if (HasWeights) {
3383     GetBranchWeights(SI, Weights);
3384     if (Weights.size() == 1 + SI->getNumCases()) {
3385       TrueWeight =
3386           (uint32_t)Weights[SI->findCaseValue(TrueVal).getSuccessorIndex()];
3387       FalseWeight =
3388           (uint32_t)Weights[SI->findCaseValue(FalseVal).getSuccessorIndex()];
3389     }
3390   }
3391 
3392   // Perform the actual simplification.
3393   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
3394                                     FalseWeight);
3395 }
3396 
3397 // Replaces
3398 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
3399 //                             blockaddress(@fn, BlockB)))
3400 // with
3401 //   (br cond, BlockA, BlockB).
3402 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3403   // Check that both operands of the select are block addresses.
3404   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3405   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3406   if (!TBA || !FBA)
3407     return false;
3408 
3409   // Extract the actual blocks.
3410   BasicBlock *TrueBB = TBA->getBasicBlock();
3411   BasicBlock *FalseBB = FBA->getBasicBlock();
3412 
3413   // Perform the actual simplification.
3414   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
3415                                     0);
3416 }
3417 
3418 /// This is called when we find an icmp instruction
3419 /// (a seteq/setne with a constant) as the only instruction in a
3420 /// block that ends with an uncond branch.  We are looking for a very specific
3421 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
3422 /// this case, we merge the first two "or's of icmp" into a switch, but then the
3423 /// default value goes to an uncond block with a seteq in it, we get something
3424 /// like:
3425 ///
3426 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
3427 /// DEFAULT:
3428 ///   %tmp = icmp eq i8 %A, 92
3429 ///   br label %end
3430 /// end:
3431 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
3432 ///
3433 /// We prefer to split the edge to 'end' so that there is a true/false entry to
3434 /// the PHI, merging the third icmp into the switch.
3435 static bool TryToSimplifyUncondBranchWithICmpInIt(
3436     ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3437     const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3438     AssumptionCache *AC) {
3439   BasicBlock *BB = ICI->getParent();
3440 
3441   // If the block has any PHIs in it or the icmp has multiple uses, it is too
3442   // complex.
3443   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
3444     return false;
3445 
3446   Value *V = ICI->getOperand(0);
3447   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
3448 
3449   // The pattern we're looking for is where our only predecessor is a switch on
3450   // 'V' and this block is the default case for the switch.  In this case we can
3451   // fold the compared value into the switch to simplify things.
3452   BasicBlock *Pred = BB->getSinglePredecessor();
3453   if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3454     return false;
3455 
3456   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3457   if (SI->getCondition() != V)
3458     return false;
3459 
3460   // If BB is reachable on a non-default case, then we simply know the value of
3461   // V in this block.  Substitute it and constant fold the icmp instruction
3462   // away.
3463   if (SI->getDefaultDest() != BB) {
3464     ConstantInt *VVal = SI->findCaseDest(BB);
3465     assert(VVal && "Should have a unique destination value");
3466     ICI->setOperand(0, VVal);
3467 
3468     if (Value *V = SimplifyInstruction(ICI, DL)) {
3469       ICI->replaceAllUsesWith(V);
3470       ICI->eraseFromParent();
3471     }
3472     // BB is now empty, so it is likely to simplify away.
3473     return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
3474   }
3475 
3476   // Ok, the block is reachable from the default dest.  If the constant we're
3477   // comparing exists in one of the other edges, then we can constant fold ICI
3478   // and zap it.
3479   if (SI->findCaseValue(Cst) != SI->case_default()) {
3480     Value *V;
3481     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3482       V = ConstantInt::getFalse(BB->getContext());
3483     else
3484       V = ConstantInt::getTrue(BB->getContext());
3485 
3486     ICI->replaceAllUsesWith(V);
3487     ICI->eraseFromParent();
3488     // BB is now empty, so it is likely to simplify away.
3489     return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
3490   }
3491 
3492   // The use of the icmp has to be in the 'end' block, by the only PHI node in
3493   // the block.
3494   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
3495   PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
3496   if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
3497       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3498     return false;
3499 
3500   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3501   // true in the PHI.
3502   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3503   Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3504 
3505   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3506     std::swap(DefaultCst, NewCst);
3507 
3508   // Replace ICI (which is used by the PHI for the default value) with true or
3509   // false depending on if it is EQ or NE.
3510   ICI->replaceAllUsesWith(DefaultCst);
3511   ICI->eraseFromParent();
3512 
3513   // Okay, the switch goes to this block on a default value.  Add an edge from
3514   // the switch to the merge point on the compared value.
3515   BasicBlock *NewBB =
3516       BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
3517   SmallVector<uint64_t, 8> Weights;
3518   bool HasWeights = HasBranchWeights(SI);
3519   if (HasWeights) {
3520     GetBranchWeights(SI, Weights);
3521     if (Weights.size() == 1 + SI->getNumCases()) {
3522       // Split weight for default case to case for "Cst".
3523       Weights[0] = (Weights[0] + 1) >> 1;
3524       Weights.push_back(Weights[0]);
3525 
3526       SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3527       SI->setMetadata(
3528           LLVMContext::MD_prof,
3529           MDBuilder(SI->getContext()).createBranchWeights(MDWeights));
3530     }
3531   }
3532   SI->addCase(Cst, NewBB);
3533 
3534   // NewBB branches to the phi block, add the uncond branch and the phi entry.
3535   Builder.SetInsertPoint(NewBB);
3536   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3537   Builder.CreateBr(SuccBlock);
3538   PHIUse->addIncoming(NewCst, NewBB);
3539   return true;
3540 }
3541 
3542 /// The specified branch is a conditional branch.
3543 /// Check to see if it is branching on an or/and chain of icmp instructions, and
3544 /// fold it into a switch instruction if so.
3545 static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3546                                       const DataLayout &DL) {
3547   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3548   if (!Cond)
3549     return false;
3550 
3551   // Change br (X == 0 | X == 1), T, F into a switch instruction.
3552   // If this is a bunch of seteq's or'd together, or if it's a bunch of
3553   // 'setne's and'ed together, collect them.
3554 
3555   // Try to gather values from a chain of and/or to be turned into a switch
3556   ConstantComparesGatherer ConstantCompare(Cond, DL);
3557   // Unpack the result
3558   SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
3559   Value *CompVal = ConstantCompare.CompValue;
3560   unsigned UsedICmps = ConstantCompare.UsedICmps;
3561   Value *ExtraCase = ConstantCompare.Extra;
3562 
3563   // If we didn't have a multiply compared value, fail.
3564   if (!CompVal)
3565     return false;
3566 
3567   // Avoid turning single icmps into a switch.
3568   if (UsedICmps <= 1)
3569     return false;
3570 
3571   bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3572 
3573   // There might be duplicate constants in the list, which the switch
3574   // instruction can't handle, remove them now.
3575   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3576   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
3577 
3578   // If Extra was used, we require at least two switch values to do the
3579   // transformation.  A switch with one value is just a conditional branch.
3580   if (ExtraCase && Values.size() < 2)
3581     return false;
3582 
3583   // TODO: Preserve branch weight metadata, similarly to how
3584   // FoldValueComparisonIntoPredecessors preserves it.
3585 
3586   // Figure out which block is which destination.
3587   BasicBlock *DefaultBB = BI->getSuccessor(1);
3588   BasicBlock *EdgeBB = BI->getSuccessor(0);
3589   if (!TrueWhenEqual)
3590     std::swap(DefaultBB, EdgeBB);
3591 
3592   BasicBlock *BB = BI->getParent();
3593 
3594   DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
3595                << " cases into SWITCH.  BB is:\n"
3596                << *BB);
3597 
3598   // If there are any extra values that couldn't be folded into the switch
3599   // then we evaluate them with an explicit branch first.  Split the block
3600   // right before the condbr to handle it.
3601   if (ExtraCase) {
3602     BasicBlock *NewBB =
3603         BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
3604     // Remove the uncond branch added to the old block.
3605     TerminatorInst *OldTI = BB->getTerminator();
3606     Builder.SetInsertPoint(OldTI);
3607 
3608     if (TrueWhenEqual)
3609       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
3610     else
3611       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
3612 
3613     OldTI->eraseFromParent();
3614 
3615     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3616     // for the edge we just added.
3617     AddPredecessorToBlock(EdgeBB, BB, NewBB);
3618 
3619     DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
3620                  << "\nEXTRABB = " << *BB);
3621     BB = NewBB;
3622   }
3623 
3624   Builder.SetInsertPoint(BI);
3625   // Convert pointer to int before we switch.
3626   if (CompVal->getType()->isPointerTy()) {
3627     CompVal = Builder.CreatePtrToInt(
3628         CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
3629   }
3630 
3631   // Create the new switch instruction now.
3632   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
3633 
3634   // Add all of the 'cases' to the switch instruction.
3635   for (unsigned i = 0, e = Values.size(); i != e; ++i)
3636     New->addCase(Values[i], EdgeBB);
3637 
3638   // We added edges from PI to the EdgeBB.  As such, if there were any
3639   // PHI nodes in EdgeBB, they need entries to be added corresponding to
3640   // the number of edges added.
3641   for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
3642     PHINode *PN = cast<PHINode>(BBI);
3643     Value *InVal = PN->getIncomingValueForBlock(BB);
3644     for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
3645       PN->addIncoming(InVal, BB);
3646   }
3647 
3648   // Erase the old branch instruction.
3649   EraseTerminatorInstAndDCECond(BI);
3650 
3651   DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
3652   return true;
3653 }
3654 
3655 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
3656   if (isa<PHINode>(RI->getValue()))
3657     return SimplifyCommonResume(RI);
3658   else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3659            RI->getValue() == RI->getParent()->getFirstNonPHI())
3660     // The resume must unwind the exception that caused control to branch here.
3661     return SimplifySingleResume(RI);
3662 
3663   return false;
3664 }
3665 
3666 // Simplify resume that is shared by several landing pads (phi of landing pad).
3667 bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3668   BasicBlock *BB = RI->getParent();
3669 
3670   // Check that there are no other instructions except for debug intrinsics
3671   // between the phi of landing pads (RI->getValue()) and resume instruction.
3672   BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
3673                        E = RI->getIterator();
3674   while (++I != E)
3675     if (!isa<DbgInfoIntrinsic>(I))
3676       return false;
3677 
3678   SmallSet<BasicBlock *, 4> TrivialUnwindBlocks;
3679   auto *PhiLPInst = cast<PHINode>(RI->getValue());
3680 
3681   // Check incoming blocks to see if any of them are trivial.
3682   for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3683        Idx++) {
3684     auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3685     auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3686 
3687     // If the block has other successors, we can not delete it because
3688     // it has other dependents.
3689     if (IncomingBB->getUniqueSuccessor() != BB)
3690       continue;
3691 
3692     auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
3693     // Not the landing pad that caused the control to branch here.
3694     if (IncomingValue != LandingPad)
3695       continue;
3696 
3697     bool isTrivial = true;
3698 
3699     I = IncomingBB->getFirstNonPHI()->getIterator();
3700     E = IncomingBB->getTerminator()->getIterator();
3701     while (++I != E)
3702       if (!isa<DbgInfoIntrinsic>(I)) {
3703         isTrivial = false;
3704         break;
3705       }
3706 
3707     if (isTrivial)
3708       TrivialUnwindBlocks.insert(IncomingBB);
3709   }
3710 
3711   // If no trivial unwind blocks, don't do any simplifications.
3712   if (TrivialUnwindBlocks.empty())
3713     return false;
3714 
3715   // Turn all invokes that unwind here into calls.
3716   for (auto *TrivialBB : TrivialUnwindBlocks) {
3717     // Blocks that will be simplified should be removed from the phi node.
3718     // Note there could be multiple edges to the resume block, and we need
3719     // to remove them all.
3720     while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3721       BB->removePredecessor(TrivialBB, true);
3722 
3723     for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3724          PI != PE;) {
3725       BasicBlock *Pred = *PI++;
3726       removeUnwindEdge(Pred);
3727     }
3728 
3729     // In each SimplifyCFG run, only the current processed block can be erased.
3730     // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3731     // of erasing TrivialBB, we only remove the branch to the common resume
3732     // block so that we can later erase the resume block since it has no
3733     // predecessors.
3734     TrivialBB->getTerminator()->eraseFromParent();
3735     new UnreachableInst(RI->getContext(), TrivialBB);
3736   }
3737 
3738   // Delete the resume block if all its predecessors have been removed.
3739   if (pred_empty(BB))
3740     BB->eraseFromParent();
3741 
3742   return !TrivialUnwindBlocks.empty();
3743 }
3744 
3745 // Simplify resume that is only used by a single (non-phi) landing pad.
3746 bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
3747   BasicBlock *BB = RI->getParent();
3748   LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
3749   assert(RI->getValue() == LPInst &&
3750          "Resume must unwind the exception that caused control to here");
3751 
3752   // Check that there are no other instructions except for debug intrinsics.
3753   BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
3754   while (++I != E)
3755     if (!isa<DbgInfoIntrinsic>(I))
3756       return false;
3757 
3758   // Turn all invokes that unwind here into calls and delete the basic block.
3759   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3760     BasicBlock *Pred = *PI++;
3761     removeUnwindEdge(Pred);
3762   }
3763 
3764   // The landingpad is now unreachable.  Zap it.
3765   BB->eraseFromParent();
3766   if (LoopHeaders)
3767     LoopHeaders->erase(BB);
3768   return true;
3769 }
3770 
3771 static bool removeEmptyCleanup(CleanupReturnInst *RI) {
3772   // If this is a trivial cleanup pad that executes no instructions, it can be
3773   // eliminated.  If the cleanup pad continues to the caller, any predecessor
3774   // that is an EH pad will be updated to continue to the caller and any
3775   // predecessor that terminates with an invoke instruction will have its invoke
3776   // instruction converted to a call instruction.  If the cleanup pad being
3777   // simplified does not continue to the caller, each predecessor will be
3778   // updated to continue to the unwind destination of the cleanup pad being
3779   // simplified.
3780   BasicBlock *BB = RI->getParent();
3781   CleanupPadInst *CPInst = RI->getCleanupPad();
3782   if (CPInst->getParent() != BB)
3783     // This isn't an empty cleanup.
3784     return false;
3785 
3786   // We cannot kill the pad if it has multiple uses.  This typically arises
3787   // from unreachable basic blocks.
3788   if (!CPInst->hasOneUse())
3789     return false;
3790 
3791   // Check that there are no other instructions except for benign intrinsics.
3792   BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
3793   while (++I != E) {
3794     auto *II = dyn_cast<IntrinsicInst>(I);
3795     if (!II)
3796       return false;
3797 
3798     Intrinsic::ID IntrinsicID = II->getIntrinsicID();
3799     switch (IntrinsicID) {
3800     case Intrinsic::dbg_declare:
3801     case Intrinsic::dbg_value:
3802     case Intrinsic::lifetime_end:
3803       break;
3804     default:
3805       return false;
3806     }
3807   }
3808 
3809   // If the cleanup return we are simplifying unwinds to the caller, this will
3810   // set UnwindDest to nullptr.
3811   BasicBlock *UnwindDest = RI->getUnwindDest();
3812   Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
3813 
3814   // We're about to remove BB from the control flow.  Before we do, sink any
3815   // PHINodes into the unwind destination.  Doing this before changing the
3816   // control flow avoids some potentially slow checks, since we can currently
3817   // be certain that UnwindDest and BB have no common predecessors (since they
3818   // are both EH pads).
3819   if (UnwindDest) {
3820     // First, go through the PHI nodes in UnwindDest and update any nodes that
3821     // reference the block we are removing
3822     for (BasicBlock::iterator I = UnwindDest->begin(),
3823                               IE = DestEHPad->getIterator();
3824          I != IE; ++I) {
3825       PHINode *DestPN = cast<PHINode>(I);
3826 
3827       int Idx = DestPN->getBasicBlockIndex(BB);
3828       // Since BB unwinds to UnwindDest, it has to be in the PHI node.
3829       assert(Idx != -1);
3830       // This PHI node has an incoming value that corresponds to a control
3831       // path through the cleanup pad we are removing.  If the incoming
3832       // value is in the cleanup pad, it must be a PHINode (because we
3833       // verified above that the block is otherwise empty).  Otherwise, the
3834       // value is either a constant or a value that dominates the cleanup
3835       // pad being removed.
3836       //
3837       // Because BB and UnwindDest are both EH pads, all of their
3838       // predecessors must unwind to these blocks, and since no instruction
3839       // can have multiple unwind destinations, there will be no overlap in
3840       // incoming blocks between SrcPN and DestPN.
3841       Value *SrcVal = DestPN->getIncomingValue(Idx);
3842       PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3843 
3844       // Remove the entry for the block we are deleting.
3845       DestPN->removeIncomingValue(Idx, false);
3846 
3847       if (SrcPN && SrcPN->getParent() == BB) {
3848         // If the incoming value was a PHI node in the cleanup pad we are
3849         // removing, we need to merge that PHI node's incoming values into
3850         // DestPN.
3851         for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
3852              SrcIdx != SrcE; ++SrcIdx) {
3853           DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3854                               SrcPN->getIncomingBlock(SrcIdx));
3855         }
3856       } else {
3857         // Otherwise, the incoming value came from above BB and
3858         // so we can just reuse it.  We must associate all of BB's
3859         // predecessors with this value.
3860         for (auto *pred : predecessors(BB)) {
3861           DestPN->addIncoming(SrcVal, pred);
3862         }
3863       }
3864     }
3865 
3866     // Sink any remaining PHI nodes directly into UnwindDest.
3867     Instruction *InsertPt = DestEHPad;
3868     for (BasicBlock::iterator I = BB->begin(),
3869                               IE = BB->getFirstNonPHI()->getIterator();
3870          I != IE;) {
3871       // The iterator must be incremented here because the instructions are
3872       // being moved to another block.
3873       PHINode *PN = cast<PHINode>(I++);
3874       if (PN->use_empty())
3875         // If the PHI node has no uses, just leave it.  It will be erased
3876         // when we erase BB below.
3877         continue;
3878 
3879       // Otherwise, sink this PHI node into UnwindDest.
3880       // Any predecessors to UnwindDest which are not already represented
3881       // must be back edges which inherit the value from the path through
3882       // BB.  In this case, the PHI value must reference itself.
3883       for (auto *pred : predecessors(UnwindDest))
3884         if (pred != BB)
3885           PN->addIncoming(PN, pred);
3886       PN->moveBefore(InsertPt);
3887     }
3888   }
3889 
3890   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3891     // The iterator must be updated here because we are removing this pred.
3892     BasicBlock *PredBB = *PI++;
3893     if (UnwindDest == nullptr) {
3894       removeUnwindEdge(PredBB);
3895     } else {
3896       TerminatorInst *TI = PredBB->getTerminator();
3897       TI->replaceUsesOfWith(BB, UnwindDest);
3898     }
3899   }
3900 
3901   // The cleanup pad is now unreachable.  Zap it.
3902   BB->eraseFromParent();
3903   return true;
3904 }
3905 
3906 // Try to merge two cleanuppads together.
3907 static bool mergeCleanupPad(CleanupReturnInst *RI) {
3908   // Skip any cleanuprets which unwind to caller, there is nothing to merge
3909   // with.
3910   BasicBlock *UnwindDest = RI->getUnwindDest();
3911   if (!UnwindDest)
3912     return false;
3913 
3914   // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
3915   // be safe to merge without code duplication.
3916   if (UnwindDest->getSinglePredecessor() != RI->getParent())
3917     return false;
3918 
3919   // Verify that our cleanuppad's unwind destination is another cleanuppad.
3920   auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
3921   if (!SuccessorCleanupPad)
3922     return false;
3923 
3924   CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
3925   // Replace any uses of the successor cleanupad with the predecessor pad
3926   // The only cleanuppad uses should be this cleanupret, it's cleanupret and
3927   // funclet bundle operands.
3928   SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
3929   // Remove the old cleanuppad.
3930   SuccessorCleanupPad->eraseFromParent();
3931   // Now, we simply replace the cleanupret with a branch to the unwind
3932   // destination.
3933   BranchInst::Create(UnwindDest, RI->getParent());
3934   RI->eraseFromParent();
3935 
3936   return true;
3937 }
3938 
3939 bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
3940   // It is possible to transiantly have an undef cleanuppad operand because we
3941   // have deleted some, but not all, dead blocks.
3942   // Eventually, this block will be deleted.
3943   if (isa<UndefValue>(RI->getOperand(0)))
3944     return false;
3945 
3946   if (mergeCleanupPad(RI))
3947     return true;
3948 
3949   if (removeEmptyCleanup(RI))
3950     return true;
3951 
3952   return false;
3953 }
3954 
3955 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
3956   BasicBlock *BB = RI->getParent();
3957   if (!BB->getFirstNonPHIOrDbg()->isTerminator())
3958     return false;
3959 
3960   // Find predecessors that end with branches.
3961   SmallVector<BasicBlock *, 8> UncondBranchPreds;
3962   SmallVector<BranchInst *, 8> CondBranchPreds;
3963   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3964     BasicBlock *P = *PI;
3965     TerminatorInst *PTI = P->getTerminator();
3966     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3967       if (BI->isUnconditional())
3968         UncondBranchPreds.push_back(P);
3969       else
3970         CondBranchPreds.push_back(BI);
3971     }
3972   }
3973 
3974   // If we found some, do the transformation!
3975   if (!UncondBranchPreds.empty() && DupRet) {
3976     while (!UncondBranchPreds.empty()) {
3977       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3978       DEBUG(dbgs() << "FOLDING: " << *BB
3979                    << "INTO UNCOND BRANCH PRED: " << *Pred);
3980       (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
3981     }
3982 
3983     // If we eliminated all predecessors of the block, delete the block now.
3984     if (pred_empty(BB)) {
3985       // We know there are no successors, so just nuke the block.
3986       BB->eraseFromParent();
3987       if (LoopHeaders)
3988         LoopHeaders->erase(BB);
3989     }
3990 
3991     return true;
3992   }
3993 
3994   // Check out all of the conditional branches going to this return
3995   // instruction.  If any of them just select between returns, change the
3996   // branch itself into a select/return pair.
3997   while (!CondBranchPreds.empty()) {
3998     BranchInst *BI = CondBranchPreds.pop_back_val();
3999 
4000     // Check to see if the non-BB successor is also a return block.
4001     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
4002         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
4003         SimplifyCondBranchToTwoReturns(BI, Builder))
4004       return true;
4005   }
4006   return false;
4007 }
4008 
4009 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
4010   BasicBlock *BB = UI->getParent();
4011 
4012   bool Changed = false;
4013 
4014   // If there are any instructions immediately before the unreachable that can
4015   // be removed, do so.
4016   while (UI->getIterator() != BB->begin()) {
4017     BasicBlock::iterator BBI = UI->getIterator();
4018     --BBI;
4019     // Do not delete instructions that can have side effects which might cause
4020     // the unreachable to not be reachable; specifically, calls and volatile
4021     // operations may have this effect.
4022     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4023       break;
4024 
4025     if (BBI->mayHaveSideEffects()) {
4026       if (auto *SI = dyn_cast<StoreInst>(BBI)) {
4027         if (SI->isVolatile())
4028           break;
4029       } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
4030         if (LI->isVolatile())
4031           break;
4032       } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
4033         if (RMWI->isVolatile())
4034           break;
4035       } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
4036         if (CXI->isVolatile())
4037           break;
4038       } else if (isa<CatchPadInst>(BBI)) {
4039         // A catchpad may invoke exception object constructors and such, which
4040         // in some languages can be arbitrary code, so be conservative by
4041         // default.
4042         // For CoreCLR, it just involves a type test, so can be removed.
4043         if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
4044             EHPersonality::CoreCLR)
4045           break;
4046       } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4047                  !isa<LandingPadInst>(BBI)) {
4048         break;
4049       }
4050       // Note that deleting LandingPad's here is in fact okay, although it
4051       // involves a bit of subtle reasoning. If this inst is a LandingPad,
4052       // all the predecessors of this block will be the unwind edges of Invokes,
4053       // and we can therefore guarantee this block will be erased.
4054     }
4055 
4056     // Delete this instruction (any uses are guaranteed to be dead)
4057     if (!BBI->use_empty())
4058       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
4059     BBI->eraseFromParent();
4060     Changed = true;
4061   }
4062 
4063   // If the unreachable instruction is the first in the block, take a gander
4064   // at all of the predecessors of this instruction, and simplify them.
4065   if (&BB->front() != UI)
4066     return Changed;
4067 
4068   SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
4069   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4070     TerminatorInst *TI = Preds[i]->getTerminator();
4071     IRBuilder<> Builder(TI);
4072     if (auto *BI = dyn_cast<BranchInst>(TI)) {
4073       if (BI->isUnconditional()) {
4074         if (BI->getSuccessor(0) == BB) {
4075           new UnreachableInst(TI->getContext(), TI);
4076           TI->eraseFromParent();
4077           Changed = true;
4078         }
4079       } else {
4080         if (BI->getSuccessor(0) == BB) {
4081           Builder.CreateBr(BI->getSuccessor(1));
4082           EraseTerminatorInstAndDCECond(BI);
4083         } else if (BI->getSuccessor(1) == BB) {
4084           Builder.CreateBr(BI->getSuccessor(0));
4085           EraseTerminatorInstAndDCECond(BI);
4086           Changed = true;
4087         }
4088       }
4089     } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
4090       for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e;
4091            ++i)
4092         if (i.getCaseSuccessor() == BB) {
4093           BB->removePredecessor(SI->getParent());
4094           SI->removeCase(i);
4095           --i;
4096           --e;
4097           Changed = true;
4098         }
4099     } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4100       if (II->getUnwindDest() == BB) {
4101         removeUnwindEdge(TI->getParent());
4102         Changed = true;
4103       }
4104     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4105       if (CSI->getUnwindDest() == BB) {
4106         removeUnwindEdge(TI->getParent());
4107         Changed = true;
4108         continue;
4109       }
4110 
4111       for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4112                                              E = CSI->handler_end();
4113            I != E; ++I) {
4114         if (*I == BB) {
4115           CSI->removeHandler(I);
4116           --I;
4117           --E;
4118           Changed = true;
4119         }
4120       }
4121       if (CSI->getNumHandlers() == 0) {
4122         BasicBlock *CatchSwitchBB = CSI->getParent();
4123         if (CSI->hasUnwindDest()) {
4124           // Redirect preds to the unwind dest
4125           CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
4126         } else {
4127           // Rewrite all preds to unwind to caller (or from invoke to call).
4128           SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
4129           for (BasicBlock *EHPred : EHPreds)
4130             removeUnwindEdge(EHPred);
4131         }
4132         // The catchswitch is no longer reachable.
4133         new UnreachableInst(CSI->getContext(), CSI);
4134         CSI->eraseFromParent();
4135         Changed = true;
4136       }
4137     } else if (isa<CleanupReturnInst>(TI)) {
4138       new UnreachableInst(TI->getContext(), TI);
4139       TI->eraseFromParent();
4140       Changed = true;
4141     }
4142   }
4143 
4144   // If this block is now dead, remove it.
4145   if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
4146     // We know there are no successors, so just nuke the block.
4147     BB->eraseFromParent();
4148     if (LoopHeaders)
4149       LoopHeaders->erase(BB);
4150     return true;
4151   }
4152 
4153   return Changed;
4154 }
4155 
4156 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4157   assert(Cases.size() >= 1);
4158 
4159   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4160   for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4161     if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4162       return false;
4163   }
4164   return true;
4165 }
4166 
4167 /// Turn a switch with two reachable destinations into an integer range
4168 /// comparison and branch.
4169 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
4170   assert(SI->getNumCases() > 1 && "Degenerate switch?");
4171 
4172   bool HasDefault =
4173       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4174 
4175   // Partition the cases into two sets with different destinations.
4176   BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4177   BasicBlock *DestB = nullptr;
4178   SmallVector<ConstantInt *, 16> CasesA;
4179   SmallVector<ConstantInt *, 16> CasesB;
4180 
4181   for (SwitchInst::CaseIt I : SI->cases()) {
4182     BasicBlock *Dest = I.getCaseSuccessor();
4183     if (!DestA)
4184       DestA = Dest;
4185     if (Dest == DestA) {
4186       CasesA.push_back(I.getCaseValue());
4187       continue;
4188     }
4189     if (!DestB)
4190       DestB = Dest;
4191     if (Dest == DestB) {
4192       CasesB.push_back(I.getCaseValue());
4193       continue;
4194     }
4195     return false; // More than two destinations.
4196   }
4197 
4198   assert(DestA && DestB &&
4199          "Single-destination switch should have been folded.");
4200   assert(DestA != DestB);
4201   assert(DestB != SI->getDefaultDest());
4202   assert(!CasesB.empty() && "There must be non-default cases.");
4203   assert(!CasesA.empty() || HasDefault);
4204 
4205   // Figure out if one of the sets of cases form a contiguous range.
4206   SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4207   BasicBlock *ContiguousDest = nullptr;
4208   BasicBlock *OtherDest = nullptr;
4209   if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4210     ContiguousCases = &CasesA;
4211     ContiguousDest = DestA;
4212     OtherDest = DestB;
4213   } else if (CasesAreContiguous(CasesB)) {
4214     ContiguousCases = &CasesB;
4215     ContiguousDest = DestB;
4216     OtherDest = DestA;
4217   } else
4218     return false;
4219 
4220   // Start building the compare and branch.
4221 
4222   Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
4223   Constant *NumCases =
4224       ConstantInt::get(Offset->getType(), ContiguousCases->size());
4225 
4226   Value *Sub = SI->getCondition();
4227   if (!Offset->isNullValue())
4228     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4229 
4230   Value *Cmp;
4231   // If NumCases overflowed, then all possible values jump to the successor.
4232   if (NumCases->isNullValue() && !ContiguousCases->empty())
4233     Cmp = ConstantInt::getTrue(SI->getContext());
4234   else
4235     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
4236   BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
4237 
4238   // Update weight for the newly-created conditional branch.
4239   if (HasBranchWeights(SI)) {
4240     SmallVector<uint64_t, 8> Weights;
4241     GetBranchWeights(SI, Weights);
4242     if (Weights.size() == 1 + SI->getNumCases()) {
4243       uint64_t TrueWeight = 0;
4244       uint64_t FalseWeight = 0;
4245       for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4246         if (SI->getSuccessor(I) == ContiguousDest)
4247           TrueWeight += Weights[I];
4248         else
4249           FalseWeight += Weights[I];
4250       }
4251       while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4252         TrueWeight /= 2;
4253         FalseWeight /= 2;
4254       }
4255       NewBI->setMetadata(LLVMContext::MD_prof,
4256                          MDBuilder(SI->getContext())
4257                              .createBranchWeights((uint32_t)TrueWeight,
4258                                                   (uint32_t)FalseWeight));
4259     }
4260   }
4261 
4262   // Prune obsolete incoming values off the successors' PHI nodes.
4263   for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4264     unsigned PreviousEdges = ContiguousCases->size();
4265     if (ContiguousDest == SI->getDefaultDest())
4266       ++PreviousEdges;
4267     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4268       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4269   }
4270   for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4271     unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
4272     if (OtherDest == SI->getDefaultDest())
4273       ++PreviousEdges;
4274     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4275       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4276   }
4277 
4278   // Drop the switch.
4279   SI->eraseFromParent();
4280 
4281   return true;
4282 }
4283 
4284 /// Compute masked bits for the condition of a switch
4285 /// and use it to remove dead cases.
4286 static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
4287                                      const DataLayout &DL) {
4288   Value *Cond = SI->getCondition();
4289   unsigned Bits = Cond->getType()->getIntegerBitWidth();
4290   APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
4291   computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
4292 
4293   // We can also eliminate cases by determining that their values are outside of
4294   // the limited range of the condition based on how many significant (non-sign)
4295   // bits are in the condition value.
4296   unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
4297   unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4298 
4299   // Gather dead cases.
4300   SmallVector<ConstantInt *, 8> DeadCases;
4301   for (auto &Case : SI->cases()) {
4302     APInt CaseVal = Case.getCaseValue()->getValue();
4303     if ((CaseVal & KnownZero) != 0 || (CaseVal & KnownOne) != KnownOne ||
4304         (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
4305       DeadCases.push_back(Case.getCaseValue());
4306       DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal << " is dead.\n");
4307     }
4308   }
4309 
4310   // If we can prove that the cases must cover all possible values, the
4311   // default destination becomes dead and we can remove it.  If we know some
4312   // of the bits in the value, we can use that to more precisely compute the
4313   // number of possible unique case values.
4314   bool HasDefault =
4315       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4316   const unsigned NumUnknownBits =
4317       Bits - (KnownZero.Or(KnownOne)).countPopulation();
4318   assert(NumUnknownBits <= Bits);
4319   if (HasDefault && DeadCases.empty() &&
4320       NumUnknownBits < 64 /* avoid overflow */ &&
4321       SI->getNumCases() == (1ULL << NumUnknownBits)) {
4322     DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
4323     BasicBlock *NewDefault =
4324         SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
4325     SI->setDefaultDest(&*NewDefault);
4326     SplitBlock(&*NewDefault, &NewDefault->front());
4327     auto *OldTI = NewDefault->getTerminator();
4328     new UnreachableInst(SI->getContext(), OldTI);
4329     EraseTerminatorInstAndDCECond(OldTI);
4330     return true;
4331   }
4332 
4333   SmallVector<uint64_t, 8> Weights;
4334   bool HasWeight = HasBranchWeights(SI);
4335   if (HasWeight) {
4336     GetBranchWeights(SI, Weights);
4337     HasWeight = (Weights.size() == 1 + SI->getNumCases());
4338   }
4339 
4340   // Remove dead cases from the switch.
4341   for (ConstantInt *DeadCase : DeadCases) {
4342     SwitchInst::CaseIt Case = SI->findCaseValue(DeadCase);
4343     assert(Case != SI->case_default() &&
4344            "Case was not found. Probably mistake in DeadCases forming.");
4345     if (HasWeight) {
4346       std::swap(Weights[Case.getCaseIndex() + 1], Weights.back());
4347       Weights.pop_back();
4348     }
4349 
4350     // Prune unused values from PHI nodes.
4351     Case.getCaseSuccessor()->removePredecessor(SI->getParent());
4352     SI->removeCase(Case);
4353   }
4354   if (HasWeight && Weights.size() >= 2) {
4355     SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
4356     SI->setMetadata(LLVMContext::MD_prof,
4357                     MDBuilder(SI->getParent()->getContext())
4358                         .createBranchWeights(MDWeights));
4359   }
4360 
4361   return !DeadCases.empty();
4362 }
4363 
4364 /// If BB would be eligible for simplification by
4365 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
4366 /// by an unconditional branch), look at the phi node for BB in the successor
4367 /// block and see if the incoming value is equal to CaseValue. If so, return
4368 /// the phi node, and set PhiIndex to BB's index in the phi node.
4369 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
4370                                               BasicBlock *BB, int *PhiIndex) {
4371   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
4372     return nullptr; // BB must be empty to be a candidate for simplification.
4373   if (!BB->getSinglePredecessor())
4374     return nullptr; // BB must be dominated by the switch.
4375 
4376   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4377   if (!Branch || !Branch->isUnconditional())
4378     return nullptr; // Terminator must be unconditional branch.
4379 
4380   BasicBlock *Succ = Branch->getSuccessor(0);
4381 
4382   BasicBlock::iterator I = Succ->begin();
4383   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4384     int Idx = PHI->getBasicBlockIndex(BB);
4385     assert(Idx >= 0 && "PHI has no entry for predecessor?");
4386 
4387     Value *InValue = PHI->getIncomingValue(Idx);
4388     if (InValue != CaseValue)
4389       continue;
4390 
4391     *PhiIndex = Idx;
4392     return PHI;
4393   }
4394 
4395   return nullptr;
4396 }
4397 
4398 /// Try to forward the condition of a switch instruction to a phi node
4399 /// dominated by the switch, if that would mean that some of the destination
4400 /// blocks of the switch can be folded away.
4401 /// Returns true if a change is made.
4402 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
4403   typedef DenseMap<PHINode *, SmallVector<int, 4>> ForwardingNodesMap;
4404   ForwardingNodesMap ForwardingNodes;
4405 
4406   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E;
4407        ++I) {
4408     ConstantInt *CaseValue = I.getCaseValue();
4409     BasicBlock *CaseDest = I.getCaseSuccessor();
4410 
4411     int PhiIndex;
4412     PHINode *PHI =
4413         FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIndex);
4414     if (!PHI)
4415       continue;
4416 
4417     ForwardingNodes[PHI].push_back(PhiIndex);
4418   }
4419 
4420   bool Changed = false;
4421 
4422   for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
4423                                     E = ForwardingNodes.end();
4424        I != E; ++I) {
4425     PHINode *Phi = I->first;
4426     SmallVectorImpl<int> &Indexes = I->second;
4427 
4428     if (Indexes.size() < 2)
4429       continue;
4430 
4431     for (size_t I = 0, E = Indexes.size(); I != E; ++I)
4432       Phi->setIncomingValue(Indexes[I], SI->getCondition());
4433     Changed = true;
4434   }
4435 
4436   return Changed;
4437 }
4438 
4439 /// Return true if the backend will be able to handle
4440 /// initializing an array of constants like C.
4441 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
4442   if (C->isThreadDependent())
4443     return false;
4444   if (C->isDLLImportDependent())
4445     return false;
4446 
4447   if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
4448       !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
4449       !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
4450     return false;
4451 
4452   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
4453     if (!CE->isGEPWithNoNotionalOverIndexing())
4454       return false;
4455 
4456   if (!TTI.shouldBuildLookupTablesForConstant(C))
4457     return false;
4458 
4459   return true;
4460 }
4461 
4462 /// If V is a Constant, return it. Otherwise, try to look up
4463 /// its constant value in ConstantPool, returning 0 if it's not there.
4464 static Constant *
4465 LookupConstant(Value *V,
4466                const SmallDenseMap<Value *, Constant *> &ConstantPool) {
4467   if (Constant *C = dyn_cast<Constant>(V))
4468     return C;
4469   return ConstantPool.lookup(V);
4470 }
4471 
4472 /// Try to fold instruction I into a constant. This works for
4473 /// simple instructions such as binary operations where both operands are
4474 /// constant or can be replaced by constants from the ConstantPool. Returns the
4475 /// resulting constant on success, 0 otherwise.
4476 static Constant *
4477 ConstantFold(Instruction *I, const DataLayout &DL,
4478              const SmallDenseMap<Value *, Constant *> &ConstantPool) {
4479   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
4480     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4481     if (!A)
4482       return nullptr;
4483     if (A->isAllOnesValue())
4484       return LookupConstant(Select->getTrueValue(), ConstantPool);
4485     if (A->isNullValue())
4486       return LookupConstant(Select->getFalseValue(), ConstantPool);
4487     return nullptr;
4488   }
4489 
4490   SmallVector<Constant *, 4> COps;
4491   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4492     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4493       COps.push_back(A);
4494     else
4495       return nullptr;
4496   }
4497 
4498   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
4499     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4500                                            COps[1], DL);
4501   }
4502 
4503   return ConstantFoldInstOperands(I, COps, DL);
4504 }
4505 
4506 /// Try to determine the resulting constant values in phi nodes
4507 /// at the common destination basic block, *CommonDest, for one of the case
4508 /// destionations CaseDest corresponding to value CaseVal (0 for the default
4509 /// case), of a switch instruction SI.
4510 static bool
4511 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
4512                BasicBlock **CommonDest,
4513                SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
4514                const DataLayout &DL, const TargetTransformInfo &TTI) {
4515   // The block from which we enter the common destination.
4516   BasicBlock *Pred = SI->getParent();
4517 
4518   // If CaseDest is empty except for some side-effect free instructions through
4519   // which we can constant-propagate the CaseVal, continue to its successor.
4520   SmallDenseMap<Value *, Constant *> ConstantPool;
4521   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4522   for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4523        ++I) {
4524     if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4525       // If the terminator is a simple branch, continue to the next block.
4526       if (T->getNumSuccessors() != 1 || T->isExceptional())
4527         return false;
4528       Pred = CaseDest;
4529       CaseDest = T->getSuccessor(0);
4530     } else if (isa<DbgInfoIntrinsic>(I)) {
4531       // Skip debug intrinsic.
4532       continue;
4533     } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
4534       // Instruction is side-effect free and constant.
4535 
4536       // If the instruction has uses outside this block or a phi node slot for
4537       // the block, it is not safe to bypass the instruction since it would then
4538       // no longer dominate all its uses.
4539       for (auto &Use : I->uses()) {
4540         User *User = Use.getUser();
4541         if (Instruction *I = dyn_cast<Instruction>(User))
4542           if (I->getParent() == CaseDest)
4543             continue;
4544         if (PHINode *Phi = dyn_cast<PHINode>(User))
4545           if (Phi->getIncomingBlock(Use) == CaseDest)
4546             continue;
4547         return false;
4548       }
4549 
4550       ConstantPool.insert(std::make_pair(&*I, C));
4551     } else {
4552       break;
4553     }
4554   }
4555 
4556   // If we did not have a CommonDest before, use the current one.
4557   if (!*CommonDest)
4558     *CommonDest = CaseDest;
4559   // If the destination isn't the common one, abort.
4560   if (CaseDest != *CommonDest)
4561     return false;
4562 
4563   // Get the values for this case from phi nodes in the destination block.
4564   BasicBlock::iterator I = (*CommonDest)->begin();
4565   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4566     int Idx = PHI->getBasicBlockIndex(Pred);
4567     if (Idx == -1)
4568       continue;
4569 
4570     Constant *ConstVal =
4571         LookupConstant(PHI->getIncomingValue(Idx), ConstantPool);
4572     if (!ConstVal)
4573       return false;
4574 
4575     // Be conservative about which kinds of constants we support.
4576     if (!ValidLookupTableConstant(ConstVal, TTI))
4577       return false;
4578 
4579     Res.push_back(std::make_pair(PHI, ConstVal));
4580   }
4581 
4582   return Res.size() > 0;
4583 }
4584 
4585 // Helper function used to add CaseVal to the list of cases that generate
4586 // Result.
4587 static void MapCaseToResult(ConstantInt *CaseVal,
4588                             SwitchCaseResultVectorTy &UniqueResults,
4589                             Constant *Result) {
4590   for (auto &I : UniqueResults) {
4591     if (I.first == Result) {
4592       I.second.push_back(CaseVal);
4593       return;
4594     }
4595   }
4596   UniqueResults.push_back(
4597       std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
4598 }
4599 
4600 // Helper function that initializes a map containing
4601 // results for the PHI node of the common destination block for a switch
4602 // instruction. Returns false if multiple PHI nodes have been found or if
4603 // there is not a common destination block for the switch.
4604 static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4605                                   BasicBlock *&CommonDest,
4606                                   SwitchCaseResultVectorTy &UniqueResults,
4607                                   Constant *&DefaultResult,
4608                                   const DataLayout &DL,
4609                                   const TargetTransformInfo &TTI) {
4610   for (auto &I : SI->cases()) {
4611     ConstantInt *CaseVal = I.getCaseValue();
4612 
4613     // Resulting value at phi nodes for this case value.
4614     SwitchCaseResultsTy Results;
4615     if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4616                         DL, TTI))
4617       return false;
4618 
4619     // Only one value per case is permitted
4620     if (Results.size() > 1)
4621       return false;
4622     MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4623 
4624     // Check the PHI consistency.
4625     if (!PHI)
4626       PHI = Results[0].first;
4627     else if (PHI != Results[0].first)
4628       return false;
4629   }
4630   // Find the default result value.
4631   SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4632   BasicBlock *DefaultDest = SI->getDefaultDest();
4633   GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4634                  DL, TTI);
4635   // If the default value is not found abort unless the default destination
4636   // is unreachable.
4637   DefaultResult =
4638       DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4639   if ((!DefaultResult &&
4640        !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4641     return false;
4642 
4643   return true;
4644 }
4645 
4646 // Helper function that checks if it is possible to transform a switch with only
4647 // two cases (or two cases + default) that produces a result into a select.
4648 // Example:
4649 // switch (a) {
4650 //   case 10:                %0 = icmp eq i32 %a, 10
4651 //     return 10;            %1 = select i1 %0, i32 10, i32 4
4652 //   case 20:        ---->   %2 = icmp eq i32 %a, 20
4653 //     return 2;             %3 = select i1 %2, i32 2, i32 %1
4654 //   default:
4655 //     return 4;
4656 // }
4657 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4658                                    Constant *DefaultResult, Value *Condition,
4659                                    IRBuilder<> &Builder) {
4660   assert(ResultVector.size() == 2 &&
4661          "We should have exactly two unique results at this point");
4662   // If we are selecting between only two cases transform into a simple
4663   // select or a two-way select if default is possible.
4664   if (ResultVector[0].second.size() == 1 &&
4665       ResultVector[1].second.size() == 1) {
4666     ConstantInt *const FirstCase = ResultVector[0].second[0];
4667     ConstantInt *const SecondCase = ResultVector[1].second[0];
4668 
4669     bool DefaultCanTrigger = DefaultResult;
4670     Value *SelectValue = ResultVector[1].first;
4671     if (DefaultCanTrigger) {
4672       Value *const ValueCompare =
4673           Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4674       SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4675                                          DefaultResult, "switch.select");
4676     }
4677     Value *const ValueCompare =
4678         Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4679     return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
4680                                 SelectValue, "switch.select");
4681   }
4682 
4683   return nullptr;
4684 }
4685 
4686 // Helper function to cleanup a switch instruction that has been converted into
4687 // a select, fixing up PHI nodes and basic blocks.
4688 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4689                                               Value *SelectValue,
4690                                               IRBuilder<> &Builder) {
4691   BasicBlock *SelectBB = SI->getParent();
4692   while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4693     PHI->removeIncomingValue(SelectBB);
4694   PHI->addIncoming(SelectValue, SelectBB);
4695 
4696   Builder.CreateBr(PHI->getParent());
4697 
4698   // Remove the switch.
4699   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4700     BasicBlock *Succ = SI->getSuccessor(i);
4701 
4702     if (Succ == PHI->getParent())
4703       continue;
4704     Succ->removePredecessor(SelectBB);
4705   }
4706   SI->eraseFromParent();
4707 }
4708 
4709 /// If the switch is only used to initialize one or more
4710 /// phi nodes in a common successor block with only two different
4711 /// constant values, replace the switch with select.
4712 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
4713                            AssumptionCache *AC, const DataLayout &DL,
4714                            const TargetTransformInfo &TTI) {
4715   Value *const Cond = SI->getCondition();
4716   PHINode *PHI = nullptr;
4717   BasicBlock *CommonDest = nullptr;
4718   Constant *DefaultResult;
4719   SwitchCaseResultVectorTy UniqueResults;
4720   // Collect all the cases that will deliver the same value from the switch.
4721   if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4722                              DL, TTI))
4723     return false;
4724   // Selects choose between maximum two values.
4725   if (UniqueResults.size() != 2)
4726     return false;
4727   assert(PHI != nullptr && "PHI for value select not found");
4728 
4729   Builder.SetInsertPoint(SI);
4730   Value *SelectValue =
4731       ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
4732   if (SelectValue) {
4733     RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4734     return true;
4735   }
4736   // The switch couldn't be converted into a select.
4737   return false;
4738 }
4739 
4740 namespace {
4741 /// This class represents a lookup table that can be used to replace a switch.
4742 class SwitchLookupTable {
4743 public:
4744   /// Create a lookup table to use as a switch replacement with the contents
4745   /// of Values, using DefaultValue to fill any holes in the table.
4746   SwitchLookupTable(
4747       Module &M, uint64_t TableSize, ConstantInt *Offset,
4748       const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4749       Constant *DefaultValue, const DataLayout &DL);
4750 
4751   /// Build instructions with Builder to retrieve the value at
4752   /// the position given by Index in the lookup table.
4753   Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
4754 
4755   /// Return true if a table with TableSize elements of
4756   /// type ElementType would fit in a target-legal register.
4757   static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
4758                                  Type *ElementType);
4759 
4760 private:
4761   // Depending on the contents of the table, it can be represented in
4762   // different ways.
4763   enum {
4764     // For tables where each element contains the same value, we just have to
4765     // store that single value and return it for each lookup.
4766     SingleValueKind,
4767 
4768     // For tables where there is a linear relationship between table index
4769     // and values. We calculate the result with a simple multiplication
4770     // and addition instead of a table lookup.
4771     LinearMapKind,
4772 
4773     // For small tables with integer elements, we can pack them into a bitmap
4774     // that fits into a target-legal register. Values are retrieved by
4775     // shift and mask operations.
4776     BitMapKind,
4777 
4778     // The table is stored as an array of values. Values are retrieved by load
4779     // instructions from the table.
4780     ArrayKind
4781   } Kind;
4782 
4783   // For SingleValueKind, this is the single value.
4784   Constant *SingleValue;
4785 
4786   // For BitMapKind, this is the bitmap.
4787   ConstantInt *BitMap;
4788   IntegerType *BitMapElementTy;
4789 
4790   // For LinearMapKind, these are the constants used to derive the value.
4791   ConstantInt *LinearOffset;
4792   ConstantInt *LinearMultiplier;
4793 
4794   // For ArrayKind, this is the array.
4795   GlobalVariable *Array;
4796 };
4797 }
4798 
4799 SwitchLookupTable::SwitchLookupTable(
4800     Module &M, uint64_t TableSize, ConstantInt *Offset,
4801     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4802     Constant *DefaultValue, const DataLayout &DL)
4803     : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
4804       LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
4805   assert(Values.size() && "Can't build lookup table without values!");
4806   assert(TableSize >= Values.size() && "Can't fit values in table!");
4807 
4808   // If all values in the table are equal, this is that value.
4809   SingleValue = Values.begin()->second;
4810 
4811   Type *ValueType = Values.begin()->second->getType();
4812 
4813   // Build up the table contents.
4814   SmallVector<Constant *, 64> TableContents(TableSize);
4815   for (size_t I = 0, E = Values.size(); I != E; ++I) {
4816     ConstantInt *CaseVal = Values[I].first;
4817     Constant *CaseRes = Values[I].second;
4818     assert(CaseRes->getType() == ValueType);
4819 
4820     uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
4821     TableContents[Idx] = CaseRes;
4822 
4823     if (CaseRes != SingleValue)
4824       SingleValue = nullptr;
4825   }
4826 
4827   // Fill in any holes in the table with the default result.
4828   if (Values.size() < TableSize) {
4829     assert(DefaultValue &&
4830            "Need a default value to fill the lookup table holes.");
4831     assert(DefaultValue->getType() == ValueType);
4832     for (uint64_t I = 0; I < TableSize; ++I) {
4833       if (!TableContents[I])
4834         TableContents[I] = DefaultValue;
4835     }
4836 
4837     if (DefaultValue != SingleValue)
4838       SingleValue = nullptr;
4839   }
4840 
4841   // If each element in the table contains the same value, we only need to store
4842   // that single value.
4843   if (SingleValue) {
4844     Kind = SingleValueKind;
4845     return;
4846   }
4847 
4848   // Check if we can derive the value with a linear transformation from the
4849   // table index.
4850   if (isa<IntegerType>(ValueType)) {
4851     bool LinearMappingPossible = true;
4852     APInt PrevVal;
4853     APInt DistToPrev;
4854     assert(TableSize >= 2 && "Should be a SingleValue table.");
4855     // Check if there is the same distance between two consecutive values.
4856     for (uint64_t I = 0; I < TableSize; ++I) {
4857       ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4858       if (!ConstVal) {
4859         // This is an undef. We could deal with it, but undefs in lookup tables
4860         // are very seldom. It's probably not worth the additional complexity.
4861         LinearMappingPossible = false;
4862         break;
4863       }
4864       APInt Val = ConstVal->getValue();
4865       if (I != 0) {
4866         APInt Dist = Val - PrevVal;
4867         if (I == 1) {
4868           DistToPrev = Dist;
4869         } else if (Dist != DistToPrev) {
4870           LinearMappingPossible = false;
4871           break;
4872         }
4873       }
4874       PrevVal = Val;
4875     }
4876     if (LinearMappingPossible) {
4877       LinearOffset = cast<ConstantInt>(TableContents[0]);
4878       LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4879       Kind = LinearMapKind;
4880       ++NumLinearMaps;
4881       return;
4882     }
4883   }
4884 
4885   // If the type is integer and the table fits in a register, build a bitmap.
4886   if (WouldFitInRegister(DL, TableSize, ValueType)) {
4887     IntegerType *IT = cast<IntegerType>(ValueType);
4888     APInt TableInt(TableSize * IT->getBitWidth(), 0);
4889     for (uint64_t I = TableSize; I > 0; --I) {
4890       TableInt <<= IT->getBitWidth();
4891       // Insert values into the bitmap. Undef values are set to zero.
4892       if (!isa<UndefValue>(TableContents[I - 1])) {
4893         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4894         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4895       }
4896     }
4897     BitMap = ConstantInt::get(M.getContext(), TableInt);
4898     BitMapElementTy = IT;
4899     Kind = BitMapKind;
4900     ++NumBitMaps;
4901     return;
4902   }
4903 
4904   // Store the table in an array.
4905   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
4906   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4907 
4908   Array = new GlobalVariable(M, ArrayTy, /*constant=*/true,
4909                              GlobalVariable::PrivateLinkage, Initializer,
4910                              "switch.table");
4911   Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
4912   Kind = ArrayKind;
4913 }
4914 
4915 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
4916   switch (Kind) {
4917   case SingleValueKind:
4918     return SingleValue;
4919   case LinearMapKind: {
4920     // Derive the result value from the input value.
4921     Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4922                                           false, "switch.idx.cast");
4923     if (!LinearMultiplier->isOne())
4924       Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4925     if (!LinearOffset->isZero())
4926       Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4927     return Result;
4928   }
4929   case BitMapKind: {
4930     // Type of the bitmap (e.g. i59).
4931     IntegerType *MapTy = BitMap->getType();
4932 
4933     // Cast Index to the same type as the bitmap.
4934     // Note: The Index is <= the number of elements in the table, so
4935     // truncating it to the width of the bitmask is safe.
4936     Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
4937 
4938     // Multiply the shift amount by the element width.
4939     ShiftAmt = Builder.CreateMul(
4940         ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4941         "switch.shiftamt");
4942 
4943     // Shift down.
4944     Value *DownShifted =
4945         Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
4946     // Mask off.
4947     return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
4948   }
4949   case ArrayKind: {
4950     // Make sure the table index will not overflow when treated as signed.
4951     IntegerType *IT = cast<IntegerType>(Index->getType());
4952     uint64_t TableSize =
4953         Array->getInitializer()->getType()->getArrayNumElements();
4954     if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4955       Index = Builder.CreateZExt(
4956           Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
4957           "switch.tableidx.zext");
4958 
4959     Value *GEPIndices[] = {Builder.getInt32(0), Index};
4960     Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4961                                            GEPIndices, "switch.gep");
4962     return Builder.CreateLoad(GEP, "switch.load");
4963   }
4964   }
4965   llvm_unreachable("Unknown lookup table kind!");
4966 }
4967 
4968 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
4969                                            uint64_t TableSize,
4970                                            Type *ElementType) {
4971   auto *IT = dyn_cast<IntegerType>(ElementType);
4972   if (!IT)
4973     return false;
4974   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4975   // are <= 15, we could try to narrow the type.
4976 
4977   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4978   if (TableSize >= UINT_MAX / IT->getBitWidth())
4979     return false;
4980   return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
4981 }
4982 
4983 /// Determine whether a lookup table should be built for this switch, based on
4984 /// the number of cases, size of the table, and the types of the results.
4985 static bool
4986 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4987                        const TargetTransformInfo &TTI, const DataLayout &DL,
4988                        const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
4989   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4990     return false; // TableSize overflowed, or mul below might overflow.
4991 
4992   bool AllTablesFitInRegister = true;
4993   bool HasIllegalType = false;
4994   for (const auto &I : ResultTypes) {
4995     Type *Ty = I.second;
4996 
4997     // Saturate this flag to true.
4998     HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
4999 
5000     // Saturate this flag to false.
5001     AllTablesFitInRegister =
5002         AllTablesFitInRegister &&
5003         SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5004 
5005     // If both flags saturate, we're done. NOTE: This *only* works with
5006     // saturating flags, and all flags have to saturate first due to the
5007     // non-deterministic behavior of iterating over a dense map.
5008     if (HasIllegalType && !AllTablesFitInRegister)
5009       break;
5010   }
5011 
5012   // If each table would fit in a register, we should build it anyway.
5013   if (AllTablesFitInRegister)
5014     return true;
5015 
5016   // Don't build a table that doesn't fit in-register if it has illegal types.
5017   if (HasIllegalType)
5018     return false;
5019 
5020   // The table density should be at least 40%. This is the same criterion as for
5021   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
5022   // FIXME: Find the best cut-off.
5023   return SI->getNumCases() * 10 >= TableSize * 4;
5024 }
5025 
5026 /// Try to reuse the switch table index compare. Following pattern:
5027 /// \code
5028 ///     if (idx < tablesize)
5029 ///        r = table[idx]; // table does not contain default_value
5030 ///     else
5031 ///        r = default_value;
5032 ///     if (r != default_value)
5033 ///        ...
5034 /// \endcode
5035 /// Is optimized to:
5036 /// \code
5037 ///     cond = idx < tablesize;
5038 ///     if (cond)
5039 ///        r = table[idx];
5040 ///     else
5041 ///        r = default_value;
5042 ///     if (cond)
5043 ///        ...
5044 /// \endcode
5045 /// Jump threading will then eliminate the second if(cond).
5046 static void reuseTableCompare(
5047     User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
5048     Constant *DefaultValue,
5049     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5050 
5051   ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
5052   if (!CmpInst)
5053     return;
5054 
5055   // We require that the compare is in the same block as the phi so that jump
5056   // threading can do its work afterwards.
5057   if (CmpInst->getParent() != PhiBlock)
5058     return;
5059 
5060   Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5061   if (!CmpOp1)
5062     return;
5063 
5064   Value *RangeCmp = RangeCheckBranch->getCondition();
5065   Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5066   Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5067 
5068   // Check if the compare with the default value is constant true or false.
5069   Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5070                                                  DefaultValue, CmpOp1, true);
5071   if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5072     return;
5073 
5074   // Check if the compare with the case values is distinct from the default
5075   // compare result.
5076   for (auto ValuePair : Values) {
5077     Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5078                                                 ValuePair.second, CmpOp1, true);
5079     if (!CaseConst || CaseConst == DefaultConst)
5080       return;
5081     assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5082            "Expect true or false as compare result.");
5083   }
5084 
5085   // Check if the branch instruction dominates the phi node. It's a simple
5086   // dominance check, but sufficient for our needs.
5087   // Although this check is invariant in the calling loops, it's better to do it
5088   // at this late stage. Practically we do it at most once for a switch.
5089   BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5090   for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
5091     BasicBlock *Pred = *PI;
5092     if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5093       return;
5094   }
5095 
5096   if (DefaultConst == FalseConst) {
5097     // The compare yields the same result. We can replace it.
5098     CmpInst->replaceAllUsesWith(RangeCmp);
5099     ++NumTableCmpReuses;
5100   } else {
5101     // The compare yields the same result, just inverted. We can replace it.
5102     Value *InvertedTableCmp = BinaryOperator::CreateXor(
5103         RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5104         RangeCheckBranch);
5105     CmpInst->replaceAllUsesWith(InvertedTableCmp);
5106     ++NumTableCmpReuses;
5107   }
5108 }
5109 
5110 /// If the switch is only used to initialize one or more phi nodes in a common
5111 /// successor block with different constant values, replace the switch with
5112 /// lookup tables.
5113 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5114                                 const DataLayout &DL,
5115                                 const TargetTransformInfo &TTI) {
5116   assert(SI->getNumCases() > 1 && "Degenerate switch?");
5117 
5118   // Only build lookup table when we have a target that supports it.
5119   if (!TTI.shouldBuildLookupTables())
5120     return false;
5121 
5122   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5123   // split off a dense part and build a lookup table for that.
5124 
5125   // FIXME: This creates arrays of GEPs to constant strings, which means each
5126   // GEP needs a runtime relocation in PIC code. We should just build one big
5127   // string and lookup indices into that.
5128 
5129   // Ignore switches with less than three cases. Lookup tables will not make
5130   // them
5131   // faster, so we don't analyze them.
5132   if (SI->getNumCases() < 3)
5133     return false;
5134 
5135   // Figure out the corresponding result for each case value and phi node in the
5136   // common destination, as well as the min and max case values.
5137   assert(SI->case_begin() != SI->case_end());
5138   SwitchInst::CaseIt CI = SI->case_begin();
5139   ConstantInt *MinCaseVal = CI.getCaseValue();
5140   ConstantInt *MaxCaseVal = CI.getCaseValue();
5141 
5142   BasicBlock *CommonDest = nullptr;
5143   typedef SmallVector<std::pair<ConstantInt *, Constant *>, 4> ResultListTy;
5144   SmallDenseMap<PHINode *, ResultListTy> ResultLists;
5145   SmallDenseMap<PHINode *, Constant *> DefaultResults;
5146   SmallDenseMap<PHINode *, Type *> ResultTypes;
5147   SmallVector<PHINode *, 4> PHIs;
5148 
5149   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
5150     ConstantInt *CaseVal = CI.getCaseValue();
5151     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5152       MinCaseVal = CaseVal;
5153     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5154       MaxCaseVal = CaseVal;
5155 
5156     // Resulting value at phi nodes for this case value.
5157     typedef SmallVector<std::pair<PHINode *, Constant *>, 4> ResultsTy;
5158     ResultsTy Results;
5159     if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
5160                         Results, DL, TTI))
5161       return false;
5162 
5163     // Append the result from this case to the list for each phi.
5164     for (const auto &I : Results) {
5165       PHINode *PHI = I.first;
5166       Constant *Value = I.second;
5167       if (!ResultLists.count(PHI))
5168         PHIs.push_back(PHI);
5169       ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5170     }
5171   }
5172 
5173   // Keep track of the result types.
5174   for (PHINode *PHI : PHIs) {
5175     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5176   }
5177 
5178   uint64_t NumResults = ResultLists[PHIs[0]].size();
5179   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5180   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5181   bool TableHasHoles = (NumResults < TableSize);
5182 
5183   // If the table has holes, we need a constant result for the default case
5184   // or a bitmask that fits in a register.
5185   SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
5186   bool HasDefaultResults =
5187       GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
5188                      DefaultResultsList, DL, TTI);
5189 
5190   bool NeedMask = (TableHasHoles && !HasDefaultResults);
5191   if (NeedMask) {
5192     // As an extra penalty for the validity test we require more cases.
5193     if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
5194       return false;
5195     if (!DL.fitsInLegalInteger(TableSize))
5196       return false;
5197   }
5198 
5199   for (const auto &I : DefaultResultsList) {
5200     PHINode *PHI = I.first;
5201     Constant *Result = I.second;
5202     DefaultResults[PHI] = Result;
5203   }
5204 
5205   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
5206     return false;
5207 
5208   // Create the BB that does the lookups.
5209   Module &Mod = *CommonDest->getParent()->getParent();
5210   BasicBlock *LookupBB = BasicBlock::Create(
5211       Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
5212 
5213   // Compute the table index value.
5214   Builder.SetInsertPoint(SI);
5215   Value *TableIndex =
5216       Builder.CreateSub(SI->getCondition(), MinCaseVal, "switch.tableidx");
5217 
5218   // Compute the maximum table size representable by the integer type we are
5219   // switching upon.
5220   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
5221   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
5222   assert(MaxTableSize >= TableSize &&
5223          "It is impossible for a switch to have more entries than the max "
5224          "representable value of its input integer type's size.");
5225 
5226   // If the default destination is unreachable, or if the lookup table covers
5227   // all values of the conditional variable, branch directly to the lookup table
5228   // BB. Otherwise, check that the condition is within the case range.
5229   const bool DefaultIsReachable =
5230       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5231   const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
5232   BranchInst *RangeCheckBranch = nullptr;
5233 
5234   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5235     Builder.CreateBr(LookupBB);
5236     // Note: We call removeProdecessor later since we need to be able to get the
5237     // PHI value for the default case in case we're using a bit mask.
5238   } else {
5239     Value *Cmp = Builder.CreateICmpULT(
5240         TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5241     RangeCheckBranch =
5242         Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
5243   }
5244 
5245   // Populate the BB that does the lookups.
5246   Builder.SetInsertPoint(LookupBB);
5247 
5248   if (NeedMask) {
5249     // Before doing the lookup we do the hole check.
5250     // The LookupBB is therefore re-purposed to do the hole check
5251     // and we create a new LookupBB.
5252     BasicBlock *MaskBB = LookupBB;
5253     MaskBB->setName("switch.hole_check");
5254     LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5255                                   CommonDest->getParent(), CommonDest);
5256 
5257     // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
5258     // unnecessary illegal types.
5259     uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5260     APInt MaskInt(TableSizePowOf2, 0);
5261     APInt One(TableSizePowOf2, 1);
5262     // Build bitmask; fill in a 1 bit for every case.
5263     const ResultListTy &ResultList = ResultLists[PHIs[0]];
5264     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
5265       uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5266                          .getLimitedValue();
5267       MaskInt |= One << Idx;
5268     }
5269     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5270 
5271     // Get the TableIndex'th bit of the bitmask.
5272     // If this bit is 0 (meaning hole) jump to the default destination,
5273     // else continue with table lookup.
5274     IntegerType *MapTy = TableMask->getType();
5275     Value *MaskIndex =
5276         Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5277     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5278     Value *LoBit = Builder.CreateTrunc(
5279         Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
5280     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5281 
5282     Builder.SetInsertPoint(LookupBB);
5283     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
5284   }
5285 
5286   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5287     // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
5288     // do not delete PHINodes here.
5289     SI->getDefaultDest()->removePredecessor(SI->getParent(),
5290                                             /*DontDeleteUselessPHIs=*/true);
5291   }
5292 
5293   bool ReturnedEarly = false;
5294   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
5295     PHINode *PHI = PHIs[I];
5296     const ResultListTy &ResultList = ResultLists[PHI];
5297 
5298     // If using a bitmask, use any value to fill the lookup table holes.
5299     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
5300     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
5301 
5302     Value *Result = Table.BuildLookup(TableIndex, Builder);
5303 
5304     // If the result is used to return immediately from the function, we want to
5305     // do that right here.
5306     if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5307         PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
5308       Builder.CreateRet(Result);
5309       ReturnedEarly = true;
5310       break;
5311     }
5312 
5313     // Do a small peephole optimization: re-use the switch table compare if
5314     // possible.
5315     if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5316       BasicBlock *PhiBlock = PHI->getParent();
5317       // Search for compare instructions which use the phi.
5318       for (auto *User : PHI->users()) {
5319         reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5320       }
5321     }
5322 
5323     PHI->addIncoming(Result, LookupBB);
5324   }
5325 
5326   if (!ReturnedEarly)
5327     Builder.CreateBr(CommonDest);
5328 
5329   // Remove the switch.
5330   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5331     BasicBlock *Succ = SI->getSuccessor(i);
5332 
5333     if (Succ == SI->getDefaultDest())
5334       continue;
5335     Succ->removePredecessor(SI->getParent());
5336   }
5337   SI->eraseFromParent();
5338 
5339   ++NumLookupTables;
5340   if (NeedMask)
5341     ++NumLookupTablesHoles;
5342   return true;
5343 }
5344 
5345 static bool isSwitchDense(ArrayRef<int64_t> Values) {
5346   // See also SelectionDAGBuilder::isDense(), which this function was based on.
5347   uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5348   uint64_t Range = Diff + 1;
5349   uint64_t NumCases = Values.size();
5350   // 40% is the default density for building a jump table in optsize/minsize mode.
5351   uint64_t MinDensity = 40;
5352 
5353   return NumCases * 100 >= Range * MinDensity;
5354 }
5355 
5356 // Try and transform a switch that has "holes" in it to a contiguous sequence
5357 // of cases.
5358 //
5359 // A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5360 // range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5361 //
5362 // This converts a sparse switch into a dense switch which allows better
5363 // lowering and could also allow transforming into a lookup table.
5364 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5365                               const DataLayout &DL,
5366                               const TargetTransformInfo &TTI) {
5367   auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5368   if (CondTy->getIntegerBitWidth() > 64 ||
5369       !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5370     return false;
5371   // Only bother with this optimization if there are more than 3 switch cases;
5372   // SDAG will only bother creating jump tables for 4 or more cases.
5373   if (SI->getNumCases() < 4)
5374     return false;
5375 
5376   // This transform is agnostic to the signedness of the input or case values. We
5377   // can treat the case values as signed or unsigned. We can optimize more common
5378   // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5379   // as signed.
5380   SmallVector<int64_t,4> Values;
5381   for (auto &C : SI->cases())
5382     Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5383   std::sort(Values.begin(), Values.end());
5384 
5385   // If the switch is already dense, there's nothing useful to do here.
5386   if (isSwitchDense(Values))
5387     return false;
5388 
5389   // First, transform the values such that they start at zero and ascend.
5390   int64_t Base = Values[0];
5391   for (auto &V : Values)
5392     V -= Base;
5393 
5394   // Now we have signed numbers that have been shifted so that, given enough
5395   // precision, there are no negative values. Since the rest of the transform
5396   // is bitwise only, we switch now to an unsigned representation.
5397   uint64_t GCD = 0;
5398   for (auto &V : Values)
5399     GCD = llvm::GreatestCommonDivisor64(GCD, (uint64_t)V);
5400 
5401   // This transform can be done speculatively because it is so cheap - it results
5402   // in a single rotate operation being inserted. This can only happen if the
5403   // factor extracted is a power of 2.
5404   // FIXME: If the GCD is an odd number we can multiply by the multiplicative
5405   // inverse of GCD and then perform this transform.
5406   // FIXME: It's possible that optimizing a switch on powers of two might also
5407   // be beneficial - flag values are often powers of two and we could use a CLZ
5408   // as the key function.
5409   if (GCD <= 1 || !llvm::isPowerOf2_64(GCD))
5410     // No common divisor found or too expensive to compute key function.
5411     return false;
5412 
5413   unsigned Shift = llvm::Log2_64(GCD);
5414   for (auto &V : Values)
5415     V = (int64_t)((uint64_t)V >> Shift);
5416 
5417   if (!isSwitchDense(Values))
5418     // Transform didn't create a dense switch.
5419     return false;
5420 
5421   // The obvious transform is to shift the switch condition right and emit a
5422   // check that the condition actually cleanly divided by GCD, i.e.
5423   //   C & (1 << Shift - 1) == 0
5424   // inserting a new CFG edge to handle the case where it didn't divide cleanly.
5425   //
5426   // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
5427   // shift and puts the shifted-off bits in the uppermost bits. If any of these
5428   // are nonzero then the switch condition will be very large and will hit the
5429   // default case.
5430 
5431   auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
5432   Builder.SetInsertPoint(SI);
5433   auto *ShiftC = ConstantInt::get(Ty, Shift);
5434   auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
5435   auto *LShr = Builder.CreateLShr(Sub, ShiftC);
5436   auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
5437   auto *Rot = Builder.CreateOr(LShr, Shl);
5438   SI->replaceUsesOfWith(SI->getCondition(), Rot);
5439 
5440   for (SwitchInst::CaseIt C = SI->case_begin(), E = SI->case_end(); C != E;
5441        ++C) {
5442     auto *Orig = C.getCaseValue();
5443     auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
5444     C.setValue(
5445         cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
5446   }
5447   return true;
5448 }
5449 
5450 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
5451   BasicBlock *BB = SI->getParent();
5452 
5453   if (isValueEqualityComparison(SI)) {
5454     // If we only have one predecessor, and if it is a branch on this value,
5455     // see if that predecessor totally determines the outcome of this switch.
5456     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5457       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
5458         return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5459 
5460     Value *Cond = SI->getCondition();
5461     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
5462       if (SimplifySwitchOnSelect(SI, Select))
5463         return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5464 
5465     // If the block only contains the switch, see if we can fold the block
5466     // away into any preds.
5467     BasicBlock::iterator BBI = BB->begin();
5468     // Ignore dbg intrinsics.
5469     while (isa<DbgInfoIntrinsic>(BBI))
5470       ++BBI;
5471     if (SI == &*BBI)
5472       if (FoldValueComparisonIntoPredecessors(SI, Builder))
5473         return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5474   }
5475 
5476   // Try to transform the switch into an icmp and a branch.
5477   if (TurnSwitchRangeIntoICmp(SI, Builder))
5478     return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5479 
5480   // Remove unreachable cases.
5481   if (EliminateDeadSwitchCases(SI, AC, DL))
5482     return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5483 
5484   if (SwitchToSelect(SI, Builder, AC, DL, TTI))
5485     return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5486 
5487   if (ForwardSwitchConditionToPHI(SI))
5488     return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5489 
5490   if (SwitchToLookupTable(SI, Builder, DL, TTI))
5491     return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5492 
5493   if (ReduceSwitchRange(SI, Builder, DL, TTI))
5494     return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5495 
5496   return false;
5497 }
5498 
5499 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
5500   BasicBlock *BB = IBI->getParent();
5501   bool Changed = false;
5502 
5503   // Eliminate redundant destinations.
5504   SmallPtrSet<Value *, 8> Succs;
5505   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
5506     BasicBlock *Dest = IBI->getDestination(i);
5507     if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
5508       Dest->removePredecessor(BB);
5509       IBI->removeDestination(i);
5510       --i;
5511       --e;
5512       Changed = true;
5513     }
5514   }
5515 
5516   if (IBI->getNumDestinations() == 0) {
5517     // If the indirectbr has no successors, change it to unreachable.
5518     new UnreachableInst(IBI->getContext(), IBI);
5519     EraseTerminatorInstAndDCECond(IBI);
5520     return true;
5521   }
5522 
5523   if (IBI->getNumDestinations() == 1) {
5524     // If the indirectbr has one successor, change it to a direct branch.
5525     BranchInst::Create(IBI->getDestination(0), IBI);
5526     EraseTerminatorInstAndDCECond(IBI);
5527     return true;
5528   }
5529 
5530   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
5531     if (SimplifyIndirectBrOnSelect(IBI, SI))
5532       return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5533   }
5534   return Changed;
5535 }
5536 
5537 /// Given an block with only a single landing pad and a unconditional branch
5538 /// try to find another basic block which this one can be merged with.  This
5539 /// handles cases where we have multiple invokes with unique landing pads, but
5540 /// a shared handler.
5541 ///
5542 /// We specifically choose to not worry about merging non-empty blocks
5543 /// here.  That is a PRE/scheduling problem and is best solved elsewhere.  In
5544 /// practice, the optimizer produces empty landing pad blocks quite frequently
5545 /// when dealing with exception dense code.  (see: instcombine, gvn, if-else
5546 /// sinking in this file)
5547 ///
5548 /// This is primarily a code size optimization.  We need to avoid performing
5549 /// any transform which might inhibit optimization (such as our ability to
5550 /// specialize a particular handler via tail commoning).  We do this by not
5551 /// merging any blocks which require us to introduce a phi.  Since the same
5552 /// values are flowing through both blocks, we don't loose any ability to
5553 /// specialize.  If anything, we make such specialization more likely.
5554 ///
5555 /// TODO - This transformation could remove entries from a phi in the target
5556 /// block when the inputs in the phi are the same for the two blocks being
5557 /// merged.  In some cases, this could result in removal of the PHI entirely.
5558 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5559                                  BasicBlock *BB) {
5560   auto Succ = BB->getUniqueSuccessor();
5561   assert(Succ);
5562   // If there's a phi in the successor block, we'd likely have to introduce
5563   // a phi into the merged landing pad block.
5564   if (isa<PHINode>(*Succ->begin()))
5565     return false;
5566 
5567   for (BasicBlock *OtherPred : predecessors(Succ)) {
5568     if (BB == OtherPred)
5569       continue;
5570     BasicBlock::iterator I = OtherPred->begin();
5571     LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5572     if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5573       continue;
5574     for (++I; isa<DbgInfoIntrinsic>(I); ++I) {
5575     }
5576     BranchInst *BI2 = dyn_cast<BranchInst>(I);
5577     if (!BI2 || !BI2->isIdenticalTo(BI))
5578       continue;
5579 
5580     // We've found an identical block.  Update our predecessors to take that
5581     // path instead and make ourselves dead.
5582     SmallSet<BasicBlock *, 16> Preds;
5583     Preds.insert(pred_begin(BB), pred_end(BB));
5584     for (BasicBlock *Pred : Preds) {
5585       InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
5586       assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
5587              "unexpected successor");
5588       II->setUnwindDest(OtherPred);
5589     }
5590 
5591     // The debug info in OtherPred doesn't cover the merged control flow that
5592     // used to go through BB.  We need to delete it or update it.
5593     for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
5594       Instruction &Inst = *I;
5595       I++;
5596       if (isa<DbgInfoIntrinsic>(Inst))
5597         Inst.eraseFromParent();
5598     }
5599 
5600     SmallSet<BasicBlock *, 16> Succs;
5601     Succs.insert(succ_begin(BB), succ_end(BB));
5602     for (BasicBlock *Succ : Succs) {
5603       Succ->removePredecessor(BB);
5604     }
5605 
5606     IRBuilder<> Builder(BI);
5607     Builder.CreateUnreachable();
5608     BI->eraseFromParent();
5609     return true;
5610   }
5611   return false;
5612 }
5613 
5614 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
5615                                           IRBuilder<> &Builder) {
5616   BasicBlock *BB = BI->getParent();
5617 
5618   if (SinkCommon && SinkThenElseCodeToEnd(BI))
5619     return true;
5620 
5621   // If the Terminator is the only non-phi instruction, simplify the block.
5622   // if LoopHeader is provided, check if the block is a loop header
5623   // (This is for early invocations before loop simplify and vectorization
5624   // to keep canonical loop forms for nested loops.
5625   // These blocks can be eliminated when the pass is invoked later
5626   // in the back-end.)
5627   BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
5628   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
5629       (!LoopHeaders || !LoopHeaders->count(BB)) &&
5630       TryToSimplifyUncondBranchFromEmptyBlock(BB))
5631     return true;
5632 
5633   // If the only instruction in the block is a seteq/setne comparison
5634   // against a constant, try to simplify the block.
5635   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5636     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5637       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5638         ;
5639       if (I->isTerminator() &&
5640           TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
5641                                                 BonusInstThreshold, AC))
5642         return true;
5643     }
5644 
5645   // See if we can merge an empty landing pad block with another which is
5646   // equivalent.
5647   if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
5648     for (++I; isa<DbgInfoIntrinsic>(I); ++I) {
5649     }
5650     if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
5651       return true;
5652   }
5653 
5654   // If this basic block is ONLY a compare and a branch, and if a predecessor
5655   // branches to us and our successor, fold the comparison into the
5656   // predecessor and use logical operations to update the incoming value
5657   // for PHI nodes in common successor.
5658   if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5659     return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5660   return false;
5661 }
5662 
5663 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5664   BasicBlock *PredPred = nullptr;
5665   for (auto *P : predecessors(BB)) {
5666     BasicBlock *PPred = P->getSinglePredecessor();
5667     if (!PPred || (PredPred && PredPred != PPred))
5668       return nullptr;
5669     PredPred = PPred;
5670   }
5671   return PredPred;
5672 }
5673 
5674 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
5675   BasicBlock *BB = BI->getParent();
5676 
5677   // Conditional branch
5678   if (isValueEqualityComparison(BI)) {
5679     // If we only have one predecessor, and if it is a branch on this value,
5680     // see if that predecessor totally determines the outcome of this
5681     // switch.
5682     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5683       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
5684         return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5685 
5686     // This block must be empty, except for the setcond inst, if it exists.
5687     // Ignore dbg intrinsics.
5688     BasicBlock::iterator I = BB->begin();
5689     // Ignore dbg intrinsics.
5690     while (isa<DbgInfoIntrinsic>(I))
5691       ++I;
5692     if (&*I == BI) {
5693       if (FoldValueComparisonIntoPredecessors(BI, Builder))
5694         return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5695     } else if (&*I == cast<Instruction>(BI->getCondition())) {
5696       ++I;
5697       // Ignore dbg intrinsics.
5698       while (isa<DbgInfoIntrinsic>(I))
5699         ++I;
5700       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
5701         return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5702     }
5703   }
5704 
5705   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
5706   if (SimplifyBranchOnICmpChain(BI, Builder, DL))
5707     return true;
5708 
5709   // If this basic block has a single dominating predecessor block and the
5710   // dominating block's condition implies BI's condition, we know the direction
5711   // of the BI branch.
5712   if (BasicBlock *Dom = BB->getSinglePredecessor()) {
5713     auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
5714     if (PBI && PBI->isConditional() &&
5715         PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
5716         (PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB)) {
5717       bool CondIsFalse = PBI->getSuccessor(1) == BB;
5718       Optional<bool> Implication = isImpliedCondition(
5719           PBI->getCondition(), BI->getCondition(), DL, CondIsFalse);
5720       if (Implication) {
5721         // Turn this into a branch on constant.
5722         auto *OldCond = BI->getCondition();
5723         ConstantInt *CI = *Implication
5724                               ? ConstantInt::getTrue(BB->getContext())
5725                               : ConstantInt::getFalse(BB->getContext());
5726         BI->setCondition(CI);
5727         RecursivelyDeleteTriviallyDeadInstructions(OldCond);
5728         return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5729       }
5730     }
5731   }
5732 
5733   // If this basic block is ONLY a compare and a branch, and if a predecessor
5734   // branches to us and one of our successors, fold the comparison into the
5735   // predecessor and use logical operations to pick the right destination.
5736   if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5737     return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5738 
5739   // We have a conditional branch to two blocks that are only reachable
5740   // from BI.  We know that the condbr dominates the two blocks, so see if
5741   // there is any identical code in the "then" and "else" blocks.  If so, we
5742   // can hoist it up to the branching block.
5743   if (BI->getSuccessor(0)->getSinglePredecessor()) {
5744     if (BI->getSuccessor(1)->getSinglePredecessor()) {
5745       if (HoistThenElseCodeToIf(BI, TTI))
5746         return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5747     } else {
5748       // If Successor #1 has multiple preds, we may be able to conditionally
5749       // execute Successor #0 if it branches to Successor #1.
5750       TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5751       if (Succ0TI->getNumSuccessors() == 1 &&
5752           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
5753         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5754           return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5755     }
5756   } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
5757     // If Successor #0 has multiple preds, we may be able to conditionally
5758     // execute Successor #1 if it branches to Successor #0.
5759     TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5760     if (Succ1TI->getNumSuccessors() == 1 &&
5761         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
5762       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5763         return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5764   }
5765 
5766   // If this is a branch on a phi node in the current block, thread control
5767   // through this block if any PHI node entries are constants.
5768   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5769     if (PN->getParent() == BI->getParent())
5770       if (FoldCondBranchOnPHI(BI, DL))
5771         return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5772 
5773   // Scan predecessor blocks for conditional branches.
5774   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5775     if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
5776       if (PBI != BI && PBI->isConditional())
5777         if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
5778           return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5779 
5780   // Look for diamond patterns.
5781   if (MergeCondStores)
5782     if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5783       if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5784         if (PBI != BI && PBI->isConditional())
5785           if (mergeConditionalStores(PBI, BI))
5786             return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5787 
5788   return false;
5789 }
5790 
5791 /// Check if passing a value to an instruction will cause undefined behavior.
5792 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5793   Constant *C = dyn_cast<Constant>(V);
5794   if (!C)
5795     return false;
5796 
5797   if (I->use_empty())
5798     return false;
5799 
5800   if (C->isNullValue() || isa<UndefValue>(C)) {
5801     // Only look at the first use, avoid hurting compile time with long uselists
5802     User *Use = *I->user_begin();
5803 
5804     // Now make sure that there are no instructions in between that can alter
5805     // control flow (eg. calls)
5806     for (BasicBlock::iterator
5807              i = ++BasicBlock::iterator(I),
5808              UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
5809          i != UI; ++i)
5810       if (i == I->getParent()->end() || i->mayHaveSideEffects())
5811         return false;
5812 
5813     // Look through GEPs. A load from a GEP derived from NULL is still undefined
5814     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5815       if (GEP->getPointerOperand() == I)
5816         return passingValueIsAlwaysUndefined(V, GEP);
5817 
5818     // Look through bitcasts.
5819     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5820       return passingValueIsAlwaysUndefined(V, BC);
5821 
5822     // Load from null is undefined.
5823     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
5824       if (!LI->isVolatile())
5825         return LI->getPointerAddressSpace() == 0;
5826 
5827     // Store to null is undefined.
5828     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
5829       if (!SI->isVolatile())
5830         return SI->getPointerAddressSpace() == 0 &&
5831                SI->getPointerOperand() == I;
5832 
5833     // A call to null is undefined.
5834     if (auto CS = CallSite(Use))
5835       return CS.getCalledValue() == I;
5836   }
5837   return false;
5838 }
5839 
5840 /// If BB has an incoming value that will always trigger undefined behavior
5841 /// (eg. null pointer dereference), remove the branch leading here.
5842 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5843   for (BasicBlock::iterator i = BB->begin();
5844        PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5845     for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5846       if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5847         TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5848         IRBuilder<> Builder(T);
5849         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5850           BB->removePredecessor(PHI->getIncomingBlock(i));
5851           // Turn uncoditional branches into unreachables and remove the dead
5852           // destination from conditional branches.
5853           if (BI->isUnconditional())
5854             Builder.CreateUnreachable();
5855           else
5856             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
5857                                                        : BI->getSuccessor(0));
5858           BI->eraseFromParent();
5859           return true;
5860         }
5861         // TODO: SwitchInst.
5862       }
5863 
5864   return false;
5865 }
5866 
5867 bool SimplifyCFGOpt::run(BasicBlock *BB) {
5868   bool Changed = false;
5869 
5870   assert(BB && BB->getParent() && "Block not embedded in function!");
5871   assert(BB->getTerminator() && "Degenerate basic block encountered!");
5872 
5873   // Remove basic blocks that have no predecessors (except the entry block)...
5874   // or that just have themself as a predecessor.  These are unreachable.
5875   if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
5876       BB->getSinglePredecessor() == BB) {
5877     DEBUG(dbgs() << "Removing BB: \n" << *BB);
5878     DeleteDeadBlock(BB);
5879     return true;
5880   }
5881 
5882   // Check to see if we can constant propagate this terminator instruction
5883   // away...
5884   Changed |= ConstantFoldTerminator(BB, true);
5885 
5886   // Check for and eliminate duplicate PHI nodes in this block.
5887   Changed |= EliminateDuplicatePHINodes(BB);
5888 
5889   // Check for and remove branches that will always cause undefined behavior.
5890   Changed |= removeUndefIntroducingPredecessor(BB);
5891 
5892   // Merge basic blocks into their predecessor if there is only one distinct
5893   // pred, and if there is only one distinct successor of the predecessor, and
5894   // if there are no PHI nodes.
5895   //
5896   if (MergeBlockIntoPredecessor(BB))
5897     return true;
5898 
5899   IRBuilder<> Builder(BB);
5900 
5901   // If there is a trivial two-entry PHI node in this basic block, and we can
5902   // eliminate it, do so now.
5903   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5904     if (PN->getNumIncomingValues() == 2)
5905       Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
5906 
5907   Builder.SetInsertPoint(BB->getTerminator());
5908   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
5909     if (BI->isUnconditional()) {
5910       if (SimplifyUncondBranch(BI, Builder))
5911         return true;
5912     } else {
5913       if (SimplifyCondBranch(BI, Builder))
5914         return true;
5915     }
5916   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
5917     if (SimplifyReturn(RI, Builder))
5918       return true;
5919   } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
5920     if (SimplifyResume(RI, Builder))
5921       return true;
5922   } else if (CleanupReturnInst *RI =
5923                  dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5924     if (SimplifyCleanupReturn(RI))
5925       return true;
5926   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
5927     if (SimplifySwitch(SI, Builder))
5928       return true;
5929   } else if (UnreachableInst *UI =
5930                  dyn_cast<UnreachableInst>(BB->getTerminator())) {
5931     if (SimplifyUnreachable(UI))
5932       return true;
5933   } else if (IndirectBrInst *IBI =
5934                  dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5935     if (SimplifyIndirectBr(IBI))
5936       return true;
5937   }
5938 
5939   return Changed;
5940 }
5941 
5942 /// This function is used to do simplification of a CFG.
5943 /// For example, it adjusts branches to branches to eliminate the extra hop,
5944 /// eliminates unreachable basic blocks, and does other "peephole" optimization
5945 /// of the CFG.  It returns true if a modification was made.
5946 ///
5947 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
5948                        unsigned BonusInstThreshold, AssumptionCache *AC,
5949                        SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
5950   return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
5951                         BonusInstThreshold, AC, LoopHeaders)
5952       .run(BB);
5953 }
5954