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