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