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