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