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