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