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