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