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