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