xref: /aosp_15_r20/external/llvm/lib/Analysis/InlineCost.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
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 // This file implements inline cost analysis.
11*9880d681SAndroid Build Coastguard Worker //
12*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
13*9880d681SAndroid Build Coastguard Worker 
14*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InlineCost.h"
15*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/STLExtras.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetVector.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallPtrSet.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallVector.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CodeMetrics.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ConstantFolding.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ProfileSummaryInfo.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetTransformInfo.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CallSite.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CallingConv.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/GetElementPtrTypeIterator.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/GlobalAlias.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/InstVisitor.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Operator.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
36*9880d681SAndroid Build Coastguard Worker 
37*9880d681SAndroid Build Coastguard Worker using namespace llvm;
38*9880d681SAndroid Build Coastguard Worker 
39*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "inline-cost"
40*9880d681SAndroid Build Coastguard Worker 
41*9880d681SAndroid Build Coastguard Worker STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
42*9880d681SAndroid Build Coastguard Worker 
43*9880d681SAndroid Build Coastguard Worker // Threshold to use when optsize is specified (and there is no
44*9880d681SAndroid Build Coastguard Worker // -inline-threshold).
45*9880d681SAndroid Build Coastguard Worker const int OptSizeThreshold = 75;
46*9880d681SAndroid Build Coastguard Worker 
47*9880d681SAndroid Build Coastguard Worker // Threshold to use when -Oz is specified (and there is no -inline-threshold).
48*9880d681SAndroid Build Coastguard Worker const int OptMinSizeThreshold = 25;
49*9880d681SAndroid Build Coastguard Worker 
50*9880d681SAndroid Build Coastguard Worker // Threshold to use when -O[34] is specified (and there is no
51*9880d681SAndroid Build Coastguard Worker // -inline-threshold).
52*9880d681SAndroid Build Coastguard Worker const int OptAggressiveThreshold = 275;
53*9880d681SAndroid Build Coastguard Worker 
54*9880d681SAndroid Build Coastguard Worker static cl::opt<int> DefaultInlineThreshold(
55*9880d681SAndroid Build Coastguard Worker     "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
56*9880d681SAndroid Build Coastguard Worker     cl::desc("Control the amount of inlining to perform (default = 225)"));
57*9880d681SAndroid Build Coastguard Worker 
58*9880d681SAndroid Build Coastguard Worker static cl::opt<int> HintThreshold(
59*9880d681SAndroid Build Coastguard Worker     "inlinehint-threshold", cl::Hidden, cl::init(325),
60*9880d681SAndroid Build Coastguard Worker     cl::desc("Threshold for inlining functions with inline hint"));
61*9880d681SAndroid Build Coastguard Worker 
62*9880d681SAndroid Build Coastguard Worker // We introduce this threshold to help performance of instrumentation based
63*9880d681SAndroid Build Coastguard Worker // PGO before we actually hook up inliner with analysis passes such as BPI and
64*9880d681SAndroid Build Coastguard Worker // BFI.
65*9880d681SAndroid Build Coastguard Worker static cl::opt<int> ColdThreshold(
66*9880d681SAndroid Build Coastguard Worker     "inlinecold-threshold", cl::Hidden, cl::init(225),
67*9880d681SAndroid Build Coastguard Worker     cl::desc("Threshold for inlining functions with cold attribute"));
68*9880d681SAndroid Build Coastguard Worker 
69*9880d681SAndroid Build Coastguard Worker namespace {
70*9880d681SAndroid Build Coastguard Worker 
71*9880d681SAndroid Build Coastguard Worker class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
72*9880d681SAndroid Build Coastguard Worker   typedef InstVisitor<CallAnalyzer, bool> Base;
73*9880d681SAndroid Build Coastguard Worker   friend class InstVisitor<CallAnalyzer, bool>;
74*9880d681SAndroid Build Coastguard Worker 
75*9880d681SAndroid Build Coastguard Worker   /// The TargetTransformInfo available for this compilation.
76*9880d681SAndroid Build Coastguard Worker   const TargetTransformInfo &TTI;
77*9880d681SAndroid Build Coastguard Worker 
78*9880d681SAndroid Build Coastguard Worker   /// The cache of @llvm.assume intrinsics.
79*9880d681SAndroid Build Coastguard Worker   AssumptionCacheTracker *ACT;
80*9880d681SAndroid Build Coastguard Worker 
81*9880d681SAndroid Build Coastguard Worker   /// Profile summary information.
82*9880d681SAndroid Build Coastguard Worker   ProfileSummaryInfo *PSI;
83*9880d681SAndroid Build Coastguard Worker 
84*9880d681SAndroid Build Coastguard Worker   // The called function.
85*9880d681SAndroid Build Coastguard Worker   Function &F;
86*9880d681SAndroid Build Coastguard Worker 
87*9880d681SAndroid Build Coastguard Worker   // The candidate callsite being analyzed. Please do not use this to do
88*9880d681SAndroid Build Coastguard Worker   // analysis in the caller function; we want the inline cost query to be
89*9880d681SAndroid Build Coastguard Worker   // easily cacheable. Instead, use the cover function paramHasAttr.
90*9880d681SAndroid Build Coastguard Worker   CallSite CandidateCS;
91*9880d681SAndroid Build Coastguard Worker 
92*9880d681SAndroid Build Coastguard Worker   int Threshold;
93*9880d681SAndroid Build Coastguard Worker   int Cost;
94*9880d681SAndroid Build Coastguard Worker 
95*9880d681SAndroid Build Coastguard Worker   bool IsCallerRecursive;
96*9880d681SAndroid Build Coastguard Worker   bool IsRecursiveCall;
97*9880d681SAndroid Build Coastguard Worker   bool ExposesReturnsTwice;
98*9880d681SAndroid Build Coastguard Worker   bool HasDynamicAlloca;
99*9880d681SAndroid Build Coastguard Worker   bool ContainsNoDuplicateCall;
100*9880d681SAndroid Build Coastguard Worker   bool HasReturn;
101*9880d681SAndroid Build Coastguard Worker   bool HasIndirectBr;
102*9880d681SAndroid Build Coastguard Worker   bool HasFrameEscape;
103*9880d681SAndroid Build Coastguard Worker 
104*9880d681SAndroid Build Coastguard Worker   /// Number of bytes allocated statically by the callee.
105*9880d681SAndroid Build Coastguard Worker   uint64_t AllocatedSize;
106*9880d681SAndroid Build Coastguard Worker   unsigned NumInstructions, NumVectorInstructions;
107*9880d681SAndroid Build Coastguard Worker   int FiftyPercentVectorBonus, TenPercentVectorBonus;
108*9880d681SAndroid Build Coastguard Worker   int VectorBonus;
109*9880d681SAndroid Build Coastguard Worker 
110*9880d681SAndroid Build Coastguard Worker   // While we walk the potentially-inlined instructions, we build up and
111*9880d681SAndroid Build Coastguard Worker   // maintain a mapping of simplified values specific to this callsite. The
112*9880d681SAndroid Build Coastguard Worker   // idea is to propagate any special information we have about arguments to
113*9880d681SAndroid Build Coastguard Worker   // this call through the inlinable section of the function, and account for
114*9880d681SAndroid Build Coastguard Worker   // likely simplifications post-inlining. The most important aspect we track
115*9880d681SAndroid Build Coastguard Worker   // is CFG altering simplifications -- when we prove a basic block dead, that
116*9880d681SAndroid Build Coastguard Worker   // can cause dramatic shifts in the cost of inlining a function.
117*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, Constant *> SimplifiedValues;
118*9880d681SAndroid Build Coastguard Worker 
119*9880d681SAndroid Build Coastguard Worker   // Keep track of the values which map back (through function arguments) to
120*9880d681SAndroid Build Coastguard Worker   // allocas on the caller stack which could be simplified through SROA.
121*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, Value *> SROAArgValues;
122*9880d681SAndroid Build Coastguard Worker 
123*9880d681SAndroid Build Coastguard Worker   // The mapping of caller Alloca values to their accumulated cost savings. If
124*9880d681SAndroid Build Coastguard Worker   // we have to disable SROA for one of the allocas, this tells us how much
125*9880d681SAndroid Build Coastguard Worker   // cost must be added.
126*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, int> SROAArgCosts;
127*9880d681SAndroid Build Coastguard Worker 
128*9880d681SAndroid Build Coastguard Worker   // Keep track of values which map to a pointer base and constant offset.
129*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
130*9880d681SAndroid Build Coastguard Worker 
131*9880d681SAndroid Build Coastguard Worker   // Custom simplification helper routines.
132*9880d681SAndroid Build Coastguard Worker   bool isAllocaDerivedArg(Value *V);
133*9880d681SAndroid Build Coastguard Worker   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
134*9880d681SAndroid Build Coastguard Worker                             DenseMap<Value *, int>::iterator &CostIt);
135*9880d681SAndroid Build Coastguard Worker   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
136*9880d681SAndroid Build Coastguard Worker   void disableSROA(Value *V);
137*9880d681SAndroid Build Coastguard Worker   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
138*9880d681SAndroid Build Coastguard Worker                           int InstructionCost);
139*9880d681SAndroid Build Coastguard Worker   bool isGEPOffsetConstant(GetElementPtrInst &GEP);
140*9880d681SAndroid Build Coastguard Worker   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
141*9880d681SAndroid Build Coastguard Worker   bool simplifyCallSite(Function *F, CallSite CS);
142*9880d681SAndroid Build Coastguard Worker   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
143*9880d681SAndroid Build Coastguard Worker 
144*9880d681SAndroid Build Coastguard Worker   /// Return true if the given argument to the function being considered for
145*9880d681SAndroid Build Coastguard Worker   /// inlining has the given attribute set either at the call site or the
146*9880d681SAndroid Build Coastguard Worker   /// function declaration.  Primarily used to inspect call site specific
147*9880d681SAndroid Build Coastguard Worker   /// attributes since these can be more precise than the ones on the callee
148*9880d681SAndroid Build Coastguard Worker   /// itself.
149*9880d681SAndroid Build Coastguard Worker   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
150*9880d681SAndroid Build Coastguard Worker 
151*9880d681SAndroid Build Coastguard Worker   /// Return true if the given value is known non null within the callee if
152*9880d681SAndroid Build Coastguard Worker   /// inlined through this particular callsite.
153*9880d681SAndroid Build Coastguard Worker   bool isKnownNonNullInCallee(Value *V);
154*9880d681SAndroid Build Coastguard Worker 
155*9880d681SAndroid Build Coastguard Worker   /// Update Threshold based on callsite properties such as callee
156*9880d681SAndroid Build Coastguard Worker   /// attributes and callee hotness for PGO builds. The Callee is explicitly
157*9880d681SAndroid Build Coastguard Worker   /// passed to support analyzing indirect calls whose target is inferred by
158*9880d681SAndroid Build Coastguard Worker   /// analysis.
159*9880d681SAndroid Build Coastguard Worker   void updateThreshold(CallSite CS, Function &Callee);
160*9880d681SAndroid Build Coastguard Worker 
161*9880d681SAndroid Build Coastguard Worker   /// Return true if size growth is allowed when inlining the callee at CS.
162*9880d681SAndroid Build Coastguard Worker   bool allowSizeGrowth(CallSite CS);
163*9880d681SAndroid Build Coastguard Worker 
164*9880d681SAndroid Build Coastguard Worker   // Custom analysis routines.
165*9880d681SAndroid Build Coastguard Worker   bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues);
166*9880d681SAndroid Build Coastguard Worker 
167*9880d681SAndroid Build Coastguard Worker   // Disable several entry points to the visitor so we don't accidentally use
168*9880d681SAndroid Build Coastguard Worker   // them by declaring but not defining them here.
169*9880d681SAndroid Build Coastguard Worker   void visit(Module *);
170*9880d681SAndroid Build Coastguard Worker   void visit(Module &);
171*9880d681SAndroid Build Coastguard Worker   void visit(Function *);
172*9880d681SAndroid Build Coastguard Worker   void visit(Function &);
173*9880d681SAndroid Build Coastguard Worker   void visit(BasicBlock *);
174*9880d681SAndroid Build Coastguard Worker   void visit(BasicBlock &);
175*9880d681SAndroid Build Coastguard Worker 
176*9880d681SAndroid Build Coastguard Worker   // Provide base case for our instruction visit.
177*9880d681SAndroid Build Coastguard Worker   bool visitInstruction(Instruction &I);
178*9880d681SAndroid Build Coastguard Worker 
179*9880d681SAndroid Build Coastguard Worker   // Our visit overrides.
180*9880d681SAndroid Build Coastguard Worker   bool visitAlloca(AllocaInst &I);
181*9880d681SAndroid Build Coastguard Worker   bool visitPHI(PHINode &I);
182*9880d681SAndroid Build Coastguard Worker   bool visitGetElementPtr(GetElementPtrInst &I);
183*9880d681SAndroid Build Coastguard Worker   bool visitBitCast(BitCastInst &I);
184*9880d681SAndroid Build Coastguard Worker   bool visitPtrToInt(PtrToIntInst &I);
185*9880d681SAndroid Build Coastguard Worker   bool visitIntToPtr(IntToPtrInst &I);
186*9880d681SAndroid Build Coastguard Worker   bool visitCastInst(CastInst &I);
187*9880d681SAndroid Build Coastguard Worker   bool visitUnaryInstruction(UnaryInstruction &I);
188*9880d681SAndroid Build Coastguard Worker   bool visitCmpInst(CmpInst &I);
189*9880d681SAndroid Build Coastguard Worker   bool visitSub(BinaryOperator &I);
190*9880d681SAndroid Build Coastguard Worker   bool visitBinaryOperator(BinaryOperator &I);
191*9880d681SAndroid Build Coastguard Worker   bool visitLoad(LoadInst &I);
192*9880d681SAndroid Build Coastguard Worker   bool visitStore(StoreInst &I);
193*9880d681SAndroid Build Coastguard Worker   bool visitExtractValue(ExtractValueInst &I);
194*9880d681SAndroid Build Coastguard Worker   bool visitInsertValue(InsertValueInst &I);
195*9880d681SAndroid Build Coastguard Worker   bool visitCallSite(CallSite CS);
196*9880d681SAndroid Build Coastguard Worker   bool visitReturnInst(ReturnInst &RI);
197*9880d681SAndroid Build Coastguard Worker   bool visitBranchInst(BranchInst &BI);
198*9880d681SAndroid Build Coastguard Worker   bool visitSwitchInst(SwitchInst &SI);
199*9880d681SAndroid Build Coastguard Worker   bool visitIndirectBrInst(IndirectBrInst &IBI);
200*9880d681SAndroid Build Coastguard Worker   bool visitResumeInst(ResumeInst &RI);
201*9880d681SAndroid Build Coastguard Worker   bool visitCleanupReturnInst(CleanupReturnInst &RI);
202*9880d681SAndroid Build Coastguard Worker   bool visitCatchReturnInst(CatchReturnInst &RI);
203*9880d681SAndroid Build Coastguard Worker   bool visitUnreachableInst(UnreachableInst &I);
204*9880d681SAndroid Build Coastguard Worker 
205*9880d681SAndroid Build Coastguard Worker public:
CallAnalyzer(const TargetTransformInfo & TTI,AssumptionCacheTracker * ACT,ProfileSummaryInfo * PSI,Function & Callee,int Threshold,CallSite CSArg)206*9880d681SAndroid Build Coastguard Worker   CallAnalyzer(const TargetTransformInfo &TTI, AssumptionCacheTracker *ACT,
207*9880d681SAndroid Build Coastguard Worker                ProfileSummaryInfo *PSI, Function &Callee, int Threshold,
208*9880d681SAndroid Build Coastguard Worker                CallSite CSArg)
209*9880d681SAndroid Build Coastguard Worker       : TTI(TTI), ACT(ACT), PSI(PSI), F(Callee), CandidateCS(CSArg),
210*9880d681SAndroid Build Coastguard Worker         Threshold(Threshold), Cost(0), IsCallerRecursive(false),
211*9880d681SAndroid Build Coastguard Worker         IsRecursiveCall(false), ExposesReturnsTwice(false),
212*9880d681SAndroid Build Coastguard Worker         HasDynamicAlloca(false), ContainsNoDuplicateCall(false),
213*9880d681SAndroid Build Coastguard Worker         HasReturn(false), HasIndirectBr(false), HasFrameEscape(false),
214*9880d681SAndroid Build Coastguard Worker         AllocatedSize(0), NumInstructions(0), NumVectorInstructions(0),
215*9880d681SAndroid Build Coastguard Worker         FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
216*9880d681SAndroid Build Coastguard Worker         NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
217*9880d681SAndroid Build Coastguard Worker         NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
218*9880d681SAndroid Build Coastguard Worker         NumInstructionsSimplified(0), SROACostSavings(0),
219*9880d681SAndroid Build Coastguard Worker         SROACostSavingsLost(0) {}
220*9880d681SAndroid Build Coastguard Worker 
221*9880d681SAndroid Build Coastguard Worker   bool analyzeCall(CallSite CS);
222*9880d681SAndroid Build Coastguard Worker 
getThreshold()223*9880d681SAndroid Build Coastguard Worker   int getThreshold() { return Threshold; }
getCost()224*9880d681SAndroid Build Coastguard Worker   int getCost() { return Cost; }
225*9880d681SAndroid Build Coastguard Worker 
226*9880d681SAndroid Build Coastguard Worker   // Keep a bunch of stats about the cost savings found so we can print them
227*9880d681SAndroid Build Coastguard Worker   // out when debugging.
228*9880d681SAndroid Build Coastguard Worker   unsigned NumConstantArgs;
229*9880d681SAndroid Build Coastguard Worker   unsigned NumConstantOffsetPtrArgs;
230*9880d681SAndroid Build Coastguard Worker   unsigned NumAllocaArgs;
231*9880d681SAndroid Build Coastguard Worker   unsigned NumConstantPtrCmps;
232*9880d681SAndroid Build Coastguard Worker   unsigned NumConstantPtrDiffs;
233*9880d681SAndroid Build Coastguard Worker   unsigned NumInstructionsSimplified;
234*9880d681SAndroid Build Coastguard Worker   unsigned SROACostSavings;
235*9880d681SAndroid Build Coastguard Worker   unsigned SROACostSavingsLost;
236*9880d681SAndroid Build Coastguard Worker 
237*9880d681SAndroid Build Coastguard Worker   void dump();
238*9880d681SAndroid Build Coastguard Worker };
239*9880d681SAndroid Build Coastguard Worker 
240*9880d681SAndroid Build Coastguard Worker } // namespace
241*9880d681SAndroid Build Coastguard Worker 
242*9880d681SAndroid Build Coastguard Worker /// \brief Test whether the given value is an Alloca-derived function argument.
isAllocaDerivedArg(Value * V)243*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
244*9880d681SAndroid Build Coastguard Worker   return SROAArgValues.count(V);
245*9880d681SAndroid Build Coastguard Worker }
246*9880d681SAndroid Build Coastguard Worker 
247*9880d681SAndroid Build Coastguard Worker /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
248*9880d681SAndroid Build Coastguard Worker /// Returns false if V does not map to a SROA-candidate.
lookupSROAArgAndCost(Value * V,Value * & Arg,DenseMap<Value *,int>::iterator & CostIt)249*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::lookupSROAArgAndCost(
250*9880d681SAndroid Build Coastguard Worker     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
251*9880d681SAndroid Build Coastguard Worker   if (SROAArgValues.empty() || SROAArgCosts.empty())
252*9880d681SAndroid Build Coastguard Worker     return false;
253*9880d681SAndroid Build Coastguard Worker 
254*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
255*9880d681SAndroid Build Coastguard Worker   if (ArgIt == SROAArgValues.end())
256*9880d681SAndroid Build Coastguard Worker     return false;
257*9880d681SAndroid Build Coastguard Worker 
258*9880d681SAndroid Build Coastguard Worker   Arg = ArgIt->second;
259*9880d681SAndroid Build Coastguard Worker   CostIt = SROAArgCosts.find(Arg);
260*9880d681SAndroid Build Coastguard Worker   return CostIt != SROAArgCosts.end();
261*9880d681SAndroid Build Coastguard Worker }
262*9880d681SAndroid Build Coastguard Worker 
263*9880d681SAndroid Build Coastguard Worker /// \brief Disable SROA for the candidate marked by this cost iterator.
264*9880d681SAndroid Build Coastguard Worker ///
265*9880d681SAndroid Build Coastguard Worker /// This marks the candidate as no longer viable for SROA, and adds the cost
266*9880d681SAndroid Build Coastguard Worker /// savings associated with it back into the inline cost measurement.
disableSROA(DenseMap<Value *,int>::iterator CostIt)267*9880d681SAndroid Build Coastguard Worker void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
268*9880d681SAndroid Build Coastguard Worker   // If we're no longer able to perform SROA we need to undo its cost savings
269*9880d681SAndroid Build Coastguard Worker   // and prevent subsequent analysis.
270*9880d681SAndroid Build Coastguard Worker   Cost += CostIt->second;
271*9880d681SAndroid Build Coastguard Worker   SROACostSavings -= CostIt->second;
272*9880d681SAndroid Build Coastguard Worker   SROACostSavingsLost += CostIt->second;
273*9880d681SAndroid Build Coastguard Worker   SROAArgCosts.erase(CostIt);
274*9880d681SAndroid Build Coastguard Worker }
275*9880d681SAndroid Build Coastguard Worker 
276*9880d681SAndroid Build Coastguard Worker /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
disableSROA(Value * V)277*9880d681SAndroid Build Coastguard Worker void CallAnalyzer::disableSROA(Value *V) {
278*9880d681SAndroid Build Coastguard Worker   Value *SROAArg;
279*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, int>::iterator CostIt;
280*9880d681SAndroid Build Coastguard Worker   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
281*9880d681SAndroid Build Coastguard Worker     disableSROA(CostIt);
282*9880d681SAndroid Build Coastguard Worker }
283*9880d681SAndroid Build Coastguard Worker 
284*9880d681SAndroid Build Coastguard Worker /// \brief Accumulate the given cost for a particular SROA candidate.
accumulateSROACost(DenseMap<Value *,int>::iterator CostIt,int InstructionCost)285*9880d681SAndroid Build Coastguard Worker void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
286*9880d681SAndroid Build Coastguard Worker                                       int InstructionCost) {
287*9880d681SAndroid Build Coastguard Worker   CostIt->second += InstructionCost;
288*9880d681SAndroid Build Coastguard Worker   SROACostSavings += InstructionCost;
289*9880d681SAndroid Build Coastguard Worker }
290*9880d681SAndroid Build Coastguard Worker 
291*9880d681SAndroid Build Coastguard Worker /// \brief Check whether a GEP's indices are all constant.
292*9880d681SAndroid Build Coastguard Worker ///
293*9880d681SAndroid Build Coastguard Worker /// Respects any simplified values known during the analysis of this callsite.
isGEPOffsetConstant(GetElementPtrInst & GEP)294*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
295*9880d681SAndroid Build Coastguard Worker   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
296*9880d681SAndroid Build Coastguard Worker     if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
297*9880d681SAndroid Build Coastguard Worker       return false;
298*9880d681SAndroid Build Coastguard Worker 
299*9880d681SAndroid Build Coastguard Worker   return true;
300*9880d681SAndroid Build Coastguard Worker }
301*9880d681SAndroid Build Coastguard Worker 
302*9880d681SAndroid Build Coastguard Worker /// \brief Accumulate a constant GEP offset into an APInt if possible.
303*9880d681SAndroid Build Coastguard Worker ///
304*9880d681SAndroid Build Coastguard Worker /// Returns false if unable to compute the offset for any reason. Respects any
305*9880d681SAndroid Build Coastguard Worker /// simplified values known during the analysis of this callsite.
accumulateGEPOffset(GEPOperator & GEP,APInt & Offset)306*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
307*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = F.getParent()->getDataLayout();
308*9880d681SAndroid Build Coastguard Worker   unsigned IntPtrWidth = DL.getPointerSizeInBits();
309*9880d681SAndroid Build Coastguard Worker   assert(IntPtrWidth == Offset.getBitWidth());
310*9880d681SAndroid Build Coastguard Worker 
311*9880d681SAndroid Build Coastguard Worker   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
312*9880d681SAndroid Build Coastguard Worker        GTI != GTE; ++GTI) {
313*9880d681SAndroid Build Coastguard Worker     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
314*9880d681SAndroid Build Coastguard Worker     if (!OpC)
315*9880d681SAndroid Build Coastguard Worker       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
316*9880d681SAndroid Build Coastguard Worker         OpC = dyn_cast<ConstantInt>(SimpleOp);
317*9880d681SAndroid Build Coastguard Worker     if (!OpC)
318*9880d681SAndroid Build Coastguard Worker       return false;
319*9880d681SAndroid Build Coastguard Worker     if (OpC->isZero())
320*9880d681SAndroid Build Coastguard Worker       continue;
321*9880d681SAndroid Build Coastguard Worker 
322*9880d681SAndroid Build Coastguard Worker     // Handle a struct index, which adds its field offset to the pointer.
323*9880d681SAndroid Build Coastguard Worker     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
324*9880d681SAndroid Build Coastguard Worker       unsigned ElementIdx = OpC->getZExtValue();
325*9880d681SAndroid Build Coastguard Worker       const StructLayout *SL = DL.getStructLayout(STy);
326*9880d681SAndroid Build Coastguard Worker       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
327*9880d681SAndroid Build Coastguard Worker       continue;
328*9880d681SAndroid Build Coastguard Worker     }
329*9880d681SAndroid Build Coastguard Worker 
330*9880d681SAndroid Build Coastguard Worker     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
331*9880d681SAndroid Build Coastguard Worker     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
332*9880d681SAndroid Build Coastguard Worker   }
333*9880d681SAndroid Build Coastguard Worker   return true;
334*9880d681SAndroid Build Coastguard Worker }
335*9880d681SAndroid Build Coastguard Worker 
visitAlloca(AllocaInst & I)336*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitAlloca(AllocaInst &I) {
337*9880d681SAndroid Build Coastguard Worker   // Check whether inlining will turn a dynamic alloca into a static
338*9880d681SAndroid Build Coastguard Worker   // alloca and handle that case.
339*9880d681SAndroid Build Coastguard Worker   if (I.isArrayAllocation()) {
340*9880d681SAndroid Build Coastguard Worker     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
341*9880d681SAndroid Build Coastguard Worker     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
342*9880d681SAndroid Build Coastguard Worker       const DataLayout &DL = F.getParent()->getDataLayout();
343*9880d681SAndroid Build Coastguard Worker       Type *Ty = I.getAllocatedType();
344*9880d681SAndroid Build Coastguard Worker       AllocatedSize = SaturatingMultiplyAdd(
345*9880d681SAndroid Build Coastguard Worker           AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty), AllocatedSize);
346*9880d681SAndroid Build Coastguard Worker       return Base::visitAlloca(I);
347*9880d681SAndroid Build Coastguard Worker     }
348*9880d681SAndroid Build Coastguard Worker   }
349*9880d681SAndroid Build Coastguard Worker 
350*9880d681SAndroid Build Coastguard Worker   // Accumulate the allocated size.
351*9880d681SAndroid Build Coastguard Worker   if (I.isStaticAlloca()) {
352*9880d681SAndroid Build Coastguard Worker     const DataLayout &DL = F.getParent()->getDataLayout();
353*9880d681SAndroid Build Coastguard Worker     Type *Ty = I.getAllocatedType();
354*9880d681SAndroid Build Coastguard Worker     AllocatedSize = SaturatingAdd(DL.getTypeAllocSize(Ty), AllocatedSize);
355*9880d681SAndroid Build Coastguard Worker   }
356*9880d681SAndroid Build Coastguard Worker 
357*9880d681SAndroid Build Coastguard Worker   // We will happily inline static alloca instructions.
358*9880d681SAndroid Build Coastguard Worker   if (I.isStaticAlloca())
359*9880d681SAndroid Build Coastguard Worker     return Base::visitAlloca(I);
360*9880d681SAndroid Build Coastguard Worker 
361*9880d681SAndroid Build Coastguard Worker   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
362*9880d681SAndroid Build Coastguard Worker   // a variety of reasons, and so we would like to not inline them into
363*9880d681SAndroid Build Coastguard Worker   // functions which don't currently have a dynamic alloca. This simply
364*9880d681SAndroid Build Coastguard Worker   // disables inlining altogether in the presence of a dynamic alloca.
365*9880d681SAndroid Build Coastguard Worker   HasDynamicAlloca = true;
366*9880d681SAndroid Build Coastguard Worker   return false;
367*9880d681SAndroid Build Coastguard Worker }
368*9880d681SAndroid Build Coastguard Worker 
visitPHI(PHINode & I)369*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitPHI(PHINode &I) {
370*9880d681SAndroid Build Coastguard Worker   // FIXME: We should potentially be tracking values through phi nodes,
371*9880d681SAndroid Build Coastguard Worker   // especially when they collapse to a single value due to deleted CFG edges
372*9880d681SAndroid Build Coastguard Worker   // during inlining.
373*9880d681SAndroid Build Coastguard Worker 
374*9880d681SAndroid Build Coastguard Worker   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
375*9880d681SAndroid Build Coastguard Worker   // though we don't want to propagate it's bonuses. The idea is to disable
376*9880d681SAndroid Build Coastguard Worker   // SROA if it *might* be used in an inappropriate manner.
377*9880d681SAndroid Build Coastguard Worker 
378*9880d681SAndroid Build Coastguard Worker   // Phi nodes are always zero-cost.
379*9880d681SAndroid Build Coastguard Worker   return true;
380*9880d681SAndroid Build Coastguard Worker }
381*9880d681SAndroid Build Coastguard Worker 
visitGetElementPtr(GetElementPtrInst & I)382*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
383*9880d681SAndroid Build Coastguard Worker   Value *SROAArg;
384*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, int>::iterator CostIt;
385*9880d681SAndroid Build Coastguard Worker   bool SROACandidate =
386*9880d681SAndroid Build Coastguard Worker       lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt);
387*9880d681SAndroid Build Coastguard Worker 
388*9880d681SAndroid Build Coastguard Worker   // Try to fold GEPs of constant-offset call site argument pointers. This
389*9880d681SAndroid Build Coastguard Worker   // requires target data and inbounds GEPs.
390*9880d681SAndroid Build Coastguard Worker   if (I.isInBounds()) {
391*9880d681SAndroid Build Coastguard Worker     // Check if we have a base + offset for the pointer.
392*9880d681SAndroid Build Coastguard Worker     Value *Ptr = I.getPointerOperand();
393*9880d681SAndroid Build Coastguard Worker     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
394*9880d681SAndroid Build Coastguard Worker     if (BaseAndOffset.first) {
395*9880d681SAndroid Build Coastguard Worker       // Check if the offset of this GEP is constant, and if so accumulate it
396*9880d681SAndroid Build Coastguard Worker       // into Offset.
397*9880d681SAndroid Build Coastguard Worker       if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
398*9880d681SAndroid Build Coastguard Worker         // Non-constant GEPs aren't folded, and disable SROA.
399*9880d681SAndroid Build Coastguard Worker         if (SROACandidate)
400*9880d681SAndroid Build Coastguard Worker           disableSROA(CostIt);
401*9880d681SAndroid Build Coastguard Worker         return false;
402*9880d681SAndroid Build Coastguard Worker       }
403*9880d681SAndroid Build Coastguard Worker 
404*9880d681SAndroid Build Coastguard Worker       // Add the result as a new mapping to Base + Offset.
405*9880d681SAndroid Build Coastguard Worker       ConstantOffsetPtrs[&I] = BaseAndOffset;
406*9880d681SAndroid Build Coastguard Worker 
407*9880d681SAndroid Build Coastguard Worker       // Also handle SROA candidates here, we already know that the GEP is
408*9880d681SAndroid Build Coastguard Worker       // all-constant indexed.
409*9880d681SAndroid Build Coastguard Worker       if (SROACandidate)
410*9880d681SAndroid Build Coastguard Worker         SROAArgValues[&I] = SROAArg;
411*9880d681SAndroid Build Coastguard Worker 
412*9880d681SAndroid Build Coastguard Worker       return true;
413*9880d681SAndroid Build Coastguard Worker     }
414*9880d681SAndroid Build Coastguard Worker   }
415*9880d681SAndroid Build Coastguard Worker 
416*9880d681SAndroid Build Coastguard Worker   if (isGEPOffsetConstant(I)) {
417*9880d681SAndroid Build Coastguard Worker     if (SROACandidate)
418*9880d681SAndroid Build Coastguard Worker       SROAArgValues[&I] = SROAArg;
419*9880d681SAndroid Build Coastguard Worker 
420*9880d681SAndroid Build Coastguard Worker     // Constant GEPs are modeled as free.
421*9880d681SAndroid Build Coastguard Worker     return true;
422*9880d681SAndroid Build Coastguard Worker   }
423*9880d681SAndroid Build Coastguard Worker 
424*9880d681SAndroid Build Coastguard Worker   // Variable GEPs will require math and will disable SROA.
425*9880d681SAndroid Build Coastguard Worker   if (SROACandidate)
426*9880d681SAndroid Build Coastguard Worker     disableSROA(CostIt);
427*9880d681SAndroid Build Coastguard Worker   return false;
428*9880d681SAndroid Build Coastguard Worker }
429*9880d681SAndroid Build Coastguard Worker 
visitBitCast(BitCastInst & I)430*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitBitCast(BitCastInst &I) {
431*9880d681SAndroid Build Coastguard Worker   // Propagate constants through bitcasts.
432*9880d681SAndroid Build Coastguard Worker   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
433*9880d681SAndroid Build Coastguard Worker   if (!COp)
434*9880d681SAndroid Build Coastguard Worker     COp = SimplifiedValues.lookup(I.getOperand(0));
435*9880d681SAndroid Build Coastguard Worker   if (COp)
436*9880d681SAndroid Build Coastguard Worker     if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
437*9880d681SAndroid Build Coastguard Worker       SimplifiedValues[&I] = C;
438*9880d681SAndroid Build Coastguard Worker       return true;
439*9880d681SAndroid Build Coastguard Worker     }
440*9880d681SAndroid Build Coastguard Worker 
441*9880d681SAndroid Build Coastguard Worker   // Track base/offsets through casts
442*9880d681SAndroid Build Coastguard Worker   std::pair<Value *, APInt> BaseAndOffset =
443*9880d681SAndroid Build Coastguard Worker       ConstantOffsetPtrs.lookup(I.getOperand(0));
444*9880d681SAndroid Build Coastguard Worker   // Casts don't change the offset, just wrap it up.
445*9880d681SAndroid Build Coastguard Worker   if (BaseAndOffset.first)
446*9880d681SAndroid Build Coastguard Worker     ConstantOffsetPtrs[&I] = BaseAndOffset;
447*9880d681SAndroid Build Coastguard Worker 
448*9880d681SAndroid Build Coastguard Worker   // Also look for SROA candidates here.
449*9880d681SAndroid Build Coastguard Worker   Value *SROAArg;
450*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, int>::iterator CostIt;
451*9880d681SAndroid Build Coastguard Worker   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
452*9880d681SAndroid Build Coastguard Worker     SROAArgValues[&I] = SROAArg;
453*9880d681SAndroid Build Coastguard Worker 
454*9880d681SAndroid Build Coastguard Worker   // Bitcasts are always zero cost.
455*9880d681SAndroid Build Coastguard Worker   return true;
456*9880d681SAndroid Build Coastguard Worker }
457*9880d681SAndroid Build Coastguard Worker 
visitPtrToInt(PtrToIntInst & I)458*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
459*9880d681SAndroid Build Coastguard Worker   // Propagate constants through ptrtoint.
460*9880d681SAndroid Build Coastguard Worker   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
461*9880d681SAndroid Build Coastguard Worker   if (!COp)
462*9880d681SAndroid Build Coastguard Worker     COp = SimplifiedValues.lookup(I.getOperand(0));
463*9880d681SAndroid Build Coastguard Worker   if (COp)
464*9880d681SAndroid Build Coastguard Worker     if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
465*9880d681SAndroid Build Coastguard Worker       SimplifiedValues[&I] = C;
466*9880d681SAndroid Build Coastguard Worker       return true;
467*9880d681SAndroid Build Coastguard Worker     }
468*9880d681SAndroid Build Coastguard Worker 
469*9880d681SAndroid Build Coastguard Worker   // Track base/offset pairs when converted to a plain integer provided the
470*9880d681SAndroid Build Coastguard Worker   // integer is large enough to represent the pointer.
471*9880d681SAndroid Build Coastguard Worker   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
472*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = F.getParent()->getDataLayout();
473*9880d681SAndroid Build Coastguard Worker   if (IntegerSize >= DL.getPointerSizeInBits()) {
474*9880d681SAndroid Build Coastguard Worker     std::pair<Value *, APInt> BaseAndOffset =
475*9880d681SAndroid Build Coastguard Worker         ConstantOffsetPtrs.lookup(I.getOperand(0));
476*9880d681SAndroid Build Coastguard Worker     if (BaseAndOffset.first)
477*9880d681SAndroid Build Coastguard Worker       ConstantOffsetPtrs[&I] = BaseAndOffset;
478*9880d681SAndroid Build Coastguard Worker   }
479*9880d681SAndroid Build Coastguard Worker 
480*9880d681SAndroid Build Coastguard Worker   // This is really weird. Technically, ptrtoint will disable SROA. However,
481*9880d681SAndroid Build Coastguard Worker   // unless that ptrtoint is *used* somewhere in the live basic blocks after
482*9880d681SAndroid Build Coastguard Worker   // inlining, it will be nuked, and SROA should proceed. All of the uses which
483*9880d681SAndroid Build Coastguard Worker   // would block SROA would also block SROA if applied directly to a pointer,
484*9880d681SAndroid Build Coastguard Worker   // and so we can just add the integer in here. The only places where SROA is
485*9880d681SAndroid Build Coastguard Worker   // preserved either cannot fire on an integer, or won't in-and-of themselves
486*9880d681SAndroid Build Coastguard Worker   // disable SROA (ext) w/o some later use that we would see and disable.
487*9880d681SAndroid Build Coastguard Worker   Value *SROAArg;
488*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, int>::iterator CostIt;
489*9880d681SAndroid Build Coastguard Worker   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
490*9880d681SAndroid Build Coastguard Worker     SROAArgValues[&I] = SROAArg;
491*9880d681SAndroid Build Coastguard Worker 
492*9880d681SAndroid Build Coastguard Worker   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
493*9880d681SAndroid Build Coastguard Worker }
494*9880d681SAndroid Build Coastguard Worker 
visitIntToPtr(IntToPtrInst & I)495*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
496*9880d681SAndroid Build Coastguard Worker   // Propagate constants through ptrtoint.
497*9880d681SAndroid Build Coastguard Worker   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
498*9880d681SAndroid Build Coastguard Worker   if (!COp)
499*9880d681SAndroid Build Coastguard Worker     COp = SimplifiedValues.lookup(I.getOperand(0));
500*9880d681SAndroid Build Coastguard Worker   if (COp)
501*9880d681SAndroid Build Coastguard Worker     if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
502*9880d681SAndroid Build Coastguard Worker       SimplifiedValues[&I] = C;
503*9880d681SAndroid Build Coastguard Worker       return true;
504*9880d681SAndroid Build Coastguard Worker     }
505*9880d681SAndroid Build Coastguard Worker 
506*9880d681SAndroid Build Coastguard Worker   // Track base/offset pairs when round-tripped through a pointer without
507*9880d681SAndroid Build Coastguard Worker   // modifications provided the integer is not too large.
508*9880d681SAndroid Build Coastguard Worker   Value *Op = I.getOperand(0);
509*9880d681SAndroid Build Coastguard Worker   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
510*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = F.getParent()->getDataLayout();
511*9880d681SAndroid Build Coastguard Worker   if (IntegerSize <= DL.getPointerSizeInBits()) {
512*9880d681SAndroid Build Coastguard Worker     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
513*9880d681SAndroid Build Coastguard Worker     if (BaseAndOffset.first)
514*9880d681SAndroid Build Coastguard Worker       ConstantOffsetPtrs[&I] = BaseAndOffset;
515*9880d681SAndroid Build Coastguard Worker   }
516*9880d681SAndroid Build Coastguard Worker 
517*9880d681SAndroid Build Coastguard Worker   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
518*9880d681SAndroid Build Coastguard Worker   Value *SROAArg;
519*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, int>::iterator CostIt;
520*9880d681SAndroid Build Coastguard Worker   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
521*9880d681SAndroid Build Coastguard Worker     SROAArgValues[&I] = SROAArg;
522*9880d681SAndroid Build Coastguard Worker 
523*9880d681SAndroid Build Coastguard Worker   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
524*9880d681SAndroid Build Coastguard Worker }
525*9880d681SAndroid Build Coastguard Worker 
visitCastInst(CastInst & I)526*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitCastInst(CastInst &I) {
527*9880d681SAndroid Build Coastguard Worker   // Propagate constants through ptrtoint.
528*9880d681SAndroid Build Coastguard Worker   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
529*9880d681SAndroid Build Coastguard Worker   if (!COp)
530*9880d681SAndroid Build Coastguard Worker     COp = SimplifiedValues.lookup(I.getOperand(0));
531*9880d681SAndroid Build Coastguard Worker   if (COp)
532*9880d681SAndroid Build Coastguard Worker     if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
533*9880d681SAndroid Build Coastguard Worker       SimplifiedValues[&I] = C;
534*9880d681SAndroid Build Coastguard Worker       return true;
535*9880d681SAndroid Build Coastguard Worker     }
536*9880d681SAndroid Build Coastguard Worker 
537*9880d681SAndroid Build Coastguard Worker   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
538*9880d681SAndroid Build Coastguard Worker   disableSROA(I.getOperand(0));
539*9880d681SAndroid Build Coastguard Worker 
540*9880d681SAndroid Build Coastguard Worker   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
541*9880d681SAndroid Build Coastguard Worker }
542*9880d681SAndroid Build Coastguard Worker 
visitUnaryInstruction(UnaryInstruction & I)543*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
544*9880d681SAndroid Build Coastguard Worker   Value *Operand = I.getOperand(0);
545*9880d681SAndroid Build Coastguard Worker   Constant *COp = dyn_cast<Constant>(Operand);
546*9880d681SAndroid Build Coastguard Worker   if (!COp)
547*9880d681SAndroid Build Coastguard Worker     COp = SimplifiedValues.lookup(Operand);
548*9880d681SAndroid Build Coastguard Worker   if (COp) {
549*9880d681SAndroid Build Coastguard Worker     const DataLayout &DL = F.getParent()->getDataLayout();
550*9880d681SAndroid Build Coastguard Worker     if (Constant *C = ConstantFoldInstOperands(&I, COp, DL)) {
551*9880d681SAndroid Build Coastguard Worker       SimplifiedValues[&I] = C;
552*9880d681SAndroid Build Coastguard Worker       return true;
553*9880d681SAndroid Build Coastguard Worker     }
554*9880d681SAndroid Build Coastguard Worker   }
555*9880d681SAndroid Build Coastguard Worker 
556*9880d681SAndroid Build Coastguard Worker   // Disable any SROA on the argument to arbitrary unary operators.
557*9880d681SAndroid Build Coastguard Worker   disableSROA(Operand);
558*9880d681SAndroid Build Coastguard Worker 
559*9880d681SAndroid Build Coastguard Worker   return false;
560*9880d681SAndroid Build Coastguard Worker }
561*9880d681SAndroid Build Coastguard Worker 
paramHasAttr(Argument * A,Attribute::AttrKind Attr)562*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
563*9880d681SAndroid Build Coastguard Worker   unsigned ArgNo = A->getArgNo();
564*9880d681SAndroid Build Coastguard Worker   return CandidateCS.paramHasAttr(ArgNo + 1, Attr);
565*9880d681SAndroid Build Coastguard Worker }
566*9880d681SAndroid Build Coastguard Worker 
isKnownNonNullInCallee(Value * V)567*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
568*9880d681SAndroid Build Coastguard Worker   // Does the *call site* have the NonNull attribute set on an argument?  We
569*9880d681SAndroid Build Coastguard Worker   // use the attribute on the call site to memoize any analysis done in the
570*9880d681SAndroid Build Coastguard Worker   // caller. This will also trip if the callee function has a non-null
571*9880d681SAndroid Build Coastguard Worker   // parameter attribute, but that's a less interesting case because hopefully
572*9880d681SAndroid Build Coastguard Worker   // the callee would already have been simplified based on that.
573*9880d681SAndroid Build Coastguard Worker   if (Argument *A = dyn_cast<Argument>(V))
574*9880d681SAndroid Build Coastguard Worker     if (paramHasAttr(A, Attribute::NonNull))
575*9880d681SAndroid Build Coastguard Worker       return true;
576*9880d681SAndroid Build Coastguard Worker 
577*9880d681SAndroid Build Coastguard Worker   // Is this an alloca in the caller?  This is distinct from the attribute case
578*9880d681SAndroid Build Coastguard Worker   // above because attributes aren't updated within the inliner itself and we
579*9880d681SAndroid Build Coastguard Worker   // always want to catch the alloca derived case.
580*9880d681SAndroid Build Coastguard Worker   if (isAllocaDerivedArg(V))
581*9880d681SAndroid Build Coastguard Worker     // We can actually predict the result of comparisons between an
582*9880d681SAndroid Build Coastguard Worker     // alloca-derived value and null. Note that this fires regardless of
583*9880d681SAndroid Build Coastguard Worker     // SROA firing.
584*9880d681SAndroid Build Coastguard Worker     return true;
585*9880d681SAndroid Build Coastguard Worker 
586*9880d681SAndroid Build Coastguard Worker   return false;
587*9880d681SAndroid Build Coastguard Worker }
588*9880d681SAndroid Build Coastguard Worker 
allowSizeGrowth(CallSite CS)589*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::allowSizeGrowth(CallSite CS) {
590*9880d681SAndroid Build Coastguard Worker   // If the normal destination of the invoke or the parent block of the call
591*9880d681SAndroid Build Coastguard Worker   // site is unreachable-terminated, there is little point in inlining this
592*9880d681SAndroid Build Coastguard Worker   // unless there is literally zero cost.
593*9880d681SAndroid Build Coastguard Worker   // FIXME: Note that it is possible that an unreachable-terminated block has a
594*9880d681SAndroid Build Coastguard Worker   // hot entry. For example, in below scenario inlining hot_call_X() may be
595*9880d681SAndroid Build Coastguard Worker   // beneficial :
596*9880d681SAndroid Build Coastguard Worker   // main() {
597*9880d681SAndroid Build Coastguard Worker   //   hot_call_1();
598*9880d681SAndroid Build Coastguard Worker   //   ...
599*9880d681SAndroid Build Coastguard Worker   //   hot_call_N()
600*9880d681SAndroid Build Coastguard Worker   //   exit(0);
601*9880d681SAndroid Build Coastguard Worker   // }
602*9880d681SAndroid Build Coastguard Worker   // For now, we are not handling this corner case here as it is rare in real
603*9880d681SAndroid Build Coastguard Worker   // code. In future, we should elaborate this based on BPI and BFI in more
604*9880d681SAndroid Build Coastguard Worker   // general threshold adjusting heuristics in updateThreshold().
605*9880d681SAndroid Build Coastguard Worker   Instruction *Instr = CS.getInstruction();
606*9880d681SAndroid Build Coastguard Worker   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
607*9880d681SAndroid Build Coastguard Worker     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
608*9880d681SAndroid Build Coastguard Worker       return false;
609*9880d681SAndroid Build Coastguard Worker   } else if (isa<UnreachableInst>(Instr->getParent()->getTerminator()))
610*9880d681SAndroid Build Coastguard Worker     return false;
611*9880d681SAndroid Build Coastguard Worker 
612*9880d681SAndroid Build Coastguard Worker   return true;
613*9880d681SAndroid Build Coastguard Worker }
614*9880d681SAndroid Build Coastguard Worker 
updateThreshold(CallSite CS,Function & Callee)615*9880d681SAndroid Build Coastguard Worker void CallAnalyzer::updateThreshold(CallSite CS, Function &Callee) {
616*9880d681SAndroid Build Coastguard Worker   // If no size growth is allowed for this inlining, set Threshold to 0.
617*9880d681SAndroid Build Coastguard Worker   if (!allowSizeGrowth(CS)) {
618*9880d681SAndroid Build Coastguard Worker     Threshold = 0;
619*9880d681SAndroid Build Coastguard Worker     return;
620*9880d681SAndroid Build Coastguard Worker   }
621*9880d681SAndroid Build Coastguard Worker 
622*9880d681SAndroid Build Coastguard Worker   Function *Caller = CS.getCaller();
623*9880d681SAndroid Build Coastguard Worker   if (DefaultInlineThreshold.getNumOccurrences() > 0) {
624*9880d681SAndroid Build Coastguard Worker     // Explicitly specified -inline-threhold overrides the threshold passed to
625*9880d681SAndroid Build Coastguard Worker     // CallAnalyzer's constructor.
626*9880d681SAndroid Build Coastguard Worker     Threshold = DefaultInlineThreshold;
627*9880d681SAndroid Build Coastguard Worker   } else {
628*9880d681SAndroid Build Coastguard Worker     // If -inline-threshold is not given, listen to the optsize and minsize
629*9880d681SAndroid Build Coastguard Worker     // attributes when they would decrease the threshold.
630*9880d681SAndroid Build Coastguard Worker     if (Caller->optForMinSize() && OptMinSizeThreshold < Threshold)
631*9880d681SAndroid Build Coastguard Worker       Threshold = OptMinSizeThreshold;
632*9880d681SAndroid Build Coastguard Worker     else if (Caller->optForSize() && OptSizeThreshold < Threshold)
633*9880d681SAndroid Build Coastguard Worker       Threshold = OptSizeThreshold;
634*9880d681SAndroid Build Coastguard Worker   }
635*9880d681SAndroid Build Coastguard Worker 
636*9880d681SAndroid Build Coastguard Worker   bool HotCallsite = false;
637*9880d681SAndroid Build Coastguard Worker   uint64_t TotalWeight;
638*9880d681SAndroid Build Coastguard Worker   if (CS.getInstruction()->extractProfTotalWeight(TotalWeight) &&
639*9880d681SAndroid Build Coastguard Worker       PSI->isHotCount(TotalWeight))
640*9880d681SAndroid Build Coastguard Worker     HotCallsite = true;
641*9880d681SAndroid Build Coastguard Worker 
642*9880d681SAndroid Build Coastguard Worker   // Listen to the inlinehint attribute or profile based hotness information
643*9880d681SAndroid Build Coastguard Worker   // when it would increase the threshold and the caller does not need to
644*9880d681SAndroid Build Coastguard Worker   // minimize its size.
645*9880d681SAndroid Build Coastguard Worker   bool InlineHint = Callee.hasFnAttribute(Attribute::InlineHint) ||
646*9880d681SAndroid Build Coastguard Worker                     PSI->isHotFunction(&Callee) ||
647*9880d681SAndroid Build Coastguard Worker                     HotCallsite;
648*9880d681SAndroid Build Coastguard Worker   if (InlineHint && HintThreshold > Threshold && !Caller->optForMinSize())
649*9880d681SAndroid Build Coastguard Worker     Threshold = HintThreshold;
650*9880d681SAndroid Build Coastguard Worker 
651*9880d681SAndroid Build Coastguard Worker   bool ColdCallee = PSI->isColdFunction(&Callee);
652*9880d681SAndroid Build Coastguard Worker   // Command line argument for DefaultInlineThreshold will override the default
653*9880d681SAndroid Build Coastguard Worker   // ColdThreshold. If we have -inline-threshold but no -inlinecold-threshold,
654*9880d681SAndroid Build Coastguard Worker   // do not use the default cold threshold even if it is smaller.
655*9880d681SAndroid Build Coastguard Worker   if ((DefaultInlineThreshold.getNumOccurrences() == 0 ||
656*9880d681SAndroid Build Coastguard Worker        ColdThreshold.getNumOccurrences() > 0) &&
657*9880d681SAndroid Build Coastguard Worker       ColdCallee && ColdThreshold < Threshold)
658*9880d681SAndroid Build Coastguard Worker     Threshold = ColdThreshold;
659*9880d681SAndroid Build Coastguard Worker 
660*9880d681SAndroid Build Coastguard Worker   // Finally, take the target-specific inlining threshold multiplier into
661*9880d681SAndroid Build Coastguard Worker   // account.
662*9880d681SAndroid Build Coastguard Worker   Threshold *= TTI.getInliningThresholdMultiplier();
663*9880d681SAndroid Build Coastguard Worker }
664*9880d681SAndroid Build Coastguard Worker 
visitCmpInst(CmpInst & I)665*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitCmpInst(CmpInst &I) {
666*9880d681SAndroid Build Coastguard Worker   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
667*9880d681SAndroid Build Coastguard Worker   // First try to handle simplified comparisons.
668*9880d681SAndroid Build Coastguard Worker   if (!isa<Constant>(LHS))
669*9880d681SAndroid Build Coastguard Worker     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
670*9880d681SAndroid Build Coastguard Worker       LHS = SimpleLHS;
671*9880d681SAndroid Build Coastguard Worker   if (!isa<Constant>(RHS))
672*9880d681SAndroid Build Coastguard Worker     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
673*9880d681SAndroid Build Coastguard Worker       RHS = SimpleRHS;
674*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
675*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(RHS))
676*9880d681SAndroid Build Coastguard Worker       if (Constant *C =
677*9880d681SAndroid Build Coastguard Worker               ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
678*9880d681SAndroid Build Coastguard Worker         SimplifiedValues[&I] = C;
679*9880d681SAndroid Build Coastguard Worker         return true;
680*9880d681SAndroid Build Coastguard Worker       }
681*9880d681SAndroid Build Coastguard Worker   }
682*9880d681SAndroid Build Coastguard Worker 
683*9880d681SAndroid Build Coastguard Worker   if (I.getOpcode() == Instruction::FCmp)
684*9880d681SAndroid Build Coastguard Worker     return false;
685*9880d681SAndroid Build Coastguard Worker 
686*9880d681SAndroid Build Coastguard Worker   // Otherwise look for a comparison between constant offset pointers with
687*9880d681SAndroid Build Coastguard Worker   // a common base.
688*9880d681SAndroid Build Coastguard Worker   Value *LHSBase, *RHSBase;
689*9880d681SAndroid Build Coastguard Worker   APInt LHSOffset, RHSOffset;
690*9880d681SAndroid Build Coastguard Worker   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
691*9880d681SAndroid Build Coastguard Worker   if (LHSBase) {
692*9880d681SAndroid Build Coastguard Worker     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
693*9880d681SAndroid Build Coastguard Worker     if (RHSBase && LHSBase == RHSBase) {
694*9880d681SAndroid Build Coastguard Worker       // We have common bases, fold the icmp to a constant based on the
695*9880d681SAndroid Build Coastguard Worker       // offsets.
696*9880d681SAndroid Build Coastguard Worker       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
697*9880d681SAndroid Build Coastguard Worker       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
698*9880d681SAndroid Build Coastguard Worker       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
699*9880d681SAndroid Build Coastguard Worker         SimplifiedValues[&I] = C;
700*9880d681SAndroid Build Coastguard Worker         ++NumConstantPtrCmps;
701*9880d681SAndroid Build Coastguard Worker         return true;
702*9880d681SAndroid Build Coastguard Worker       }
703*9880d681SAndroid Build Coastguard Worker     }
704*9880d681SAndroid Build Coastguard Worker   }
705*9880d681SAndroid Build Coastguard Worker 
706*9880d681SAndroid Build Coastguard Worker   // If the comparison is an equality comparison with null, we can simplify it
707*9880d681SAndroid Build Coastguard Worker   // if we know the value (argument) can't be null
708*9880d681SAndroid Build Coastguard Worker   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
709*9880d681SAndroid Build Coastguard Worker       isKnownNonNullInCallee(I.getOperand(0))) {
710*9880d681SAndroid Build Coastguard Worker     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
711*9880d681SAndroid Build Coastguard Worker     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
712*9880d681SAndroid Build Coastguard Worker                                       : ConstantInt::getFalse(I.getType());
713*9880d681SAndroid Build Coastguard Worker     return true;
714*9880d681SAndroid Build Coastguard Worker   }
715*9880d681SAndroid Build Coastguard Worker   // Finally check for SROA candidates in comparisons.
716*9880d681SAndroid Build Coastguard Worker   Value *SROAArg;
717*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, int>::iterator CostIt;
718*9880d681SAndroid Build Coastguard Worker   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
719*9880d681SAndroid Build Coastguard Worker     if (isa<ConstantPointerNull>(I.getOperand(1))) {
720*9880d681SAndroid Build Coastguard Worker       accumulateSROACost(CostIt, InlineConstants::InstrCost);
721*9880d681SAndroid Build Coastguard Worker       return true;
722*9880d681SAndroid Build Coastguard Worker     }
723*9880d681SAndroid Build Coastguard Worker 
724*9880d681SAndroid Build Coastguard Worker     disableSROA(CostIt);
725*9880d681SAndroid Build Coastguard Worker   }
726*9880d681SAndroid Build Coastguard Worker 
727*9880d681SAndroid Build Coastguard Worker   return false;
728*9880d681SAndroid Build Coastguard Worker }
729*9880d681SAndroid Build Coastguard Worker 
visitSub(BinaryOperator & I)730*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitSub(BinaryOperator &I) {
731*9880d681SAndroid Build Coastguard Worker   // Try to handle a special case: we can fold computing the difference of two
732*9880d681SAndroid Build Coastguard Worker   // constant-related pointers.
733*9880d681SAndroid Build Coastguard Worker   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
734*9880d681SAndroid Build Coastguard Worker   Value *LHSBase, *RHSBase;
735*9880d681SAndroid Build Coastguard Worker   APInt LHSOffset, RHSOffset;
736*9880d681SAndroid Build Coastguard Worker   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
737*9880d681SAndroid Build Coastguard Worker   if (LHSBase) {
738*9880d681SAndroid Build Coastguard Worker     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
739*9880d681SAndroid Build Coastguard Worker     if (RHSBase && LHSBase == RHSBase) {
740*9880d681SAndroid Build Coastguard Worker       // We have common bases, fold the subtract to a constant based on the
741*9880d681SAndroid Build Coastguard Worker       // offsets.
742*9880d681SAndroid Build Coastguard Worker       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
743*9880d681SAndroid Build Coastguard Worker       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
744*9880d681SAndroid Build Coastguard Worker       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
745*9880d681SAndroid Build Coastguard Worker         SimplifiedValues[&I] = C;
746*9880d681SAndroid Build Coastguard Worker         ++NumConstantPtrDiffs;
747*9880d681SAndroid Build Coastguard Worker         return true;
748*9880d681SAndroid Build Coastguard Worker       }
749*9880d681SAndroid Build Coastguard Worker     }
750*9880d681SAndroid Build Coastguard Worker   }
751*9880d681SAndroid Build Coastguard Worker 
752*9880d681SAndroid Build Coastguard Worker   // Otherwise, fall back to the generic logic for simplifying and handling
753*9880d681SAndroid Build Coastguard Worker   // instructions.
754*9880d681SAndroid Build Coastguard Worker   return Base::visitSub(I);
755*9880d681SAndroid Build Coastguard Worker }
756*9880d681SAndroid Build Coastguard Worker 
visitBinaryOperator(BinaryOperator & I)757*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
758*9880d681SAndroid Build Coastguard Worker   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
759*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = F.getParent()->getDataLayout();
760*9880d681SAndroid Build Coastguard Worker   if (!isa<Constant>(LHS))
761*9880d681SAndroid Build Coastguard Worker     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
762*9880d681SAndroid Build Coastguard Worker       LHS = SimpleLHS;
763*9880d681SAndroid Build Coastguard Worker   if (!isa<Constant>(RHS))
764*9880d681SAndroid Build Coastguard Worker     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
765*9880d681SAndroid Build Coastguard Worker       RHS = SimpleRHS;
766*9880d681SAndroid Build Coastguard Worker   Value *SimpleV = nullptr;
767*9880d681SAndroid Build Coastguard Worker   if (auto FI = dyn_cast<FPMathOperator>(&I))
768*9880d681SAndroid Build Coastguard Worker     SimpleV =
769*9880d681SAndroid Build Coastguard Worker         SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
770*9880d681SAndroid Build Coastguard Worker   else
771*9880d681SAndroid Build Coastguard Worker     SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
772*9880d681SAndroid Build Coastguard Worker 
773*9880d681SAndroid Build Coastguard Worker   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
774*9880d681SAndroid Build Coastguard Worker     SimplifiedValues[&I] = C;
775*9880d681SAndroid Build Coastguard Worker     return true;
776*9880d681SAndroid Build Coastguard Worker   }
777*9880d681SAndroid Build Coastguard Worker 
778*9880d681SAndroid Build Coastguard Worker   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
779*9880d681SAndroid Build Coastguard Worker   disableSROA(LHS);
780*9880d681SAndroid Build Coastguard Worker   disableSROA(RHS);
781*9880d681SAndroid Build Coastguard Worker 
782*9880d681SAndroid Build Coastguard Worker   return false;
783*9880d681SAndroid Build Coastguard Worker }
784*9880d681SAndroid Build Coastguard Worker 
visitLoad(LoadInst & I)785*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitLoad(LoadInst &I) {
786*9880d681SAndroid Build Coastguard Worker   Value *SROAArg;
787*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, int>::iterator CostIt;
788*9880d681SAndroid Build Coastguard Worker   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
789*9880d681SAndroid Build Coastguard Worker     if (I.isSimple()) {
790*9880d681SAndroid Build Coastguard Worker       accumulateSROACost(CostIt, InlineConstants::InstrCost);
791*9880d681SAndroid Build Coastguard Worker       return true;
792*9880d681SAndroid Build Coastguard Worker     }
793*9880d681SAndroid Build Coastguard Worker 
794*9880d681SAndroid Build Coastguard Worker     disableSROA(CostIt);
795*9880d681SAndroid Build Coastguard Worker   }
796*9880d681SAndroid Build Coastguard Worker 
797*9880d681SAndroid Build Coastguard Worker   return false;
798*9880d681SAndroid Build Coastguard Worker }
799*9880d681SAndroid Build Coastguard Worker 
visitStore(StoreInst & I)800*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitStore(StoreInst &I) {
801*9880d681SAndroid Build Coastguard Worker   Value *SROAArg;
802*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, int>::iterator CostIt;
803*9880d681SAndroid Build Coastguard Worker   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
804*9880d681SAndroid Build Coastguard Worker     if (I.isSimple()) {
805*9880d681SAndroid Build Coastguard Worker       accumulateSROACost(CostIt, InlineConstants::InstrCost);
806*9880d681SAndroid Build Coastguard Worker       return true;
807*9880d681SAndroid Build Coastguard Worker     }
808*9880d681SAndroid Build Coastguard Worker 
809*9880d681SAndroid Build Coastguard Worker     disableSROA(CostIt);
810*9880d681SAndroid Build Coastguard Worker   }
811*9880d681SAndroid Build Coastguard Worker 
812*9880d681SAndroid Build Coastguard Worker   return false;
813*9880d681SAndroid Build Coastguard Worker }
814*9880d681SAndroid Build Coastguard Worker 
visitExtractValue(ExtractValueInst & I)815*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
816*9880d681SAndroid Build Coastguard Worker   // Constant folding for extract value is trivial.
817*9880d681SAndroid Build Coastguard Worker   Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
818*9880d681SAndroid Build Coastguard Worker   if (!C)
819*9880d681SAndroid Build Coastguard Worker     C = SimplifiedValues.lookup(I.getAggregateOperand());
820*9880d681SAndroid Build Coastguard Worker   if (C) {
821*9880d681SAndroid Build Coastguard Worker     SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
822*9880d681SAndroid Build Coastguard Worker     return true;
823*9880d681SAndroid Build Coastguard Worker   }
824*9880d681SAndroid Build Coastguard Worker 
825*9880d681SAndroid Build Coastguard Worker   // SROA can look through these but give them a cost.
826*9880d681SAndroid Build Coastguard Worker   return false;
827*9880d681SAndroid Build Coastguard Worker }
828*9880d681SAndroid Build Coastguard Worker 
visitInsertValue(InsertValueInst & I)829*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
830*9880d681SAndroid Build Coastguard Worker   // Constant folding for insert value is trivial.
831*9880d681SAndroid Build Coastguard Worker   Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
832*9880d681SAndroid Build Coastguard Worker   if (!AggC)
833*9880d681SAndroid Build Coastguard Worker     AggC = SimplifiedValues.lookup(I.getAggregateOperand());
834*9880d681SAndroid Build Coastguard Worker   Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
835*9880d681SAndroid Build Coastguard Worker   if (!InsertedC)
836*9880d681SAndroid Build Coastguard Worker     InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
837*9880d681SAndroid Build Coastguard Worker   if (AggC && InsertedC) {
838*9880d681SAndroid Build Coastguard Worker     SimplifiedValues[&I] =
839*9880d681SAndroid Build Coastguard Worker         ConstantExpr::getInsertValue(AggC, InsertedC, I.getIndices());
840*9880d681SAndroid Build Coastguard Worker     return true;
841*9880d681SAndroid Build Coastguard Worker   }
842*9880d681SAndroid Build Coastguard Worker 
843*9880d681SAndroid Build Coastguard Worker   // SROA can look through these but give them a cost.
844*9880d681SAndroid Build Coastguard Worker   return false;
845*9880d681SAndroid Build Coastguard Worker }
846*9880d681SAndroid Build Coastguard Worker 
847*9880d681SAndroid Build Coastguard Worker /// \brief Try to simplify a call site.
848*9880d681SAndroid Build Coastguard Worker ///
849*9880d681SAndroid Build Coastguard Worker /// Takes a concrete function and callsite and tries to actually simplify it by
850*9880d681SAndroid Build Coastguard Worker /// analyzing the arguments and call itself with instsimplify. Returns true if
851*9880d681SAndroid Build Coastguard Worker /// it has simplified the callsite to some other entity (a constant), making it
852*9880d681SAndroid Build Coastguard Worker /// free.
simplifyCallSite(Function * F,CallSite CS)853*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
854*9880d681SAndroid Build Coastguard Worker   // FIXME: Using the instsimplify logic directly for this is inefficient
855*9880d681SAndroid Build Coastguard Worker   // because we have to continually rebuild the argument list even when no
856*9880d681SAndroid Build Coastguard Worker   // simplifications can be performed. Until that is fixed with remapping
857*9880d681SAndroid Build Coastguard Worker   // inside of instsimplify, directly constant fold calls here.
858*9880d681SAndroid Build Coastguard Worker   if (!canConstantFoldCallTo(F))
859*9880d681SAndroid Build Coastguard Worker     return false;
860*9880d681SAndroid Build Coastguard Worker 
861*9880d681SAndroid Build Coastguard Worker   // Try to re-map the arguments to constants.
862*9880d681SAndroid Build Coastguard Worker   SmallVector<Constant *, 4> ConstantArgs;
863*9880d681SAndroid Build Coastguard Worker   ConstantArgs.reserve(CS.arg_size());
864*9880d681SAndroid Build Coastguard Worker   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E;
865*9880d681SAndroid Build Coastguard Worker        ++I) {
866*9880d681SAndroid Build Coastguard Worker     Constant *C = dyn_cast<Constant>(*I);
867*9880d681SAndroid Build Coastguard Worker     if (!C)
868*9880d681SAndroid Build Coastguard Worker       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
869*9880d681SAndroid Build Coastguard Worker     if (!C)
870*9880d681SAndroid Build Coastguard Worker       return false; // This argument doesn't map to a constant.
871*9880d681SAndroid Build Coastguard Worker 
872*9880d681SAndroid Build Coastguard Worker     ConstantArgs.push_back(C);
873*9880d681SAndroid Build Coastguard Worker   }
874*9880d681SAndroid Build Coastguard Worker   if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
875*9880d681SAndroid Build Coastguard Worker     SimplifiedValues[CS.getInstruction()] = C;
876*9880d681SAndroid Build Coastguard Worker     return true;
877*9880d681SAndroid Build Coastguard Worker   }
878*9880d681SAndroid Build Coastguard Worker 
879*9880d681SAndroid Build Coastguard Worker   return false;
880*9880d681SAndroid Build Coastguard Worker }
881*9880d681SAndroid Build Coastguard Worker 
visitCallSite(CallSite CS)882*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitCallSite(CallSite CS) {
883*9880d681SAndroid Build Coastguard Worker   if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
884*9880d681SAndroid Build Coastguard Worker       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
885*9880d681SAndroid Build Coastguard Worker     // This aborts the entire analysis.
886*9880d681SAndroid Build Coastguard Worker     ExposesReturnsTwice = true;
887*9880d681SAndroid Build Coastguard Worker     return false;
888*9880d681SAndroid Build Coastguard Worker   }
889*9880d681SAndroid Build Coastguard Worker   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->cannotDuplicate())
890*9880d681SAndroid Build Coastguard Worker     ContainsNoDuplicateCall = true;
891*9880d681SAndroid Build Coastguard Worker 
892*9880d681SAndroid Build Coastguard Worker   if (Function *F = CS.getCalledFunction()) {
893*9880d681SAndroid Build Coastguard Worker     // When we have a concrete function, first try to simplify it directly.
894*9880d681SAndroid Build Coastguard Worker     if (simplifyCallSite(F, CS))
895*9880d681SAndroid Build Coastguard Worker       return true;
896*9880d681SAndroid Build Coastguard Worker 
897*9880d681SAndroid Build Coastguard Worker     // Next check if it is an intrinsic we know about.
898*9880d681SAndroid Build Coastguard Worker     // FIXME: Lift this into part of the InstVisitor.
899*9880d681SAndroid Build Coastguard Worker     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
900*9880d681SAndroid Build Coastguard Worker       switch (II->getIntrinsicID()) {
901*9880d681SAndroid Build Coastguard Worker       default:
902*9880d681SAndroid Build Coastguard Worker         return Base::visitCallSite(CS);
903*9880d681SAndroid Build Coastguard Worker 
904*9880d681SAndroid Build Coastguard Worker       case Intrinsic::load_relative:
905*9880d681SAndroid Build Coastguard Worker         // This is normally lowered to 4 LLVM instructions.
906*9880d681SAndroid Build Coastguard Worker         Cost += 3 * InlineConstants::InstrCost;
907*9880d681SAndroid Build Coastguard Worker         return false;
908*9880d681SAndroid Build Coastguard Worker 
909*9880d681SAndroid Build Coastguard Worker       case Intrinsic::memset:
910*9880d681SAndroid Build Coastguard Worker       case Intrinsic::memcpy:
911*9880d681SAndroid Build Coastguard Worker       case Intrinsic::memmove:
912*9880d681SAndroid Build Coastguard Worker         // SROA can usually chew through these intrinsics, but they aren't free.
913*9880d681SAndroid Build Coastguard Worker         return false;
914*9880d681SAndroid Build Coastguard Worker       case Intrinsic::localescape:
915*9880d681SAndroid Build Coastguard Worker         HasFrameEscape = true;
916*9880d681SAndroid Build Coastguard Worker         return false;
917*9880d681SAndroid Build Coastguard Worker       }
918*9880d681SAndroid Build Coastguard Worker     }
919*9880d681SAndroid Build Coastguard Worker 
920*9880d681SAndroid Build Coastguard Worker     if (F == CS.getInstruction()->getParent()->getParent()) {
921*9880d681SAndroid Build Coastguard Worker       // This flag will fully abort the analysis, so don't bother with anything
922*9880d681SAndroid Build Coastguard Worker       // else.
923*9880d681SAndroid Build Coastguard Worker       IsRecursiveCall = true;
924*9880d681SAndroid Build Coastguard Worker       return false;
925*9880d681SAndroid Build Coastguard Worker     }
926*9880d681SAndroid Build Coastguard Worker 
927*9880d681SAndroid Build Coastguard Worker     if (TTI.isLoweredToCall(F)) {
928*9880d681SAndroid Build Coastguard Worker       // We account for the average 1 instruction per call argument setup
929*9880d681SAndroid Build Coastguard Worker       // here.
930*9880d681SAndroid Build Coastguard Worker       Cost += CS.arg_size() * InlineConstants::InstrCost;
931*9880d681SAndroid Build Coastguard Worker 
932*9880d681SAndroid Build Coastguard Worker       // Everything other than inline ASM will also have a significant cost
933*9880d681SAndroid Build Coastguard Worker       // merely from making the call.
934*9880d681SAndroid Build Coastguard Worker       if (!isa<InlineAsm>(CS.getCalledValue()))
935*9880d681SAndroid Build Coastguard Worker         Cost += InlineConstants::CallPenalty;
936*9880d681SAndroid Build Coastguard Worker     }
937*9880d681SAndroid Build Coastguard Worker 
938*9880d681SAndroid Build Coastguard Worker     return Base::visitCallSite(CS);
939*9880d681SAndroid Build Coastguard Worker   }
940*9880d681SAndroid Build Coastguard Worker 
941*9880d681SAndroid Build Coastguard Worker   // Otherwise we're in a very special case -- an indirect function call. See
942*9880d681SAndroid Build Coastguard Worker   // if we can be particularly clever about this.
943*9880d681SAndroid Build Coastguard Worker   Value *Callee = CS.getCalledValue();
944*9880d681SAndroid Build Coastguard Worker 
945*9880d681SAndroid Build Coastguard Worker   // First, pay the price of the argument setup. We account for the average
946*9880d681SAndroid Build Coastguard Worker   // 1 instruction per call argument setup here.
947*9880d681SAndroid Build Coastguard Worker   Cost += CS.arg_size() * InlineConstants::InstrCost;
948*9880d681SAndroid Build Coastguard Worker 
949*9880d681SAndroid Build Coastguard Worker   // Next, check if this happens to be an indirect function call to a known
950*9880d681SAndroid Build Coastguard Worker   // function in this inline context. If not, we've done all we can.
951*9880d681SAndroid Build Coastguard Worker   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
952*9880d681SAndroid Build Coastguard Worker   if (!F)
953*9880d681SAndroid Build Coastguard Worker     return Base::visitCallSite(CS);
954*9880d681SAndroid Build Coastguard Worker 
955*9880d681SAndroid Build Coastguard Worker   // If we have a constant that we are calling as a function, we can peer
956*9880d681SAndroid Build Coastguard Worker   // through it and see the function target. This happens not infrequently
957*9880d681SAndroid Build Coastguard Worker   // during devirtualization and so we want to give it a hefty bonus for
958*9880d681SAndroid Build Coastguard Worker   // inlining, but cap that bonus in the event that inlining wouldn't pan
959*9880d681SAndroid Build Coastguard Worker   // out. Pretend to inline the function, with a custom threshold.
960*9880d681SAndroid Build Coastguard Worker   CallAnalyzer CA(TTI, ACT, PSI, *F, InlineConstants::IndirectCallThreshold,
961*9880d681SAndroid Build Coastguard Worker                   CS);
962*9880d681SAndroid Build Coastguard Worker   if (CA.analyzeCall(CS)) {
963*9880d681SAndroid Build Coastguard Worker     // We were able to inline the indirect call! Subtract the cost from the
964*9880d681SAndroid Build Coastguard Worker     // threshold to get the bonus we want to apply, but don't go below zero.
965*9880d681SAndroid Build Coastguard Worker     Cost -= std::max(0, CA.getThreshold() - CA.getCost());
966*9880d681SAndroid Build Coastguard Worker   }
967*9880d681SAndroid Build Coastguard Worker 
968*9880d681SAndroid Build Coastguard Worker   return Base::visitCallSite(CS);
969*9880d681SAndroid Build Coastguard Worker }
970*9880d681SAndroid Build Coastguard Worker 
visitReturnInst(ReturnInst & RI)971*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
972*9880d681SAndroid Build Coastguard Worker   // At least one return instruction will be free after inlining.
973*9880d681SAndroid Build Coastguard Worker   bool Free = !HasReturn;
974*9880d681SAndroid Build Coastguard Worker   HasReturn = true;
975*9880d681SAndroid Build Coastguard Worker   return Free;
976*9880d681SAndroid Build Coastguard Worker }
977*9880d681SAndroid Build Coastguard Worker 
visitBranchInst(BranchInst & BI)978*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
979*9880d681SAndroid Build Coastguard Worker   // We model unconditional branches as essentially free -- they really
980*9880d681SAndroid Build Coastguard Worker   // shouldn't exist at all, but handling them makes the behavior of the
981*9880d681SAndroid Build Coastguard Worker   // inliner more regular and predictable. Interestingly, conditional branches
982*9880d681SAndroid Build Coastguard Worker   // which will fold away are also free.
983*9880d681SAndroid Build Coastguard Worker   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
984*9880d681SAndroid Build Coastguard Worker          dyn_cast_or_null<ConstantInt>(
985*9880d681SAndroid Build Coastguard Worker              SimplifiedValues.lookup(BI.getCondition()));
986*9880d681SAndroid Build Coastguard Worker }
987*9880d681SAndroid Build Coastguard Worker 
visitSwitchInst(SwitchInst & SI)988*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
989*9880d681SAndroid Build Coastguard Worker   // We model unconditional switches as free, see the comments on handling
990*9880d681SAndroid Build Coastguard Worker   // branches.
991*9880d681SAndroid Build Coastguard Worker   if (isa<ConstantInt>(SI.getCondition()))
992*9880d681SAndroid Build Coastguard Worker     return true;
993*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
994*9880d681SAndroid Build Coastguard Worker     if (isa<ConstantInt>(V))
995*9880d681SAndroid Build Coastguard Worker       return true;
996*9880d681SAndroid Build Coastguard Worker 
997*9880d681SAndroid Build Coastguard Worker   // Otherwise, we need to accumulate a cost proportional to the number of
998*9880d681SAndroid Build Coastguard Worker   // distinct successor blocks. This fan-out in the CFG cannot be represented
999*9880d681SAndroid Build Coastguard Worker   // for free even if we can represent the core switch as a jumptable that
1000*9880d681SAndroid Build Coastguard Worker   // takes a single instruction.
1001*9880d681SAndroid Build Coastguard Worker   //
1002*9880d681SAndroid Build Coastguard Worker   // NB: We convert large switches which are just used to initialize large phi
1003*9880d681SAndroid Build Coastguard Worker   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
1004*9880d681SAndroid Build Coastguard Worker   // inlining those. It will prevent inlining in cases where the optimization
1005*9880d681SAndroid Build Coastguard Worker   // does not (yet) fire.
1006*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<BasicBlock *, 8> SuccessorBlocks;
1007*9880d681SAndroid Build Coastguard Worker   SuccessorBlocks.insert(SI.getDefaultDest());
1008*9880d681SAndroid Build Coastguard Worker   for (auto I = SI.case_begin(), E = SI.case_end(); I != E; ++I)
1009*9880d681SAndroid Build Coastguard Worker     SuccessorBlocks.insert(I.getCaseSuccessor());
1010*9880d681SAndroid Build Coastguard Worker   // Add cost corresponding to the number of distinct destinations. The first
1011*9880d681SAndroid Build Coastguard Worker   // we model as free because of fallthrough.
1012*9880d681SAndroid Build Coastguard Worker   Cost += (SuccessorBlocks.size() - 1) * InlineConstants::InstrCost;
1013*9880d681SAndroid Build Coastguard Worker   return false;
1014*9880d681SAndroid Build Coastguard Worker }
1015*9880d681SAndroid Build Coastguard Worker 
visitIndirectBrInst(IndirectBrInst & IBI)1016*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
1017*9880d681SAndroid Build Coastguard Worker   // We never want to inline functions that contain an indirectbr.  This is
1018*9880d681SAndroid Build Coastguard Worker   // incorrect because all the blockaddress's (in static global initializers
1019*9880d681SAndroid Build Coastguard Worker   // for example) would be referring to the original function, and this
1020*9880d681SAndroid Build Coastguard Worker   // indirect jump would jump from the inlined copy of the function into the
1021*9880d681SAndroid Build Coastguard Worker   // original function which is extremely undefined behavior.
1022*9880d681SAndroid Build Coastguard Worker   // FIXME: This logic isn't really right; we can safely inline functions with
1023*9880d681SAndroid Build Coastguard Worker   // indirectbr's as long as no other function or global references the
1024*9880d681SAndroid Build Coastguard Worker   // blockaddress of a block within the current function.
1025*9880d681SAndroid Build Coastguard Worker   HasIndirectBr = true;
1026*9880d681SAndroid Build Coastguard Worker   return false;
1027*9880d681SAndroid Build Coastguard Worker }
1028*9880d681SAndroid Build Coastguard Worker 
visitResumeInst(ResumeInst & RI)1029*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
1030*9880d681SAndroid Build Coastguard Worker   // FIXME: It's not clear that a single instruction is an accurate model for
1031*9880d681SAndroid Build Coastguard Worker   // the inline cost of a resume instruction.
1032*9880d681SAndroid Build Coastguard Worker   return false;
1033*9880d681SAndroid Build Coastguard Worker }
1034*9880d681SAndroid Build Coastguard Worker 
visitCleanupReturnInst(CleanupReturnInst & CRI)1035*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
1036*9880d681SAndroid Build Coastguard Worker   // FIXME: It's not clear that a single instruction is an accurate model for
1037*9880d681SAndroid Build Coastguard Worker   // the inline cost of a cleanupret instruction.
1038*9880d681SAndroid Build Coastguard Worker   return false;
1039*9880d681SAndroid Build Coastguard Worker }
1040*9880d681SAndroid Build Coastguard Worker 
visitCatchReturnInst(CatchReturnInst & CRI)1041*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
1042*9880d681SAndroid Build Coastguard Worker   // FIXME: It's not clear that a single instruction is an accurate model for
1043*9880d681SAndroid Build Coastguard Worker   // the inline cost of a catchret instruction.
1044*9880d681SAndroid Build Coastguard Worker   return false;
1045*9880d681SAndroid Build Coastguard Worker }
1046*9880d681SAndroid Build Coastguard Worker 
visitUnreachableInst(UnreachableInst & I)1047*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
1048*9880d681SAndroid Build Coastguard Worker   // FIXME: It might be reasonably to discount the cost of instructions leading
1049*9880d681SAndroid Build Coastguard Worker   // to unreachable as they have the lowest possible impact on both runtime and
1050*9880d681SAndroid Build Coastguard Worker   // code size.
1051*9880d681SAndroid Build Coastguard Worker   return true; // No actual code is needed for unreachable.
1052*9880d681SAndroid Build Coastguard Worker }
1053*9880d681SAndroid Build Coastguard Worker 
visitInstruction(Instruction & I)1054*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::visitInstruction(Instruction &I) {
1055*9880d681SAndroid Build Coastguard Worker   // Some instructions are free. All of the free intrinsics can also be
1056*9880d681SAndroid Build Coastguard Worker   // handled by SROA, etc.
1057*9880d681SAndroid Build Coastguard Worker   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
1058*9880d681SAndroid Build Coastguard Worker     return true;
1059*9880d681SAndroid Build Coastguard Worker 
1060*9880d681SAndroid Build Coastguard Worker   // We found something we don't understand or can't handle. Mark any SROA-able
1061*9880d681SAndroid Build Coastguard Worker   // values in the operand list as no longer viable.
1062*9880d681SAndroid Build Coastguard Worker   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
1063*9880d681SAndroid Build Coastguard Worker     disableSROA(*OI);
1064*9880d681SAndroid Build Coastguard Worker 
1065*9880d681SAndroid Build Coastguard Worker   return false;
1066*9880d681SAndroid Build Coastguard Worker }
1067*9880d681SAndroid Build Coastguard Worker 
1068*9880d681SAndroid Build Coastguard Worker /// \brief Analyze a basic block for its contribution to the inline cost.
1069*9880d681SAndroid Build Coastguard Worker ///
1070*9880d681SAndroid Build Coastguard Worker /// This method walks the analyzer over every instruction in the given basic
1071*9880d681SAndroid Build Coastguard Worker /// block and accounts for their cost during inlining at this callsite. It
1072*9880d681SAndroid Build Coastguard Worker /// aborts early if the threshold has been exceeded or an impossible to inline
1073*9880d681SAndroid Build Coastguard Worker /// construct has been detected. It returns false if inlining is no longer
1074*9880d681SAndroid Build Coastguard Worker /// viable, and true if inlining remains viable.
analyzeBlock(BasicBlock * BB,SmallPtrSetImpl<const Value * > & EphValues)1075*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::analyzeBlock(BasicBlock *BB,
1076*9880d681SAndroid Build Coastguard Worker                                 SmallPtrSetImpl<const Value *> &EphValues) {
1077*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1078*9880d681SAndroid Build Coastguard Worker     // FIXME: Currently, the number of instructions in a function regardless of
1079*9880d681SAndroid Build Coastguard Worker     // our ability to simplify them during inline to constants or dead code,
1080*9880d681SAndroid Build Coastguard Worker     // are actually used by the vector bonus heuristic. As long as that's true,
1081*9880d681SAndroid Build Coastguard Worker     // we have to special case debug intrinsics here to prevent differences in
1082*9880d681SAndroid Build Coastguard Worker     // inlining due to debug symbols. Eventually, the number of unsimplified
1083*9880d681SAndroid Build Coastguard Worker     // instructions shouldn't factor into the cost computation, but until then,
1084*9880d681SAndroid Build Coastguard Worker     // hack around it here.
1085*9880d681SAndroid Build Coastguard Worker     if (isa<DbgInfoIntrinsic>(I))
1086*9880d681SAndroid Build Coastguard Worker       continue;
1087*9880d681SAndroid Build Coastguard Worker 
1088*9880d681SAndroid Build Coastguard Worker     // Skip ephemeral values.
1089*9880d681SAndroid Build Coastguard Worker     if (EphValues.count(&*I))
1090*9880d681SAndroid Build Coastguard Worker       continue;
1091*9880d681SAndroid Build Coastguard Worker 
1092*9880d681SAndroid Build Coastguard Worker     ++NumInstructions;
1093*9880d681SAndroid Build Coastguard Worker     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
1094*9880d681SAndroid Build Coastguard Worker       ++NumVectorInstructions;
1095*9880d681SAndroid Build Coastguard Worker 
1096*9880d681SAndroid Build Coastguard Worker     // If the instruction is floating point, and the target says this operation
1097*9880d681SAndroid Build Coastguard Worker     // is expensive or the function has the "use-soft-float" attribute, this may
1098*9880d681SAndroid Build Coastguard Worker     // eventually become a library call. Treat the cost as such.
1099*9880d681SAndroid Build Coastguard Worker     if (I->getType()->isFloatingPointTy()) {
1100*9880d681SAndroid Build Coastguard Worker       bool hasSoftFloatAttr = false;
1101*9880d681SAndroid Build Coastguard Worker 
1102*9880d681SAndroid Build Coastguard Worker       // If the function has the "use-soft-float" attribute, mark it as
1103*9880d681SAndroid Build Coastguard Worker       // expensive.
1104*9880d681SAndroid Build Coastguard Worker       if (F.hasFnAttribute("use-soft-float")) {
1105*9880d681SAndroid Build Coastguard Worker         Attribute Attr = F.getFnAttribute("use-soft-float");
1106*9880d681SAndroid Build Coastguard Worker         StringRef Val = Attr.getValueAsString();
1107*9880d681SAndroid Build Coastguard Worker         if (Val == "true")
1108*9880d681SAndroid Build Coastguard Worker           hasSoftFloatAttr = true;
1109*9880d681SAndroid Build Coastguard Worker       }
1110*9880d681SAndroid Build Coastguard Worker 
1111*9880d681SAndroid Build Coastguard Worker       if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive ||
1112*9880d681SAndroid Build Coastguard Worker           hasSoftFloatAttr)
1113*9880d681SAndroid Build Coastguard Worker         Cost += InlineConstants::CallPenalty;
1114*9880d681SAndroid Build Coastguard Worker     }
1115*9880d681SAndroid Build Coastguard Worker 
1116*9880d681SAndroid Build Coastguard Worker     // If the instruction simplified to a constant, there is no cost to this
1117*9880d681SAndroid Build Coastguard Worker     // instruction. Visit the instructions using our InstVisitor to account for
1118*9880d681SAndroid Build Coastguard Worker     // all of the per-instruction logic. The visit tree returns true if we
1119*9880d681SAndroid Build Coastguard Worker     // consumed the instruction in any way, and false if the instruction's base
1120*9880d681SAndroid Build Coastguard Worker     // cost should count against inlining.
1121*9880d681SAndroid Build Coastguard Worker     if (Base::visit(&*I))
1122*9880d681SAndroid Build Coastguard Worker       ++NumInstructionsSimplified;
1123*9880d681SAndroid Build Coastguard Worker     else
1124*9880d681SAndroid Build Coastguard Worker       Cost += InlineConstants::InstrCost;
1125*9880d681SAndroid Build Coastguard Worker 
1126*9880d681SAndroid Build Coastguard Worker     // If the visit this instruction detected an uninlinable pattern, abort.
1127*9880d681SAndroid Build Coastguard Worker     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
1128*9880d681SAndroid Build Coastguard Worker         HasIndirectBr || HasFrameEscape)
1129*9880d681SAndroid Build Coastguard Worker       return false;
1130*9880d681SAndroid Build Coastguard Worker 
1131*9880d681SAndroid Build Coastguard Worker     // If the caller is a recursive function then we don't want to inline
1132*9880d681SAndroid Build Coastguard Worker     // functions which allocate a lot of stack space because it would increase
1133*9880d681SAndroid Build Coastguard Worker     // the caller stack usage dramatically.
1134*9880d681SAndroid Build Coastguard Worker     if (IsCallerRecursive &&
1135*9880d681SAndroid Build Coastguard Worker         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
1136*9880d681SAndroid Build Coastguard Worker       return false;
1137*9880d681SAndroid Build Coastguard Worker 
1138*9880d681SAndroid Build Coastguard Worker     // Check if we've past the maximum possible threshold so we don't spin in
1139*9880d681SAndroid Build Coastguard Worker     // huge basic blocks that will never inline.
1140*9880d681SAndroid Build Coastguard Worker     if (Cost > Threshold)
1141*9880d681SAndroid Build Coastguard Worker       return false;
1142*9880d681SAndroid Build Coastguard Worker   }
1143*9880d681SAndroid Build Coastguard Worker 
1144*9880d681SAndroid Build Coastguard Worker   return true;
1145*9880d681SAndroid Build Coastguard Worker }
1146*9880d681SAndroid Build Coastguard Worker 
1147*9880d681SAndroid Build Coastguard Worker /// \brief Compute the base pointer and cumulative constant offsets for V.
1148*9880d681SAndroid Build Coastguard Worker ///
1149*9880d681SAndroid Build Coastguard Worker /// This strips all constant offsets off of V, leaving it the base pointer, and
1150*9880d681SAndroid Build Coastguard Worker /// accumulates the total constant offset applied in the returned constant. It
1151*9880d681SAndroid Build Coastguard Worker /// returns 0 if V is not a pointer, and returns the constant '0' if there are
1152*9880d681SAndroid Build Coastguard Worker /// no constant offsets applied.
stripAndComputeInBoundsConstantOffsets(Value * & V)1153*9880d681SAndroid Build Coastguard Worker ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
1154*9880d681SAndroid Build Coastguard Worker   if (!V->getType()->isPointerTy())
1155*9880d681SAndroid Build Coastguard Worker     return nullptr;
1156*9880d681SAndroid Build Coastguard Worker 
1157*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = F.getParent()->getDataLayout();
1158*9880d681SAndroid Build Coastguard Worker   unsigned IntPtrWidth = DL.getPointerSizeInBits();
1159*9880d681SAndroid Build Coastguard Worker   APInt Offset = APInt::getNullValue(IntPtrWidth);
1160*9880d681SAndroid Build Coastguard Worker 
1161*9880d681SAndroid Build Coastguard Worker   // Even though we don't look through PHI nodes, we could be called on an
1162*9880d681SAndroid Build Coastguard Worker   // instruction in an unreachable block, which may be on a cycle.
1163*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<Value *, 4> Visited;
1164*9880d681SAndroid Build Coastguard Worker   Visited.insert(V);
1165*9880d681SAndroid Build Coastguard Worker   do {
1166*9880d681SAndroid Build Coastguard Worker     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1167*9880d681SAndroid Build Coastguard Worker       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
1168*9880d681SAndroid Build Coastguard Worker         return nullptr;
1169*9880d681SAndroid Build Coastguard Worker       V = GEP->getPointerOperand();
1170*9880d681SAndroid Build Coastguard Worker     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1171*9880d681SAndroid Build Coastguard Worker       V = cast<Operator>(V)->getOperand(0);
1172*9880d681SAndroid Build Coastguard Worker     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1173*9880d681SAndroid Build Coastguard Worker       if (GA->isInterposable())
1174*9880d681SAndroid Build Coastguard Worker         break;
1175*9880d681SAndroid Build Coastguard Worker       V = GA->getAliasee();
1176*9880d681SAndroid Build Coastguard Worker     } else {
1177*9880d681SAndroid Build Coastguard Worker       break;
1178*9880d681SAndroid Build Coastguard Worker     }
1179*9880d681SAndroid Build Coastguard Worker     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1180*9880d681SAndroid Build Coastguard Worker   } while (Visited.insert(V).second);
1181*9880d681SAndroid Build Coastguard Worker 
1182*9880d681SAndroid Build Coastguard Worker   Type *IntPtrTy = DL.getIntPtrType(V->getContext());
1183*9880d681SAndroid Build Coastguard Worker   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
1184*9880d681SAndroid Build Coastguard Worker }
1185*9880d681SAndroid Build Coastguard Worker 
1186*9880d681SAndroid Build Coastguard Worker /// \brief Analyze a call site for potential inlining.
1187*9880d681SAndroid Build Coastguard Worker ///
1188*9880d681SAndroid Build Coastguard Worker /// Returns true if inlining this call is viable, and false if it is not
1189*9880d681SAndroid Build Coastguard Worker /// viable. It computes the cost and adjusts the threshold based on numerous
1190*9880d681SAndroid Build Coastguard Worker /// factors and heuristics. If this method returns false but the computed cost
1191*9880d681SAndroid Build Coastguard Worker /// is below the computed threshold, then inlining was forcibly disabled by
1192*9880d681SAndroid Build Coastguard Worker /// some artifact of the routine.
analyzeCall(CallSite CS)1193*9880d681SAndroid Build Coastguard Worker bool CallAnalyzer::analyzeCall(CallSite CS) {
1194*9880d681SAndroid Build Coastguard Worker   ++NumCallsAnalyzed;
1195*9880d681SAndroid Build Coastguard Worker 
1196*9880d681SAndroid Build Coastguard Worker   // Perform some tweaks to the cost and threshold based on the direct
1197*9880d681SAndroid Build Coastguard Worker   // callsite information.
1198*9880d681SAndroid Build Coastguard Worker 
1199*9880d681SAndroid Build Coastguard Worker   // We want to more aggressively inline vector-dense kernels, so up the
1200*9880d681SAndroid Build Coastguard Worker   // threshold, and we'll lower it if the % of vector instructions gets too
1201*9880d681SAndroid Build Coastguard Worker   // low. Note that these bonuses are some what arbitrary and evolved over time
1202*9880d681SAndroid Build Coastguard Worker   // by accident as much as because they are principled bonuses.
1203*9880d681SAndroid Build Coastguard Worker   //
1204*9880d681SAndroid Build Coastguard Worker   // FIXME: It would be nice to remove all such bonuses. At least it would be
1205*9880d681SAndroid Build Coastguard Worker   // nice to base the bonus values on something more scientific.
1206*9880d681SAndroid Build Coastguard Worker   assert(NumInstructions == 0);
1207*9880d681SAndroid Build Coastguard Worker   assert(NumVectorInstructions == 0);
1208*9880d681SAndroid Build Coastguard Worker 
1209*9880d681SAndroid Build Coastguard Worker   // Update the threshold based on callsite properties
1210*9880d681SAndroid Build Coastguard Worker   updateThreshold(CS, F);
1211*9880d681SAndroid Build Coastguard Worker 
1212*9880d681SAndroid Build Coastguard Worker   FiftyPercentVectorBonus = 3 * Threshold / 2;
1213*9880d681SAndroid Build Coastguard Worker   TenPercentVectorBonus = 3 * Threshold / 4;
1214*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = F.getParent()->getDataLayout();
1215*9880d681SAndroid Build Coastguard Worker 
1216*9880d681SAndroid Build Coastguard Worker   // Track whether the post-inlining function would have more than one basic
1217*9880d681SAndroid Build Coastguard Worker   // block. A single basic block is often intended for inlining. Balloon the
1218*9880d681SAndroid Build Coastguard Worker   // threshold by 50% until we pass the single-BB phase.
1219*9880d681SAndroid Build Coastguard Worker   bool SingleBB = true;
1220*9880d681SAndroid Build Coastguard Worker   int SingleBBBonus = Threshold / 2;
1221*9880d681SAndroid Build Coastguard Worker 
1222*9880d681SAndroid Build Coastguard Worker   // Speculatively apply all possible bonuses to Threshold. If cost exceeds
1223*9880d681SAndroid Build Coastguard Worker   // this Threshold any time, and cost cannot decrease, we can stop processing
1224*9880d681SAndroid Build Coastguard Worker   // the rest of the function body.
1225*9880d681SAndroid Build Coastguard Worker   Threshold += (SingleBBBonus + FiftyPercentVectorBonus);
1226*9880d681SAndroid Build Coastguard Worker 
1227*9880d681SAndroid Build Coastguard Worker   // Give out bonuses per argument, as the instructions setting them up will
1228*9880d681SAndroid Build Coastguard Worker   // be gone after inlining.
1229*9880d681SAndroid Build Coastguard Worker   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
1230*9880d681SAndroid Build Coastguard Worker     if (CS.isByValArgument(I)) {
1231*9880d681SAndroid Build Coastguard Worker       // We approximate the number of loads and stores needed by dividing the
1232*9880d681SAndroid Build Coastguard Worker       // size of the byval type by the target's pointer size.
1233*9880d681SAndroid Build Coastguard Worker       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
1234*9880d681SAndroid Build Coastguard Worker       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
1235*9880d681SAndroid Build Coastguard Worker       unsigned PointerSize = DL.getPointerSizeInBits();
1236*9880d681SAndroid Build Coastguard Worker       // Ceiling division.
1237*9880d681SAndroid Build Coastguard Worker       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
1238*9880d681SAndroid Build Coastguard Worker 
1239*9880d681SAndroid Build Coastguard Worker       // If it generates more than 8 stores it is likely to be expanded as an
1240*9880d681SAndroid Build Coastguard Worker       // inline memcpy so we take that as an upper bound. Otherwise we assume
1241*9880d681SAndroid Build Coastguard Worker       // one load and one store per word copied.
1242*9880d681SAndroid Build Coastguard Worker       // FIXME: The maxStoresPerMemcpy setting from the target should be used
1243*9880d681SAndroid Build Coastguard Worker       // here instead of a magic number of 8, but it's not available via
1244*9880d681SAndroid Build Coastguard Worker       // DataLayout.
1245*9880d681SAndroid Build Coastguard Worker       NumStores = std::min(NumStores, 8U);
1246*9880d681SAndroid Build Coastguard Worker 
1247*9880d681SAndroid Build Coastguard Worker       Cost -= 2 * NumStores * InlineConstants::InstrCost;
1248*9880d681SAndroid Build Coastguard Worker     } else {
1249*9880d681SAndroid Build Coastguard Worker       // For non-byval arguments subtract off one instruction per call
1250*9880d681SAndroid Build Coastguard Worker       // argument.
1251*9880d681SAndroid Build Coastguard Worker       Cost -= InlineConstants::InstrCost;
1252*9880d681SAndroid Build Coastguard Worker     }
1253*9880d681SAndroid Build Coastguard Worker   }
1254*9880d681SAndroid Build Coastguard Worker 
1255*9880d681SAndroid Build Coastguard Worker   // If there is only one call of the function, and it has internal linkage,
1256*9880d681SAndroid Build Coastguard Worker   // the cost of inlining it drops dramatically.
1257*9880d681SAndroid Build Coastguard Worker   bool OnlyOneCallAndLocalLinkage =
1258*9880d681SAndroid Build Coastguard Worker       F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction();
1259*9880d681SAndroid Build Coastguard Worker   if (OnlyOneCallAndLocalLinkage)
1260*9880d681SAndroid Build Coastguard Worker     Cost += InlineConstants::LastCallToStaticBonus;
1261*9880d681SAndroid Build Coastguard Worker 
1262*9880d681SAndroid Build Coastguard Worker   // If this function uses the coldcc calling convention, prefer not to inline
1263*9880d681SAndroid Build Coastguard Worker   // it.
1264*9880d681SAndroid Build Coastguard Worker   if (F.getCallingConv() == CallingConv::Cold)
1265*9880d681SAndroid Build Coastguard Worker     Cost += InlineConstants::ColdccPenalty;
1266*9880d681SAndroid Build Coastguard Worker 
1267*9880d681SAndroid Build Coastguard Worker   // Check if we're done. This can happen due to bonuses and penalties.
1268*9880d681SAndroid Build Coastguard Worker   if (Cost > Threshold)
1269*9880d681SAndroid Build Coastguard Worker     return false;
1270*9880d681SAndroid Build Coastguard Worker 
1271*9880d681SAndroid Build Coastguard Worker   if (F.empty())
1272*9880d681SAndroid Build Coastguard Worker     return true;
1273*9880d681SAndroid Build Coastguard Worker 
1274*9880d681SAndroid Build Coastguard Worker   Function *Caller = CS.getInstruction()->getParent()->getParent();
1275*9880d681SAndroid Build Coastguard Worker   // Check if the caller function is recursive itself.
1276*9880d681SAndroid Build Coastguard Worker   for (User *U : Caller->users()) {
1277*9880d681SAndroid Build Coastguard Worker     CallSite Site(U);
1278*9880d681SAndroid Build Coastguard Worker     if (!Site)
1279*9880d681SAndroid Build Coastguard Worker       continue;
1280*9880d681SAndroid Build Coastguard Worker     Instruction *I = Site.getInstruction();
1281*9880d681SAndroid Build Coastguard Worker     if (I->getParent()->getParent() == Caller) {
1282*9880d681SAndroid Build Coastguard Worker       IsCallerRecursive = true;
1283*9880d681SAndroid Build Coastguard Worker       break;
1284*9880d681SAndroid Build Coastguard Worker     }
1285*9880d681SAndroid Build Coastguard Worker   }
1286*9880d681SAndroid Build Coastguard Worker 
1287*9880d681SAndroid Build Coastguard Worker   // Populate our simplified values by mapping from function arguments to call
1288*9880d681SAndroid Build Coastguard Worker   // arguments with known important simplifications.
1289*9880d681SAndroid Build Coastguard Worker   CallSite::arg_iterator CAI = CS.arg_begin();
1290*9880d681SAndroid Build Coastguard Worker   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
1291*9880d681SAndroid Build Coastguard Worker        FAI != FAE; ++FAI, ++CAI) {
1292*9880d681SAndroid Build Coastguard Worker     assert(CAI != CS.arg_end());
1293*9880d681SAndroid Build Coastguard Worker     if (Constant *C = dyn_cast<Constant>(CAI))
1294*9880d681SAndroid Build Coastguard Worker       SimplifiedValues[&*FAI] = C;
1295*9880d681SAndroid Build Coastguard Worker 
1296*9880d681SAndroid Build Coastguard Worker     Value *PtrArg = *CAI;
1297*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
1298*9880d681SAndroid Build Coastguard Worker       ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
1299*9880d681SAndroid Build Coastguard Worker 
1300*9880d681SAndroid Build Coastguard Worker       // We can SROA any pointer arguments derived from alloca instructions.
1301*9880d681SAndroid Build Coastguard Worker       if (isa<AllocaInst>(PtrArg)) {
1302*9880d681SAndroid Build Coastguard Worker         SROAArgValues[&*FAI] = PtrArg;
1303*9880d681SAndroid Build Coastguard Worker         SROAArgCosts[PtrArg] = 0;
1304*9880d681SAndroid Build Coastguard Worker       }
1305*9880d681SAndroid Build Coastguard Worker     }
1306*9880d681SAndroid Build Coastguard Worker   }
1307*9880d681SAndroid Build Coastguard Worker   NumConstantArgs = SimplifiedValues.size();
1308*9880d681SAndroid Build Coastguard Worker   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
1309*9880d681SAndroid Build Coastguard Worker   NumAllocaArgs = SROAArgValues.size();
1310*9880d681SAndroid Build Coastguard Worker 
1311*9880d681SAndroid Build Coastguard Worker   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
1312*9880d681SAndroid Build Coastguard Worker   // the ephemeral values multiple times (and they're completely determined by
1313*9880d681SAndroid Build Coastguard Worker   // the callee, so this is purely duplicate work).
1314*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<const Value *, 32> EphValues;
1315*9880d681SAndroid Build Coastguard Worker   CodeMetrics::collectEphemeralValues(&F, &ACT->getAssumptionCache(F),
1316*9880d681SAndroid Build Coastguard Worker                                       EphValues);
1317*9880d681SAndroid Build Coastguard Worker 
1318*9880d681SAndroid Build Coastguard Worker   // The worklist of live basic blocks in the callee *after* inlining. We avoid
1319*9880d681SAndroid Build Coastguard Worker   // adding basic blocks of the callee which can be proven to be dead for this
1320*9880d681SAndroid Build Coastguard Worker   // particular call site in order to get more accurate cost estimates. This
1321*9880d681SAndroid Build Coastguard Worker   // requires a somewhat heavyweight iteration pattern: we need to walk the
1322*9880d681SAndroid Build Coastguard Worker   // basic blocks in a breadth-first order as we insert live successors. To
1323*9880d681SAndroid Build Coastguard Worker   // accomplish this, prioritizing for small iterations because we exit after
1324*9880d681SAndroid Build Coastguard Worker   // crossing our threshold, we use a small-size optimized SetVector.
1325*9880d681SAndroid Build Coastguard Worker   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1326*9880d681SAndroid Build Coastguard Worker                     SmallPtrSet<BasicBlock *, 16>>
1327*9880d681SAndroid Build Coastguard Worker       BBSetVector;
1328*9880d681SAndroid Build Coastguard Worker   BBSetVector BBWorklist;
1329*9880d681SAndroid Build Coastguard Worker   BBWorklist.insert(&F.getEntryBlock());
1330*9880d681SAndroid Build Coastguard Worker   // Note that we *must not* cache the size, this loop grows the worklist.
1331*9880d681SAndroid Build Coastguard Worker   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1332*9880d681SAndroid Build Coastguard Worker     // Bail out the moment we cross the threshold. This means we'll under-count
1333*9880d681SAndroid Build Coastguard Worker     // the cost, but only when undercounting doesn't matter.
1334*9880d681SAndroid Build Coastguard Worker     if (Cost > Threshold)
1335*9880d681SAndroid Build Coastguard Worker       break;
1336*9880d681SAndroid Build Coastguard Worker 
1337*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB = BBWorklist[Idx];
1338*9880d681SAndroid Build Coastguard Worker     if (BB->empty())
1339*9880d681SAndroid Build Coastguard Worker       continue;
1340*9880d681SAndroid Build Coastguard Worker 
1341*9880d681SAndroid Build Coastguard Worker     // Disallow inlining a blockaddress. A blockaddress only has defined
1342*9880d681SAndroid Build Coastguard Worker     // behavior for an indirect branch in the same function, and we do not
1343*9880d681SAndroid Build Coastguard Worker     // currently support inlining indirect branches. But, the inliner may not
1344*9880d681SAndroid Build Coastguard Worker     // see an indirect branch that ends up being dead code at a particular call
1345*9880d681SAndroid Build Coastguard Worker     // site. If the blockaddress escapes the function, e.g., via a global
1346*9880d681SAndroid Build Coastguard Worker     // variable, inlining may lead to an invalid cross-function reference.
1347*9880d681SAndroid Build Coastguard Worker     if (BB->hasAddressTaken())
1348*9880d681SAndroid Build Coastguard Worker       return false;
1349*9880d681SAndroid Build Coastguard Worker 
1350*9880d681SAndroid Build Coastguard Worker     // Analyze the cost of this block. If we blow through the threshold, this
1351*9880d681SAndroid Build Coastguard Worker     // returns false, and we can bail on out.
1352*9880d681SAndroid Build Coastguard Worker     if (!analyzeBlock(BB, EphValues))
1353*9880d681SAndroid Build Coastguard Worker       return false;
1354*9880d681SAndroid Build Coastguard Worker 
1355*9880d681SAndroid Build Coastguard Worker     TerminatorInst *TI = BB->getTerminator();
1356*9880d681SAndroid Build Coastguard Worker 
1357*9880d681SAndroid Build Coastguard Worker     // Add in the live successors by first checking whether we have terminator
1358*9880d681SAndroid Build Coastguard Worker     // that may be simplified based on the values simplified by this call.
1359*9880d681SAndroid Build Coastguard Worker     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1360*9880d681SAndroid Build Coastguard Worker       if (BI->isConditional()) {
1361*9880d681SAndroid Build Coastguard Worker         Value *Cond = BI->getCondition();
1362*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *SimpleCond =
1363*9880d681SAndroid Build Coastguard Worker                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1364*9880d681SAndroid Build Coastguard Worker           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
1365*9880d681SAndroid Build Coastguard Worker           continue;
1366*9880d681SAndroid Build Coastguard Worker         }
1367*9880d681SAndroid Build Coastguard Worker       }
1368*9880d681SAndroid Build Coastguard Worker     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1369*9880d681SAndroid Build Coastguard Worker       Value *Cond = SI->getCondition();
1370*9880d681SAndroid Build Coastguard Worker       if (ConstantInt *SimpleCond =
1371*9880d681SAndroid Build Coastguard Worker               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1372*9880d681SAndroid Build Coastguard Worker         BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
1373*9880d681SAndroid Build Coastguard Worker         continue;
1374*9880d681SAndroid Build Coastguard Worker       }
1375*9880d681SAndroid Build Coastguard Worker     }
1376*9880d681SAndroid Build Coastguard Worker 
1377*9880d681SAndroid Build Coastguard Worker     // If we're unable to select a particular successor, just count all of
1378*9880d681SAndroid Build Coastguard Worker     // them.
1379*9880d681SAndroid Build Coastguard Worker     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1380*9880d681SAndroid Build Coastguard Worker          ++TIdx)
1381*9880d681SAndroid Build Coastguard Worker       BBWorklist.insert(TI->getSuccessor(TIdx));
1382*9880d681SAndroid Build Coastguard Worker 
1383*9880d681SAndroid Build Coastguard Worker     // If we had any successors at this point, than post-inlining is likely to
1384*9880d681SAndroid Build Coastguard Worker     // have them as well. Note that we assume any basic blocks which existed
1385*9880d681SAndroid Build Coastguard Worker     // due to branches or switches which folded above will also fold after
1386*9880d681SAndroid Build Coastguard Worker     // inlining.
1387*9880d681SAndroid Build Coastguard Worker     if (SingleBB && TI->getNumSuccessors() > 1) {
1388*9880d681SAndroid Build Coastguard Worker       // Take off the bonus we applied to the threshold.
1389*9880d681SAndroid Build Coastguard Worker       Threshold -= SingleBBBonus;
1390*9880d681SAndroid Build Coastguard Worker       SingleBB = false;
1391*9880d681SAndroid Build Coastguard Worker     }
1392*9880d681SAndroid Build Coastguard Worker   }
1393*9880d681SAndroid Build Coastguard Worker 
1394*9880d681SAndroid Build Coastguard Worker   // If this is a noduplicate call, we can still inline as long as
1395*9880d681SAndroid Build Coastguard Worker   // inlining this would cause the removal of the caller (so the instruction
1396*9880d681SAndroid Build Coastguard Worker   // is not actually duplicated, just moved).
1397*9880d681SAndroid Build Coastguard Worker   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
1398*9880d681SAndroid Build Coastguard Worker     return false;
1399*9880d681SAndroid Build Coastguard Worker 
1400*9880d681SAndroid Build Coastguard Worker   // We applied the maximum possible vector bonus at the beginning. Now,
1401*9880d681SAndroid Build Coastguard Worker   // subtract the excess bonus, if any, from the Threshold before
1402*9880d681SAndroid Build Coastguard Worker   // comparing against Cost.
1403*9880d681SAndroid Build Coastguard Worker   if (NumVectorInstructions <= NumInstructions / 10)
1404*9880d681SAndroid Build Coastguard Worker     Threshold -= FiftyPercentVectorBonus;
1405*9880d681SAndroid Build Coastguard Worker   else if (NumVectorInstructions <= NumInstructions / 2)
1406*9880d681SAndroid Build Coastguard Worker     Threshold -= (FiftyPercentVectorBonus - TenPercentVectorBonus);
1407*9880d681SAndroid Build Coastguard Worker 
1408*9880d681SAndroid Build Coastguard Worker   return Cost < std::max(1, Threshold);
1409*9880d681SAndroid Build Coastguard Worker }
1410*9880d681SAndroid Build Coastguard Worker 
1411*9880d681SAndroid Build Coastguard Worker #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1412*9880d681SAndroid Build Coastguard Worker /// \brief Dump stats about this call's analysis.
dump()1413*9880d681SAndroid Build Coastguard Worker LLVM_DUMP_METHOD void CallAnalyzer::dump() {
1414*9880d681SAndroid Build Coastguard Worker #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
1415*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(NumConstantArgs);
1416*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1417*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(NumAllocaArgs);
1418*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(NumConstantPtrCmps);
1419*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1420*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(NumInstructionsSimplified);
1421*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(NumInstructions);
1422*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(SROACostSavings);
1423*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(SROACostSavingsLost);
1424*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
1425*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(Cost);
1426*9880d681SAndroid Build Coastguard Worker   DEBUG_PRINT_STAT(Threshold);
1427*9880d681SAndroid Build Coastguard Worker #undef DEBUG_PRINT_STAT
1428*9880d681SAndroid Build Coastguard Worker }
1429*9880d681SAndroid Build Coastguard Worker #endif
1430*9880d681SAndroid Build Coastguard Worker 
1431*9880d681SAndroid Build Coastguard Worker /// \brief Test that two functions either have or have not the given attribute
1432*9880d681SAndroid Build Coastguard Worker ///        at the same time.
1433*9880d681SAndroid Build Coastguard Worker template <typename AttrKind>
attributeMatches(Function * F1,Function * F2,AttrKind Attr)1434*9880d681SAndroid Build Coastguard Worker static bool attributeMatches(Function *F1, Function *F2, AttrKind Attr) {
1435*9880d681SAndroid Build Coastguard Worker   return F1->getFnAttribute(Attr) == F2->getFnAttribute(Attr);
1436*9880d681SAndroid Build Coastguard Worker }
1437*9880d681SAndroid Build Coastguard Worker 
1438*9880d681SAndroid Build Coastguard Worker /// \brief Test that there are no attribute conflicts between Caller and Callee
1439*9880d681SAndroid Build Coastguard Worker ///        that prevent inlining.
functionsHaveCompatibleAttributes(Function * Caller,Function * Callee,TargetTransformInfo & TTI)1440*9880d681SAndroid Build Coastguard Worker static bool functionsHaveCompatibleAttributes(Function *Caller,
1441*9880d681SAndroid Build Coastguard Worker                                               Function *Callee,
1442*9880d681SAndroid Build Coastguard Worker                                               TargetTransformInfo &TTI) {
1443*9880d681SAndroid Build Coastguard Worker   return TTI.areInlineCompatible(Caller, Callee) &&
1444*9880d681SAndroid Build Coastguard Worker          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
1445*9880d681SAndroid Build Coastguard Worker }
1446*9880d681SAndroid Build Coastguard Worker 
getInlineCost(CallSite CS,int DefaultThreshold,TargetTransformInfo & CalleeTTI,AssumptionCacheTracker * ACT,ProfileSummaryInfo * PSI)1447*9880d681SAndroid Build Coastguard Worker InlineCost llvm::getInlineCost(CallSite CS, int DefaultThreshold,
1448*9880d681SAndroid Build Coastguard Worker                                TargetTransformInfo &CalleeTTI,
1449*9880d681SAndroid Build Coastguard Worker                                AssumptionCacheTracker *ACT,
1450*9880d681SAndroid Build Coastguard Worker                                ProfileSummaryInfo *PSI) {
1451*9880d681SAndroid Build Coastguard Worker   return getInlineCost(CS, CS.getCalledFunction(), DefaultThreshold, CalleeTTI,
1452*9880d681SAndroid Build Coastguard Worker                        ACT, PSI);
1453*9880d681SAndroid Build Coastguard Worker }
1454*9880d681SAndroid Build Coastguard Worker 
computeThresholdFromOptLevels(unsigned OptLevel,unsigned SizeOptLevel)1455*9880d681SAndroid Build Coastguard Worker int llvm::computeThresholdFromOptLevels(unsigned OptLevel,
1456*9880d681SAndroid Build Coastguard Worker                                         unsigned SizeOptLevel) {
1457*9880d681SAndroid Build Coastguard Worker   if (OptLevel > 2)
1458*9880d681SAndroid Build Coastguard Worker     return OptAggressiveThreshold;
1459*9880d681SAndroid Build Coastguard Worker   if (SizeOptLevel == 1) // -Os
1460*9880d681SAndroid Build Coastguard Worker     return OptSizeThreshold;
1461*9880d681SAndroid Build Coastguard Worker   if (SizeOptLevel == 2) // -Oz
1462*9880d681SAndroid Build Coastguard Worker     return OptMinSizeThreshold;
1463*9880d681SAndroid Build Coastguard Worker   return DefaultInlineThreshold;
1464*9880d681SAndroid Build Coastguard Worker }
1465*9880d681SAndroid Build Coastguard Worker 
getDefaultInlineThreshold()1466*9880d681SAndroid Build Coastguard Worker int llvm::getDefaultInlineThreshold() { return DefaultInlineThreshold; }
1467*9880d681SAndroid Build Coastguard Worker 
getInlineCost(CallSite CS,Function * Callee,int DefaultThreshold,TargetTransformInfo & CalleeTTI,AssumptionCacheTracker * ACT,ProfileSummaryInfo * PSI)1468*9880d681SAndroid Build Coastguard Worker InlineCost llvm::getInlineCost(CallSite CS, Function *Callee,
1469*9880d681SAndroid Build Coastguard Worker                                int DefaultThreshold,
1470*9880d681SAndroid Build Coastguard Worker                                TargetTransformInfo &CalleeTTI,
1471*9880d681SAndroid Build Coastguard Worker                                AssumptionCacheTracker *ACT,
1472*9880d681SAndroid Build Coastguard Worker                                ProfileSummaryInfo *PSI) {
1473*9880d681SAndroid Build Coastguard Worker 
1474*9880d681SAndroid Build Coastguard Worker   // Cannot inline indirect calls.
1475*9880d681SAndroid Build Coastguard Worker   if (!Callee)
1476*9880d681SAndroid Build Coastguard Worker     return llvm::InlineCost::getNever();
1477*9880d681SAndroid Build Coastguard Worker 
1478*9880d681SAndroid Build Coastguard Worker   // Calls to functions with always-inline attributes should be inlined
1479*9880d681SAndroid Build Coastguard Worker   // whenever possible.
1480*9880d681SAndroid Build Coastguard Worker   if (CS.hasFnAttr(Attribute::AlwaysInline)) {
1481*9880d681SAndroid Build Coastguard Worker     if (isInlineViable(*Callee))
1482*9880d681SAndroid Build Coastguard Worker       return llvm::InlineCost::getAlways();
1483*9880d681SAndroid Build Coastguard Worker     return llvm::InlineCost::getNever();
1484*9880d681SAndroid Build Coastguard Worker   }
1485*9880d681SAndroid Build Coastguard Worker 
1486*9880d681SAndroid Build Coastguard Worker   // Never inline functions with conflicting attributes (unless callee has
1487*9880d681SAndroid Build Coastguard Worker   // always-inline attribute).
1488*9880d681SAndroid Build Coastguard Worker   if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee, CalleeTTI))
1489*9880d681SAndroid Build Coastguard Worker     return llvm::InlineCost::getNever();
1490*9880d681SAndroid Build Coastguard Worker 
1491*9880d681SAndroid Build Coastguard Worker   // Don't inline this call if the caller has the optnone attribute.
1492*9880d681SAndroid Build Coastguard Worker   if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
1493*9880d681SAndroid Build Coastguard Worker     return llvm::InlineCost::getNever();
1494*9880d681SAndroid Build Coastguard Worker 
1495*9880d681SAndroid Build Coastguard Worker   // Don't inline functions which can be interposed at link-time.  Don't inline
1496*9880d681SAndroid Build Coastguard Worker   // functions marked noinline or call sites marked noinline.
1497*9880d681SAndroid Build Coastguard Worker   // Note: inlining non-exact non-interposable fucntions is fine, since we know
1498*9880d681SAndroid Build Coastguard Worker   // we have *a* correct implementation of the source level function.
1499*9880d681SAndroid Build Coastguard Worker   if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
1500*9880d681SAndroid Build Coastguard Worker       CS.isNoInline())
1501*9880d681SAndroid Build Coastguard Worker     return llvm::InlineCost::getNever();
1502*9880d681SAndroid Build Coastguard Worker 
1503*9880d681SAndroid Build Coastguard Worker   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
1504*9880d681SAndroid Build Coastguard Worker                      << "...\n");
1505*9880d681SAndroid Build Coastguard Worker 
1506*9880d681SAndroid Build Coastguard Worker   CallAnalyzer CA(CalleeTTI, ACT, PSI, *Callee, DefaultThreshold, CS);
1507*9880d681SAndroid Build Coastguard Worker   bool ShouldInline = CA.analyzeCall(CS);
1508*9880d681SAndroid Build Coastguard Worker 
1509*9880d681SAndroid Build Coastguard Worker   DEBUG(CA.dump());
1510*9880d681SAndroid Build Coastguard Worker 
1511*9880d681SAndroid Build Coastguard Worker   // Check if there was a reason to force inlining or no inlining.
1512*9880d681SAndroid Build Coastguard Worker   if (!ShouldInline && CA.getCost() < CA.getThreshold())
1513*9880d681SAndroid Build Coastguard Worker     return InlineCost::getNever();
1514*9880d681SAndroid Build Coastguard Worker   if (ShouldInline && CA.getCost() >= CA.getThreshold())
1515*9880d681SAndroid Build Coastguard Worker     return InlineCost::getAlways();
1516*9880d681SAndroid Build Coastguard Worker 
1517*9880d681SAndroid Build Coastguard Worker   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
1518*9880d681SAndroid Build Coastguard Worker }
1519*9880d681SAndroid Build Coastguard Worker 
isInlineViable(Function & F)1520*9880d681SAndroid Build Coastguard Worker bool llvm::isInlineViable(Function &F) {
1521*9880d681SAndroid Build Coastguard Worker   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
1522*9880d681SAndroid Build Coastguard Worker   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1523*9880d681SAndroid Build Coastguard Worker     // Disallow inlining of functions which contain indirect branches or
1524*9880d681SAndroid Build Coastguard Worker     // blockaddresses.
1525*9880d681SAndroid Build Coastguard Worker     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
1526*9880d681SAndroid Build Coastguard Worker       return false;
1527*9880d681SAndroid Build Coastguard Worker 
1528*9880d681SAndroid Build Coastguard Worker     for (auto &II : *BI) {
1529*9880d681SAndroid Build Coastguard Worker       CallSite CS(&II);
1530*9880d681SAndroid Build Coastguard Worker       if (!CS)
1531*9880d681SAndroid Build Coastguard Worker         continue;
1532*9880d681SAndroid Build Coastguard Worker 
1533*9880d681SAndroid Build Coastguard Worker       // Disallow recursive calls.
1534*9880d681SAndroid Build Coastguard Worker       if (&F == CS.getCalledFunction())
1535*9880d681SAndroid Build Coastguard Worker         return false;
1536*9880d681SAndroid Build Coastguard Worker 
1537*9880d681SAndroid Build Coastguard Worker       // Disallow calls which expose returns-twice to a function not previously
1538*9880d681SAndroid Build Coastguard Worker       // attributed as such.
1539*9880d681SAndroid Build Coastguard Worker       if (!ReturnsTwice && CS.isCall() &&
1540*9880d681SAndroid Build Coastguard Worker           cast<CallInst>(CS.getInstruction())->canReturnTwice())
1541*9880d681SAndroid Build Coastguard Worker         return false;
1542*9880d681SAndroid Build Coastguard Worker 
1543*9880d681SAndroid Build Coastguard Worker       // Disallow inlining functions that call @llvm.localescape. Doing this
1544*9880d681SAndroid Build Coastguard Worker       // correctly would require major changes to the inliner.
1545*9880d681SAndroid Build Coastguard Worker       if (CS.getCalledFunction() &&
1546*9880d681SAndroid Build Coastguard Worker           CS.getCalledFunction()->getIntrinsicID() ==
1547*9880d681SAndroid Build Coastguard Worker               llvm::Intrinsic::localescape)
1548*9880d681SAndroid Build Coastguard Worker         return false;
1549*9880d681SAndroid Build Coastguard Worker     }
1550*9880d681SAndroid Build Coastguard Worker   }
1551*9880d681SAndroid Build Coastguard Worker 
1552*9880d681SAndroid Build Coastguard Worker   return true;
1553*9880d681SAndroid Build Coastguard Worker }
1554