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