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