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