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