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