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