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