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