blob: 5a9abec6a2e8b3d594f59f3d75db7afffac361f7 [file] [log] [blame]
Dan Gohman4552e3c2009-10-13 18:30:07 +00001//===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements inline cost analysis.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/InlineCost.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000020#include "llvm/Analysis/AssumptionCache.h"
Hal Finkel57f03dd2014-09-07 13:49:57 +000021#include "llvm/Analysis/CodeMetrics.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000022#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth0539c072012-03-31 12:42:41 +000023#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth42f3dce2013-01-21 11:55:09 +000024#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000025#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/GlobalAlias.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000030#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Operator.h"
Chandler Carruth0539c072012-03-31 12:42:41 +000033#include "llvm/Support/Debug.h"
Chandler Carruth0539c072012-03-31 12:42:41 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher2dfbd7e2011-02-05 00:49:15 +000035
Dan Gohman4552e3c2009-10-13 18:30:07 +000036using namespace llvm;
37
Chandler Carruthf1221bd2014-04-22 02:48:03 +000038#define DEBUG_TYPE "inline-cost"
39
Chandler Carruth7ae90d42012-04-11 10:15:10 +000040STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
41
Chandler Carruth0539c072012-03-31 12:42:41 +000042namespace {
Chandler Carrutha3089552012-03-14 07:32:53 +000043
Chandler Carruth0539c072012-03-31 12:42:41 +000044class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
45 typedef InstVisitor<CallAnalyzer, bool> Base;
46 friend class InstVisitor<CallAnalyzer, bool>;
Owen Andersona08318a2010-09-09 16:56:42 +000047
Chandler Carruth42f3dce2013-01-21 11:55:09 +000048 /// The TargetTransformInfo available for this compilation.
49 const TargetTransformInfo &TTI;
50
Hal Finkel57f03dd2014-09-07 13:49:57 +000051 /// The cache of @llvm.assume intrinsics.
Bjorn Steinbrink6f972a12015-02-12 21:04:22 +000052 AssumptionCacheTracker *ACT;
Hal Finkel57f03dd2014-09-07 13:49:57 +000053
Chandler Carruth0539c072012-03-31 12:42:41 +000054 // The called function.
55 Function &F;
Owen Andersona08318a2010-09-09 16:56:42 +000056
Chandler Carruth0539c072012-03-31 12:42:41 +000057 int Threshold;
58 int Cost;
Owen Andersona08318a2010-09-09 16:56:42 +000059
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +000060 bool IsCallerRecursive;
61 bool IsRecursiveCall;
Chandler Carruth0539c072012-03-31 12:42:41 +000062 bool ExposesReturnsTwice;
63 bool HasDynamicAlloca;
James Molloy4f6fb952012-12-20 16:04:27 +000064 bool ContainsNoDuplicateCall;
Chandler Carruth0814d2a2013-12-13 07:59:56 +000065 bool HasReturn;
66 bool HasIndirectBr;
James Molloy4f6fb952012-12-20 16:04:27 +000067
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +000068 /// Number of bytes allocated statically by the callee.
69 uint64_t AllocatedSize;
Chandler Carruth0539c072012-03-31 12:42:41 +000070 unsigned NumInstructions, NumVectorInstructions;
71 int FiftyPercentVectorBonus, TenPercentVectorBonus;
72 int VectorBonus;
73
74 // While we walk the potentially-inlined instructions, we build up and
75 // maintain a mapping of simplified values specific to this callsite. The
76 // idea is to propagate any special information we have about arguments to
77 // this call through the inlinable section of the function, and account for
78 // likely simplifications post-inlining. The most important aspect we track
79 // is CFG altering simplifications -- when we prove a basic block dead, that
80 // can cause dramatic shifts in the cost of inlining a function.
81 DenseMap<Value *, Constant *> SimplifiedValues;
82
83 // Keep track of the values which map back (through function arguments) to
84 // allocas on the caller stack which could be simplified through SROA.
85 DenseMap<Value *, Value *> SROAArgValues;
86
87 // The mapping of caller Alloca values to their accumulated cost savings. If
88 // we have to disable SROA for one of the allocas, this tells us how much
89 // cost must be added.
90 DenseMap<Value *, int> SROAArgCosts;
91
92 // Keep track of values which map to a pointer base and constant offset.
93 DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
94
95 // Custom simplification helper routines.
96 bool isAllocaDerivedArg(Value *V);
97 bool lookupSROAArgAndCost(Value *V, Value *&Arg,
98 DenseMap<Value *, int>::iterator &CostIt);
99 void disableSROA(DenseMap<Value *, int>::iterator CostIt);
100 void disableSROA(Value *V);
101 void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
102 int InstructionCost);
Chandler Carruth0539c072012-03-31 12:42:41 +0000103 bool isGEPOffsetConstant(GetElementPtrInst &GEP);
104 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
Chandler Carruth753e21d2012-12-28 14:23:32 +0000105 bool simplifyCallSite(Function *F, CallSite CS);
Chandler Carruth0539c072012-03-31 12:42:41 +0000106 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
107
108 // Custom analysis routines.
Hal Finkel57f03dd2014-09-07 13:49:57 +0000109 bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues);
Chandler Carruth0539c072012-03-31 12:42:41 +0000110
111 // Disable several entry points to the visitor so we don't accidentally use
112 // them by declaring but not defining them here.
113 void visit(Module *); void visit(Module &);
114 void visit(Function *); void visit(Function &);
115 void visit(BasicBlock *); void visit(BasicBlock &);
116
117 // Provide base case for our instruction visit.
118 bool visitInstruction(Instruction &I);
119
120 // Our visit overrides.
121 bool visitAlloca(AllocaInst &I);
122 bool visitPHI(PHINode &I);
123 bool visitGetElementPtr(GetElementPtrInst &I);
124 bool visitBitCast(BitCastInst &I);
125 bool visitPtrToInt(PtrToIntInst &I);
126 bool visitIntToPtr(IntToPtrInst &I);
127 bool visitCastInst(CastInst &I);
128 bool visitUnaryInstruction(UnaryInstruction &I);
Matt Arsenault727aa342013-07-20 04:09:00 +0000129 bool visitCmpInst(CmpInst &I);
Chandler Carruth0539c072012-03-31 12:42:41 +0000130 bool visitSub(BinaryOperator &I);
131 bool visitBinaryOperator(BinaryOperator &I);
132 bool visitLoad(LoadInst &I);
133 bool visitStore(StoreInst &I);
Chandler Carruth753e21d2012-12-28 14:23:32 +0000134 bool visitExtractValue(ExtractValueInst &I);
135 bool visitInsertValue(InsertValueInst &I);
Chandler Carruth0539c072012-03-31 12:42:41 +0000136 bool visitCallSite(CallSite CS);
Chandler Carruth0814d2a2013-12-13 07:59:56 +0000137 bool visitReturnInst(ReturnInst &RI);
138 bool visitBranchInst(BranchInst &BI);
139 bool visitSwitchInst(SwitchInst &SI);
140 bool visitIndirectBrInst(IndirectBrInst &IBI);
141 bool visitResumeInst(ResumeInst &RI);
142 bool visitUnreachableInst(UnreachableInst &I);
Chandler Carruth0539c072012-03-31 12:42:41 +0000143
144public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000145 CallAnalyzer(const TargetTransformInfo &TTI, AssumptionCacheTracker *ACT,
146 Function &Callee, int Threshold)
147 : TTI(TTI), ACT(ACT), F(Callee), Threshold(Threshold), Cost(0),
Chandler Carruth42f3dce2013-01-21 11:55:09 +0000148 IsCallerRecursive(false), IsRecursiveCall(false),
149 ExposesReturnsTwice(false), HasDynamicAlloca(false),
Chandler Carruth0814d2a2013-12-13 07:59:56 +0000150 ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
151 AllocatedSize(0), NumInstructions(0), NumVectorInstructions(0),
152 FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
153 NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
154 NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
155 NumInstructionsSimplified(0), SROACostSavings(0),
156 SROACostSavingsLost(0) {}
Chandler Carruth0539c072012-03-31 12:42:41 +0000157
158 bool analyzeCall(CallSite CS);
159
160 int getThreshold() { return Threshold; }
161 int getCost() { return Cost; }
162
163 // Keep a bunch of stats about the cost savings found so we can print them
164 // out when debugging.
165 unsigned NumConstantArgs;
166 unsigned NumConstantOffsetPtrArgs;
167 unsigned NumAllocaArgs;
168 unsigned NumConstantPtrCmps;
169 unsigned NumConstantPtrDiffs;
170 unsigned NumInstructionsSimplified;
171 unsigned SROACostSavings;
172 unsigned SROACostSavingsLost;
173
174 void dump();
175};
176
177} // namespace
178
179/// \brief Test whether the given value is an Alloca-derived function argument.
180bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
181 return SROAArgValues.count(V);
Owen Andersona08318a2010-09-09 16:56:42 +0000182}
183
Chandler Carruth0539c072012-03-31 12:42:41 +0000184/// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
185/// Returns false if V does not map to a SROA-candidate.
186bool CallAnalyzer::lookupSROAArgAndCost(
187 Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
188 if (SROAArgValues.empty() || SROAArgCosts.empty())
189 return false;
Chandler Carruth783b7192012-03-09 02:49:36 +0000190
Chandler Carruth0539c072012-03-31 12:42:41 +0000191 DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
192 if (ArgIt == SROAArgValues.end())
193 return false;
Chandler Carruth783b7192012-03-09 02:49:36 +0000194
Chandler Carruth0539c072012-03-31 12:42:41 +0000195 Arg = ArgIt->second;
196 CostIt = SROAArgCosts.find(Arg);
197 return CostIt != SROAArgCosts.end();
Chandler Carruth783b7192012-03-09 02:49:36 +0000198}
199
Chandler Carruth0539c072012-03-31 12:42:41 +0000200/// \brief Disable SROA for the candidate marked by this cost iterator.
Chandler Carruth783b7192012-03-09 02:49:36 +0000201///
Benjamin Kramerbde91762012-06-02 10:20:22 +0000202/// This marks the candidate as no longer viable for SROA, and adds the cost
Chandler Carruth0539c072012-03-31 12:42:41 +0000203/// savings associated with it back into the inline cost measurement.
204void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
205 // If we're no longer able to perform SROA we need to undo its cost savings
206 // and prevent subsequent analysis.
207 Cost += CostIt->second;
208 SROACostSavings -= CostIt->second;
209 SROACostSavingsLost += CostIt->second;
210 SROAArgCosts.erase(CostIt);
211}
212
213/// \brief If 'V' maps to a SROA candidate, disable SROA for it.
214void CallAnalyzer::disableSROA(Value *V) {
215 Value *SROAArg;
216 DenseMap<Value *, int>::iterator CostIt;
217 if (lookupSROAArgAndCost(V, SROAArg, CostIt))
218 disableSROA(CostIt);
219}
220
221/// \brief Accumulate the given cost for a particular SROA candidate.
222void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
223 int InstructionCost) {
224 CostIt->second += InstructionCost;
225 SROACostSavings += InstructionCost;
226}
227
Chandler Carruth0539c072012-03-31 12:42:41 +0000228/// \brief Check whether a GEP's indices are all constant.
229///
230/// Respects any simplified values known during the analysis of this callsite.
231bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
232 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
233 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
Chandler Carruth783b7192012-03-09 02:49:36 +0000234 return false;
Chandler Carruth783b7192012-03-09 02:49:36 +0000235
Chandler Carruth0539c072012-03-31 12:42:41 +0000236 return true;
237}
238
239/// \brief Accumulate a constant GEP offset into an APInt if possible.
240///
241/// Returns false if unable to compute the offset for any reason. Respects any
242/// simplified values known during the analysis of this callsite.
243bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000244 const DataLayout &DL = F.getParent()->getDataLayout();
245 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruth0539c072012-03-31 12:42:41 +0000246 assert(IntPtrWidth == Offset.getBitWidth());
247
248 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
249 GTI != GTE; ++GTI) {
250 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
251 if (!OpC)
252 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
253 OpC = dyn_cast<ConstantInt>(SimpleOp);
254 if (!OpC)
Chandler Carruth783b7192012-03-09 02:49:36 +0000255 return false;
Chandler Carruth0539c072012-03-31 12:42:41 +0000256 if (OpC->isZero()) continue;
Chandler Carruth783b7192012-03-09 02:49:36 +0000257
Chandler Carruth0539c072012-03-31 12:42:41 +0000258 // Handle a struct index, which adds its field offset to the pointer.
259 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
260 unsigned ElementIdx = OpC->getZExtValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000261 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth0539c072012-03-31 12:42:41 +0000262 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
263 continue;
Chandler Carruth783b7192012-03-09 02:49:36 +0000264 }
Chandler Carruth783b7192012-03-09 02:49:36 +0000265
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000266 APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
Chandler Carruth0539c072012-03-31 12:42:41 +0000267 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
268 }
269 return true;
270}
271
272bool CallAnalyzer::visitAlloca(AllocaInst &I) {
Eric Christopherbeb2cd62014-04-07 13:36:21 +0000273 // Check whether inlining will turn a dynamic alloca into a static
Chandler Carruth0539c072012-03-31 12:42:41 +0000274 // alloca, and handle that case.
Eric Christopherbeb2cd62014-04-07 13:36:21 +0000275 if (I.isArrayAllocation()) {
276 if (Constant *Size = SimplifiedValues.lookup(I.getArraySize())) {
277 ConstantInt *AllocSize = dyn_cast<ConstantInt>(Size);
278 assert(AllocSize && "Allocation size not a constant int?");
279 Type *Ty = I.getAllocatedType();
280 AllocatedSize += Ty->getPrimitiveSizeInBits() * AllocSize->getZExtValue();
281 return Base::visitAlloca(I);
282 }
283 }
Chandler Carruth0539c072012-03-31 12:42:41 +0000284
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +0000285 // Accumulate the allocated size.
286 if (I.isStaticAlloca()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000287 const DataLayout &DL = F.getParent()->getDataLayout();
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +0000288 Type *Ty = I.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289 AllocatedSize += DL.getTypeAllocSize(Ty);
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +0000290 }
291
Bob Wilsona5b0dc82012-11-19 07:04:35 +0000292 // We will happily inline static alloca instructions.
293 if (I.isStaticAlloca())
Chandler Carruth0539c072012-03-31 12:42:41 +0000294 return Base::visitAlloca(I);
295
296 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
297 // a variety of reasons, and so we would like to not inline them into
298 // functions which don't currently have a dynamic alloca. This simply
299 // disables inlining altogether in the presence of a dynamic alloca.
300 HasDynamicAlloca = true;
301 return false;
302}
303
304bool CallAnalyzer::visitPHI(PHINode &I) {
305 // FIXME: We should potentially be tracking values through phi nodes,
306 // especially when they collapse to a single value due to deleted CFG edges
307 // during inlining.
308
309 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
310 // though we don't want to propagate it's bonuses. The idea is to disable
311 // SROA if it *might* be used in an inappropriate manner.
312
313 // Phi nodes are always zero-cost.
314 return true;
315}
316
317bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
318 Value *SROAArg;
319 DenseMap<Value *, int>::iterator CostIt;
320 bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
321 SROAArg, CostIt);
322
323 // Try to fold GEPs of constant-offset call site argument pointers. This
324 // requires target data and inbounds GEPs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000325 if (I.isInBounds()) {
Chandler Carruth0539c072012-03-31 12:42:41 +0000326 // Check if we have a base + offset for the pointer.
327 Value *Ptr = I.getPointerOperand();
328 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
329 if (BaseAndOffset.first) {
330 // Check if the offset of this GEP is constant, and if so accumulate it
331 // into Offset.
332 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
333 // Non-constant GEPs aren't folded, and disable SROA.
334 if (SROACandidate)
335 disableSROA(CostIt);
336 return false;
337 }
338
339 // Add the result as a new mapping to Base + Offset.
340 ConstantOffsetPtrs[&I] = BaseAndOffset;
341
342 // Also handle SROA candidates here, we already know that the GEP is
343 // all-constant indexed.
344 if (SROACandidate)
345 SROAArgValues[&I] = SROAArg;
346
Chandler Carruth783b7192012-03-09 02:49:36 +0000347 return true;
348 }
349 }
350
Chandler Carruth0539c072012-03-31 12:42:41 +0000351 if (isGEPOffsetConstant(I)) {
352 if (SROACandidate)
353 SROAArgValues[&I] = SROAArg;
354
355 // Constant GEPs are modeled as free.
356 return true;
357 }
358
359 // Variable GEPs will require math and will disable SROA.
360 if (SROACandidate)
361 disableSROA(CostIt);
Chandler Carruth783b7192012-03-09 02:49:36 +0000362 return false;
363}
364
Chandler Carruth0539c072012-03-31 12:42:41 +0000365bool CallAnalyzer::visitBitCast(BitCastInst &I) {
366 // Propagate constants through bitcasts.
Chandler Carruth86ed5302012-12-28 14:43:42 +0000367 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
368 if (!COp)
369 COp = SimplifiedValues.lookup(I.getOperand(0));
370 if (COp)
Chandler Carruth0539c072012-03-31 12:42:41 +0000371 if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
372 SimplifiedValues[&I] = C;
373 return true;
Owen Andersona08318a2010-09-09 16:56:42 +0000374 }
Owen Andersona08318a2010-09-09 16:56:42 +0000375
Chandler Carruth0539c072012-03-31 12:42:41 +0000376 // Track base/offsets through casts
377 std::pair<Value *, APInt> BaseAndOffset
378 = ConstantOffsetPtrs.lookup(I.getOperand(0));
379 // Casts don't change the offset, just wrap it up.
380 if (BaseAndOffset.first)
381 ConstantOffsetPtrs[&I] = BaseAndOffset;
382
383 // Also look for SROA candidates here.
384 Value *SROAArg;
385 DenseMap<Value *, int>::iterator CostIt;
386 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
387 SROAArgValues[&I] = SROAArg;
388
389 // Bitcasts are always zero cost.
390 return true;
Owen Andersona08318a2010-09-09 16:56:42 +0000391}
392
Chandler Carruth0539c072012-03-31 12:42:41 +0000393bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
394 // Propagate constants through ptrtoint.
Chandler Carruth86ed5302012-12-28 14:43:42 +0000395 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
396 if (!COp)
397 COp = SimplifiedValues.lookup(I.getOperand(0));
398 if (COp)
Chandler Carruth0539c072012-03-31 12:42:41 +0000399 if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
400 SimplifiedValues[&I] = C;
401 return true;
Chandler Carruth4d1d34f2012-03-14 23:19:53 +0000402 }
Chandler Carruth0539c072012-03-31 12:42:41 +0000403
404 // Track base/offset pairs when converted to a plain integer provided the
405 // integer is large enough to represent the pointer.
406 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000407 const DataLayout &DL = F.getParent()->getDataLayout();
Mehdi Amini46a43552015-03-04 18:43:29 +0000408 if (IntegerSize >= DL.getPointerSizeInBits()) {
Chandler Carruth0539c072012-03-31 12:42:41 +0000409 std::pair<Value *, APInt> BaseAndOffset
410 = ConstantOffsetPtrs.lookup(I.getOperand(0));
411 if (BaseAndOffset.first)
412 ConstantOffsetPtrs[&I] = BaseAndOffset;
413 }
414
415 // This is really weird. Technically, ptrtoint will disable SROA. However,
416 // unless that ptrtoint is *used* somewhere in the live basic blocks after
417 // inlining, it will be nuked, and SROA should proceed. All of the uses which
418 // would block SROA would also block SROA if applied directly to a pointer,
419 // and so we can just add the integer in here. The only places where SROA is
420 // preserved either cannot fire on an integer, or won't in-and-of themselves
421 // disable SROA (ext) w/o some later use that we would see and disable.
422 Value *SROAArg;
423 DenseMap<Value *, int>::iterator CostIt;
424 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
425 SROAArgValues[&I] = SROAArg;
426
Chandler Carruthb8cf5102013-01-21 12:05:16 +0000427 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
Chandler Carruth4d1d34f2012-03-14 23:19:53 +0000428}
429
Chandler Carruth0539c072012-03-31 12:42:41 +0000430bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
431 // Propagate constants through ptrtoint.
Chandler Carruth86ed5302012-12-28 14:43:42 +0000432 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
433 if (!COp)
434 COp = SimplifiedValues.lookup(I.getOperand(0));
435 if (COp)
Chandler Carruth0539c072012-03-31 12:42:41 +0000436 if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
437 SimplifiedValues[&I] = C;
438 return true;
439 }
Dan Gohman4552e3c2009-10-13 18:30:07 +0000440
Chandler Carruth0539c072012-03-31 12:42:41 +0000441 // Track base/offset pairs when round-tripped through a pointer without
442 // modifications provided the integer is not too large.
443 Value *Op = I.getOperand(0);
444 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000445 const DataLayout &DL = F.getParent()->getDataLayout();
Mehdi Amini46a43552015-03-04 18:43:29 +0000446 if (IntegerSize <= DL.getPointerSizeInBits()) {
Chandler Carruth0539c072012-03-31 12:42:41 +0000447 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
448 if (BaseAndOffset.first)
449 ConstantOffsetPtrs[&I] = BaseAndOffset;
450 }
Dan Gohman4552e3c2009-10-13 18:30:07 +0000451
Chandler Carruth0539c072012-03-31 12:42:41 +0000452 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
453 Value *SROAArg;
454 DenseMap<Value *, int>::iterator CostIt;
455 if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
456 SROAArgValues[&I] = SROAArg;
Chandler Carruth4d1d34f2012-03-14 23:19:53 +0000457
Chandler Carruthb8cf5102013-01-21 12:05:16 +0000458 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
Chandler Carruth0539c072012-03-31 12:42:41 +0000459}
460
461bool CallAnalyzer::visitCastInst(CastInst &I) {
462 // Propagate constants through ptrtoint.
Chandler Carruth86ed5302012-12-28 14:43:42 +0000463 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
464 if (!COp)
465 COp = SimplifiedValues.lookup(I.getOperand(0));
466 if (COp)
Chandler Carruth0539c072012-03-31 12:42:41 +0000467 if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
468 SimplifiedValues[&I] = C;
469 return true;
470 }
471
472 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
473 disableSROA(I.getOperand(0));
474
Chandler Carruthb8cf5102013-01-21 12:05:16 +0000475 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
Chandler Carruth0539c072012-03-31 12:42:41 +0000476}
477
478bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
479 Value *Operand = I.getOperand(0);
Jakub Staszak7b9e0b92013-03-07 20:01:19 +0000480 Constant *COp = dyn_cast<Constant>(Operand);
481 if (!COp)
482 COp = SimplifiedValues.lookup(Operand);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000483 if (COp) {
484 const DataLayout &DL = F.getParent()->getDataLayout();
Chandler Carruth0539c072012-03-31 12:42:41 +0000485 if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000486 COp, DL)) {
Chandler Carruth0539c072012-03-31 12:42:41 +0000487 SimplifiedValues[&I] = C;
488 return true;
489 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000490 }
Chandler Carruth0539c072012-03-31 12:42:41 +0000491
492 // Disable any SROA on the argument to arbitrary unary operators.
493 disableSROA(Operand);
494
495 return false;
496}
497
Matt Arsenault727aa342013-07-20 04:09:00 +0000498bool CallAnalyzer::visitCmpInst(CmpInst &I) {
Chandler Carruth0539c072012-03-31 12:42:41 +0000499 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
500 // First try to handle simplified comparisons.
501 if (!isa<Constant>(LHS))
502 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
503 LHS = SimpleLHS;
504 if (!isa<Constant>(RHS))
505 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
506 RHS = SimpleRHS;
Matt Arsenault727aa342013-07-20 04:09:00 +0000507 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chandler Carruth0539c072012-03-31 12:42:41 +0000508 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Matt Arsenault727aa342013-07-20 04:09:00 +0000509 if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
Chandler Carruth0539c072012-03-31 12:42:41 +0000510 SimplifiedValues[&I] = C;
511 return true;
512 }
Matt Arsenault727aa342013-07-20 04:09:00 +0000513 }
514
515 if (I.getOpcode() == Instruction::FCmp)
516 return false;
Chandler Carruth0539c072012-03-31 12:42:41 +0000517
518 // Otherwise look for a comparison between constant offset pointers with
519 // a common base.
520 Value *LHSBase, *RHSBase;
521 APInt LHSOffset, RHSOffset;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000522 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
Chandler Carruth0539c072012-03-31 12:42:41 +0000523 if (LHSBase) {
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000524 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
Chandler Carruth0539c072012-03-31 12:42:41 +0000525 if (RHSBase && LHSBase == RHSBase) {
526 // We have common bases, fold the icmp to a constant based on the
527 // offsets.
528 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
529 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
530 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
531 SimplifiedValues[&I] = C;
532 ++NumConstantPtrCmps;
533 return true;
534 }
535 }
536 }
537
538 // If the comparison is an equality comparison with null, we can simplify it
539 // for any alloca-derived argument.
540 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
541 if (isAllocaDerivedArg(I.getOperand(0))) {
542 // We can actually predict the result of comparisons between an
543 // alloca-derived value and null. Note that this fires regardless of
544 // SROA firing.
545 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
546 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
547 : ConstantInt::getFalse(I.getType());
548 return true;
549 }
550
551 // Finally check for SROA candidates in comparisons.
552 Value *SROAArg;
553 DenseMap<Value *, int>::iterator CostIt;
554 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
555 if (isa<ConstantPointerNull>(I.getOperand(1))) {
556 accumulateSROACost(CostIt, InlineConstants::InstrCost);
557 return true;
558 }
559
560 disableSROA(CostIt);
561 }
562
563 return false;
564}
565
566bool CallAnalyzer::visitSub(BinaryOperator &I) {
567 // Try to handle a special case: we can fold computing the difference of two
568 // constant-related pointers.
569 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
570 Value *LHSBase, *RHSBase;
571 APInt LHSOffset, RHSOffset;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000572 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
Chandler Carruth0539c072012-03-31 12:42:41 +0000573 if (LHSBase) {
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000574 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
Chandler Carruth0539c072012-03-31 12:42:41 +0000575 if (RHSBase && LHSBase == RHSBase) {
576 // We have common bases, fold the subtract to a constant based on the
577 // offsets.
578 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
579 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
580 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
581 SimplifiedValues[&I] = C;
582 ++NumConstantPtrDiffs;
583 return true;
584 }
585 }
586 }
587
588 // Otherwise, fall back to the generic logic for simplifying and handling
589 // instructions.
590 return Base::visitSub(I);
591}
592
593bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
594 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000595 const DataLayout &DL = F.getParent()->getDataLayout();
Chandler Carruth0539c072012-03-31 12:42:41 +0000596 if (!isa<Constant>(LHS))
597 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
598 LHS = SimpleLHS;
599 if (!isa<Constant>(RHS))
600 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
601 RHS = SimpleRHS;
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000602 Value *SimpleV = nullptr;
603 if (auto FI = dyn_cast<FPMathOperator>(&I))
604 SimpleV =
605 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
606 else
607 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
608
Chandler Carruth0539c072012-03-31 12:42:41 +0000609 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
610 SimplifiedValues[&I] = C;
611 return true;
612 }
613
614 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
615 disableSROA(LHS);
616 disableSROA(RHS);
617
618 return false;
619}
620
621bool CallAnalyzer::visitLoad(LoadInst &I) {
622 Value *SROAArg;
623 DenseMap<Value *, int>::iterator CostIt;
624 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
625 if (I.isSimple()) {
626 accumulateSROACost(CostIt, InlineConstants::InstrCost);
627 return true;
628 }
629
630 disableSROA(CostIt);
631 }
632
633 return false;
634}
635
636bool CallAnalyzer::visitStore(StoreInst &I) {
637 Value *SROAArg;
638 DenseMap<Value *, int>::iterator CostIt;
639 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
640 if (I.isSimple()) {
641 accumulateSROACost(CostIt, InlineConstants::InstrCost);
642 return true;
643 }
644
645 disableSROA(CostIt);
646 }
647
648 return false;
649}
650
Chandler Carruth753e21d2012-12-28 14:23:32 +0000651bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
652 // Constant folding for extract value is trivial.
653 Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
654 if (!C)
655 C = SimplifiedValues.lookup(I.getAggregateOperand());
656 if (C) {
657 SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
658 return true;
659 }
660
661 // SROA can look through these but give them a cost.
662 return false;
663}
664
665bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
666 // Constant folding for insert value is trivial.
667 Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
668 if (!AggC)
669 AggC = SimplifiedValues.lookup(I.getAggregateOperand());
670 Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
671 if (!InsertedC)
672 InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
673 if (AggC && InsertedC) {
674 SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
675 I.getIndices());
676 return true;
677 }
678
679 // SROA can look through these but give them a cost.
680 return false;
681}
682
683/// \brief Try to simplify a call site.
684///
685/// Takes a concrete function and callsite and tries to actually simplify it by
686/// analyzing the arguments and call itself with instsimplify. Returns true if
687/// it has simplified the callsite to some other entity (a constant), making it
688/// free.
689bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
690 // FIXME: Using the instsimplify logic directly for this is inefficient
691 // because we have to continually rebuild the argument list even when no
692 // simplifications can be performed. Until that is fixed with remapping
693 // inside of instsimplify, directly constant fold calls here.
694 if (!canConstantFoldCallTo(F))
695 return false;
696
697 // Try to re-map the arguments to constants.
698 SmallVector<Constant *, 4> ConstantArgs;
699 ConstantArgs.reserve(CS.arg_size());
700 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
701 I != E; ++I) {
702 Constant *C = dyn_cast<Constant>(*I);
703 if (!C)
704 C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
705 if (!C)
706 return false; // This argument doesn't map to a constant.
707
708 ConstantArgs.push_back(C);
709 }
710 if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
711 SimplifiedValues[CS.getInstruction()] = C;
712 return true;
713 }
714
715 return false;
716}
717
Chandler Carruth0539c072012-03-31 12:42:41 +0000718bool CallAnalyzer::visitCallSite(CallSite CS) {
Chandler Carruth37d25de2013-12-13 08:00:01 +0000719 if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
Duncan P. N. Exon Smithb3fc83c2015-02-14 00:12:15 +0000720 !F.hasFnAttribute(Attribute::ReturnsTwice)) {
Chandler Carruth0539c072012-03-31 12:42:41 +0000721 // This aborts the entire analysis.
722 ExposesReturnsTwice = true;
723 return false;
724 }
James Molloy4f6fb952012-12-20 16:04:27 +0000725 if (CS.isCall() &&
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000726 cast<CallInst>(CS.getInstruction())->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000727 ContainsNoDuplicateCall = true;
Chandler Carruth0539c072012-03-31 12:42:41 +0000728
Chandler Carruth0539c072012-03-31 12:42:41 +0000729 if (Function *F = CS.getCalledFunction()) {
Chandler Carruth753e21d2012-12-28 14:23:32 +0000730 // When we have a concrete function, first try to simplify it directly.
731 if (simplifyCallSite(F, CS))
732 return true;
733
734 // Next check if it is an intrinsic we know about.
735 // FIXME: Lift this into part of the InstVisitor.
736 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
737 switch (II->getIntrinsicID()) {
738 default:
739 return Base::visitCallSite(CS);
740
741 case Intrinsic::memset:
742 case Intrinsic::memcpy:
743 case Intrinsic::memmove:
744 // SROA can usually chew through these intrinsics, but they aren't free.
745 return false;
746 }
747 }
748
Chandler Carruth0539c072012-03-31 12:42:41 +0000749 if (F == CS.getInstruction()->getParent()->getParent()) {
750 // This flag will fully abort the analysis, so don't bother with anything
751 // else.
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +0000752 IsRecursiveCall = true;
Chandler Carruth0539c072012-03-31 12:42:41 +0000753 return false;
754 }
755
Chandler Carruth0ba8db42013-01-22 11:26:02 +0000756 if (TTI.isLoweredToCall(F)) {
Chandler Carruth0539c072012-03-31 12:42:41 +0000757 // We account for the average 1 instruction per call argument setup
758 // here.
759 Cost += CS.arg_size() * InlineConstants::InstrCost;
760
761 // Everything other than inline ASM will also have a significant cost
762 // merely from making the call.
763 if (!isa<InlineAsm>(CS.getCalledValue()))
764 Cost += InlineConstants::CallPenalty;
765 }
766
767 return Base::visitCallSite(CS);
768 }
769
770 // Otherwise we're in a very special case -- an indirect function call. See
771 // if we can be particularly clever about this.
772 Value *Callee = CS.getCalledValue();
773
774 // First, pay the price of the argument setup. We account for the average
775 // 1 instruction per call argument setup here.
776 Cost += CS.arg_size() * InlineConstants::InstrCost;
777
778 // Next, check if this happens to be an indirect function call to a known
779 // function in this inline context. If not, we've done all we can.
780 Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
781 if (!F)
782 return Base::visitCallSite(CS);
783
784 // If we have a constant that we are calling as a function, we can peer
785 // through it and see the function target. This happens not infrequently
786 // during devirtualization and so we want to give it a hefty bonus for
787 // inlining, but cap that bonus in the event that inlining wouldn't pan
788 // out. Pretend to inline the function, with a custom threshold.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000789 CallAnalyzer CA(TTI, ACT, *F, InlineConstants::IndirectCallThreshold);
Chandler Carruth0539c072012-03-31 12:42:41 +0000790 if (CA.analyzeCall(CS)) {
791 // We were able to inline the indirect call! Subtract the cost from the
792 // bonus we want to apply, but don't go below zero.
793 Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
794 }
795
796 return Base::visitCallSite(CS);
797}
798
Chandler Carruth0814d2a2013-12-13 07:59:56 +0000799bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
800 // At least one return instruction will be free after inlining.
801 bool Free = !HasReturn;
802 HasReturn = true;
803 return Free;
804}
805
806bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
807 // We model unconditional branches as essentially free -- they really
808 // shouldn't exist at all, but handling them makes the behavior of the
809 // inliner more regular and predictable. Interestingly, conditional branches
810 // which will fold away are also free.
811 return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
812 dyn_cast_or_null<ConstantInt>(
813 SimplifiedValues.lookup(BI.getCondition()));
814}
815
816bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
817 // We model unconditional switches as free, see the comments on handling
818 // branches.
Chandler Carruthe01fd5f2014-04-28 08:52:44 +0000819 if (isa<ConstantInt>(SI.getCondition()))
820 return true;
821 if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
822 if (isa<ConstantInt>(V))
823 return true;
824
825 // Otherwise, we need to accumulate a cost proportional to the number of
826 // distinct successor blocks. This fan-out in the CFG cannot be represented
827 // for free even if we can represent the core switch as a jumptable that
828 // takes a single instruction.
829 //
830 // NB: We convert large switches which are just used to initialize large phi
831 // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
832 // inlining those. It will prevent inlining in cases where the optimization
833 // does not (yet) fire.
834 SmallPtrSet<BasicBlock *, 8> SuccessorBlocks;
835 SuccessorBlocks.insert(SI.getDefaultDest());
836 for (auto I = SI.case_begin(), E = SI.case_end(); I != E; ++I)
837 SuccessorBlocks.insert(I.getCaseSuccessor());
838 // Add cost corresponding to the number of distinct destinations. The first
839 // we model as free because of fallthrough.
840 Cost += (SuccessorBlocks.size() - 1) * InlineConstants::InstrCost;
841 return false;
Chandler Carruth0814d2a2013-12-13 07:59:56 +0000842}
843
844bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
845 // We never want to inline functions that contain an indirectbr. This is
846 // incorrect because all the blockaddress's (in static global initializers
847 // for example) would be referring to the original function, and this
848 // indirect jump would jump from the inlined copy of the function into the
849 // original function which is extremely undefined behavior.
850 // FIXME: This logic isn't really right; we can safely inline functions with
851 // indirectbr's as long as no other function or global references the
Gerolf Hoflehner734f4c82014-07-01 00:19:34 +0000852 // blockaddress of a block within the current function.
Chandler Carruth0814d2a2013-12-13 07:59:56 +0000853 HasIndirectBr = true;
854 return false;
855}
856
857bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
858 // FIXME: It's not clear that a single instruction is an accurate model for
859 // the inline cost of a resume instruction.
860 return false;
861}
862
863bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
864 // FIXME: It might be reasonably to discount the cost of instructions leading
865 // to unreachable as they have the lowest possible impact on both runtime and
866 // code size.
867 return true; // No actual code is needed for unreachable.
868}
869
Chandler Carruth0539c072012-03-31 12:42:41 +0000870bool CallAnalyzer::visitInstruction(Instruction &I) {
Chandler Carruthda7513a2012-05-04 00:58:03 +0000871 // Some instructions are free. All of the free intrinsics can also be
872 // handled by SROA, etc.
Chandler Carruthb8cf5102013-01-21 12:05:16 +0000873 if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
Chandler Carruthda7513a2012-05-04 00:58:03 +0000874 return true;
875
Chandler Carruth0539c072012-03-31 12:42:41 +0000876 // We found something we don't understand or can't handle. Mark any SROA-able
877 // values in the operand list as no longer viable.
878 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
879 disableSROA(*OI);
880
881 return false;
882}
883
884
885/// \brief Analyze a basic block for its contribution to the inline cost.
886///
887/// This method walks the analyzer over every instruction in the given basic
888/// block and accounts for their cost during inlining at this callsite. It
889/// aborts early if the threshold has been exceeded or an impossible to inline
890/// construct has been detected. It returns false if inlining is no longer
891/// viable, and true if inlining remains viable.
Hal Finkel57f03dd2014-09-07 13:49:57 +0000892bool CallAnalyzer::analyzeBlock(BasicBlock *BB,
893 SmallPtrSetImpl<const Value *> &EphValues) {
Chandler Carruth0814d2a2013-12-13 07:59:56 +0000894 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chandler Carruth6b4cc8b2014-02-01 10:38:17 +0000895 // FIXME: Currently, the number of instructions in a function regardless of
896 // our ability to simplify them during inline to constants or dead code,
897 // are actually used by the vector bonus heuristic. As long as that's true,
898 // we have to special case debug intrinsics here to prevent differences in
899 // inlining due to debug symbols. Eventually, the number of unsimplified
900 // instructions shouldn't factor into the cost computation, but until then,
901 // hack around it here.
902 if (isa<DbgInfoIntrinsic>(I))
903 continue;
904
Hal Finkel57f03dd2014-09-07 13:49:57 +0000905 // Skip ephemeral values.
906 if (EphValues.count(I))
907 continue;
908
Chandler Carruth0539c072012-03-31 12:42:41 +0000909 ++NumInstructions;
910 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
911 ++NumVectorInstructions;
912
Cameron Esfahani17177d12015-02-05 02:09:33 +0000913 // If the instruction is floating point, and the target says this operation is
914 // expensive or the function has the "use-soft-float" attribute, this may
915 // eventually become a library call. Treat the cost as such.
916 if (I->getType()->isFloatingPointTy()) {
917 bool hasSoftFloatAttr = false;
918
919 // If the function has the "use-soft-float" attribute, mark it as expensive.
920 if (F.hasFnAttribute("use-soft-float")) {
921 Attribute Attr = F.getFnAttribute("use-soft-float");
922 StringRef Val = Attr.getValueAsString();
923 if (Val == "true")
924 hasSoftFloatAttr = true;
925 }
926
927 if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive ||
928 hasSoftFloatAttr)
929 Cost += InlineConstants::CallPenalty;
930 }
931
Chandler Carruth0539c072012-03-31 12:42:41 +0000932 // If the instruction simplified to a constant, there is no cost to this
933 // instruction. Visit the instructions using our InstVisitor to account for
934 // all of the per-instruction logic. The visit tree returns true if we
935 // consumed the instruction in any way, and false if the instruction's base
936 // cost should count against inlining.
937 if (Base::visit(I))
938 ++NumInstructionsSimplified;
939 else
940 Cost += InlineConstants::InstrCost;
941
942 // If the visit this instruction detected an uninlinable pattern, abort.
Chandler Carruth0814d2a2013-12-13 07:59:56 +0000943 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
944 HasIndirectBr)
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +0000945 return false;
946
947 // If the caller is a recursive function then we don't want to inline
948 // functions which allocate a lot of stack space because it would increase
949 // the caller stack usage dramatically.
950 if (IsCallerRecursive &&
951 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
Chandler Carruth0539c072012-03-31 12:42:41 +0000952 return false;
953
954 if (NumVectorInstructions > NumInstructions/2)
955 VectorBonus = FiftyPercentVectorBonus;
956 else if (NumVectorInstructions > NumInstructions/10)
957 VectorBonus = TenPercentVectorBonus;
958 else
959 VectorBonus = 0;
960
961 // Check if we've past the threshold so we don't spin in huge basic
962 // blocks that will never inline.
Bob Wilsona5b0dc82012-11-19 07:04:35 +0000963 if (Cost > (Threshold + VectorBonus))
Chandler Carruth0539c072012-03-31 12:42:41 +0000964 return false;
965 }
966
967 return true;
968}
969
970/// \brief Compute the base pointer and cumulative constant offsets for V.
971///
972/// This strips all constant offsets off of V, leaving it the base pointer, and
973/// accumulates the total constant offset applied in the returned constant. It
974/// returns 0 if V is not a pointer, and returns the constant '0' if there are
975/// no constant offsets applied.
976ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000977 if (!V->getType()->isPointerTy())
Craig Topper353eda42014-04-24 06:44:33 +0000978 return nullptr;
Chandler Carruth0539c072012-03-31 12:42:41 +0000979
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000980 const DataLayout &DL = F.getParent()->getDataLayout();
981 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruth0539c072012-03-31 12:42:41 +0000982 APInt Offset = APInt::getNullValue(IntPtrWidth);
983
984 // Even though we don't look through PHI nodes, we could be called on an
985 // instruction in an unreachable block, which may be on a cycle.
986 SmallPtrSet<Value *, 4> Visited;
987 Visited.insert(V);
988 do {
989 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
990 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
Craig Topper353eda42014-04-24 06:44:33 +0000991 return nullptr;
Chandler Carruth0539c072012-03-31 12:42:41 +0000992 V = GEP->getPointerOperand();
993 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
994 V = cast<Operator>(V)->getOperand(0);
995 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
996 if (GA->mayBeOverridden())
997 break;
998 V = GA->getAliasee();
999 } else {
1000 break;
1001 }
1002 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001003 } while (Visited.insert(V).second);
Chandler Carruth0539c072012-03-31 12:42:41 +00001004
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001005 Type *IntPtrTy = DL.getIntPtrType(V->getContext());
Chandler Carruth0539c072012-03-31 12:42:41 +00001006 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
1007}
1008
1009/// \brief Analyze a call site for potential inlining.
1010///
1011/// Returns true if inlining this call is viable, and false if it is not
1012/// viable. It computes the cost and adjusts the threshold based on numerous
1013/// factors and heuristics. If this method returns false but the computed cost
1014/// is below the computed threshold, then inlining was forcibly disabled by
Bob Wilson266802d2012-11-19 07:04:30 +00001015/// some artifact of the routine.
Chandler Carruth0539c072012-03-31 12:42:41 +00001016bool CallAnalyzer::analyzeCall(CallSite CS) {
Chandler Carruth7ae90d42012-04-11 10:15:10 +00001017 ++NumCallsAnalyzed;
1018
Chandler Carruth0539c072012-03-31 12:42:41 +00001019 // Track whether the post-inlining function would have more than one basic
1020 // block. A single basic block is often intended for inlining. Balloon the
1021 // threshold by 50% until we pass the single-BB phase.
1022 bool SingleBB = true;
1023 int SingleBBBonus = Threshold / 2;
1024 Threshold += SingleBBBonus;
1025
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001026 // Perform some tweaks to the cost and threshold based on the direct
1027 // callsite information.
Chandler Carruth0539c072012-03-31 12:42:41 +00001028
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001029 // We want to more aggressively inline vector-dense kernels, so up the
1030 // threshold, and we'll lower it if the % of vector instructions gets too
1031 // low.
1032 assert(NumInstructions == 0);
1033 assert(NumVectorInstructions == 0);
1034 FiftyPercentVectorBonus = Threshold;
1035 TenPercentVectorBonus = Threshold / 2;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001036 const DataLayout &DL = F.getParent()->getDataLayout();
Benjamin Kramerc99d0e92012-08-07 11:13:19 +00001037
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001038 // Give out bonuses per argument, as the instructions setting them up will
1039 // be gone after inlining.
1040 for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001041 if (CS.isByValArgument(I)) {
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001042 // We approximate the number of loads and stores needed by dividing the
1043 // size of the byval type by the target's pointer size.
1044 PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001045 unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
1046 unsigned PointerSize = DL.getPointerSizeInBits();
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001047 // Ceiling division.
1048 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
Benjamin Kramerc99d0e92012-08-07 11:13:19 +00001049
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001050 // If it generates more than 8 stores it is likely to be expanded as an
1051 // inline memcpy so we take that as an upper bound. Otherwise we assume
1052 // one load and one store per word copied.
1053 // FIXME: The maxStoresPerMemcpy setting from the target should be used
1054 // here instead of a magic number of 8, but it's not available via
1055 // DataLayout.
1056 NumStores = std::min(NumStores, 8U);
1057
1058 Cost -= 2 * NumStores * InlineConstants::InstrCost;
1059 } else {
1060 // For non-byval arguments subtract off one instruction per call
1061 // argument.
1062 Cost -= InlineConstants::InstrCost;
Benjamin Kramerc99d0e92012-08-07 11:13:19 +00001063 }
Chandler Carruth0539c072012-03-31 12:42:41 +00001064 }
1065
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001066 // If there is only one call of the function, and it has internal linkage,
1067 // the cost of inlining it drops dramatically.
James Molloy4f6fb952012-12-20 16:04:27 +00001068 bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
1069 &F == CS.getCalledFunction();
1070 if (OnlyOneCallAndLocalLinkage)
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001071 Cost += InlineConstants::LastCallToStaticBonus;
1072
1073 // If the instruction after the call, or if the normal destination of the
1074 // invoke is an unreachable instruction, the function is noreturn. As such,
1075 // there is little point in inlining this unless there is literally zero
1076 // cost.
1077 Instruction *Instr = CS.getInstruction();
1078 if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
1079 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
1080 Threshold = 1;
1081 } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
1082 Threshold = 1;
1083
1084 // If this function uses the coldcc calling convention, prefer not to inline
1085 // it.
1086 if (F.getCallingConv() == CallingConv::Cold)
1087 Cost += InlineConstants::ColdccPenalty;
1088
1089 // Check if we're done. This can happen due to bonuses and penalties.
1090 if (Cost > Threshold)
1091 return false;
1092
Chandler Carruth0539c072012-03-31 12:42:41 +00001093 if (F.empty())
1094 return true;
1095
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +00001096 Function *Caller = CS.getInstruction()->getParent()->getParent();
1097 // Check if the caller function is recursive itself.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001098 for (User *U : Caller->users()) {
1099 CallSite Site(U);
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +00001100 if (!Site)
1101 continue;
1102 Instruction *I = Site.getInstruction();
1103 if (I->getParent()->getParent() == Caller) {
1104 IsCallerRecursive = true;
1105 break;
1106 }
1107 }
1108
Chandler Carruth0539c072012-03-31 12:42:41 +00001109 // Populate our simplified values by mapping from function arguments to call
1110 // arguments with known important simplifications.
1111 CallSite::arg_iterator CAI = CS.arg_begin();
1112 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
1113 FAI != FAE; ++FAI, ++CAI) {
1114 assert(CAI != CS.arg_end());
1115 if (Constant *C = dyn_cast<Constant>(CAI))
1116 SimplifiedValues[FAI] = C;
1117
1118 Value *PtrArg = *CAI;
1119 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
1120 ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
1121
1122 // We can SROA any pointer arguments derived from alloca instructions.
1123 if (isa<AllocaInst>(PtrArg)) {
1124 SROAArgValues[FAI] = PtrArg;
1125 SROAArgCosts[PtrArg] = 0;
1126 }
1127 }
1128 }
1129 NumConstantArgs = SimplifiedValues.size();
1130 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
1131 NumAllocaArgs = SROAArgValues.size();
1132
Hal Finkel57f03dd2014-09-07 13:49:57 +00001133 // FIXME: If a caller has multiple calls to a callee, we end up recomputing
1134 // the ephemeral values multiple times (and they're completely determined by
1135 // the callee, so this is purely duplicate work).
1136 SmallPtrSet<const Value *, 32> EphValues;
Bjorn Steinbrink6f972a12015-02-12 21:04:22 +00001137 CodeMetrics::collectEphemeralValues(&F, &ACT->getAssumptionCache(F), EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +00001138
Chandler Carruth0539c072012-03-31 12:42:41 +00001139 // The worklist of live basic blocks in the callee *after* inlining. We avoid
1140 // adding basic blocks of the callee which can be proven to be dead for this
1141 // particular call site in order to get more accurate cost estimates. This
1142 // requires a somewhat heavyweight iteration pattern: we need to walk the
1143 // basic blocks in a breadth-first order as we insert live successors. To
1144 // accomplish this, prioritizing for small iterations because we exit after
1145 // crossing our threshold, we use a small-size optimized SetVector.
1146 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1147 SmallPtrSet<BasicBlock *, 16> > BBSetVector;
1148 BBSetVector BBWorklist;
1149 BBWorklist.insert(&F.getEntryBlock());
1150 // Note that we *must not* cache the size, this loop grows the worklist.
1151 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1152 // Bail out the moment we cross the threshold. This means we'll under-count
1153 // the cost, but only when undercounting doesn't matter.
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001154 if (Cost > (Threshold + VectorBonus))
Chandler Carruth0539c072012-03-31 12:42:41 +00001155 break;
1156
1157 BasicBlock *BB = BBWorklist[Idx];
1158 if (BB->empty())
Chandler Carruth4d1d34f2012-03-14 23:19:53 +00001159 continue;
Dan Gohman4552e3c2009-10-13 18:30:07 +00001160
Gerolf Hoflehner734f4c82014-07-01 00:19:34 +00001161 // Disallow inlining a blockaddress. A blockaddress only has defined
1162 // behavior for an indirect branch in the same function, and we do not
1163 // currently support inlining indirect branches. But, the inliner may not
1164 // see an indirect branch that ends up being dead code at a particular call
1165 // site. If the blockaddress escapes the function, e.g., via a global
1166 // variable, inlining may lead to an invalid cross-function reference.
1167 if (BB->hasAddressTaken())
1168 return false;
1169
Chandler Carruth0539c072012-03-31 12:42:41 +00001170 // Analyze the cost of this block. If we blow through the threshold, this
1171 // returns false, and we can bail on out.
Hal Finkel57f03dd2014-09-07 13:49:57 +00001172 if (!analyzeBlock(BB, EphValues)) {
Chandler Carruth0814d2a2013-12-13 07:59:56 +00001173 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
1174 HasIndirectBr)
Chandler Carruth0539c072012-03-31 12:42:41 +00001175 return false;
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +00001176
1177 // If the caller is a recursive function then we don't want to inline
1178 // functions which allocate a lot of stack space because it would increase
1179 // the caller stack usage dramatically.
1180 if (IsCallerRecursive &&
1181 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
1182 return false;
1183
Chandler Carruth0539c072012-03-31 12:42:41 +00001184 break;
Eric Christopher46308e62011-02-01 01:16:32 +00001185 }
Eric Christopher46308e62011-02-01 01:16:32 +00001186
Chandler Carruth0814d2a2013-12-13 07:59:56 +00001187 TerminatorInst *TI = BB->getTerminator();
1188
Chandler Carruth0539c072012-03-31 12:42:41 +00001189 // Add in the live successors by first checking whether we have terminator
1190 // that may be simplified based on the values simplified by this call.
1191 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1192 if (BI->isConditional()) {
1193 Value *Cond = BI->getCondition();
1194 if (ConstantInt *SimpleCond
1195 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1196 BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
1197 continue;
Eric Christopher46308e62011-02-01 01:16:32 +00001198 }
Chandler Carruth0539c072012-03-31 12:42:41 +00001199 }
1200 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1201 Value *Cond = SI->getCondition();
1202 if (ConstantInt *SimpleCond
1203 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1204 BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
1205 continue;
1206 }
1207 }
Eric Christopher46308e62011-02-01 01:16:32 +00001208
Chandler Carruth0539c072012-03-31 12:42:41 +00001209 // If we're unable to select a particular successor, just count all of
1210 // them.
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +00001211 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1212 ++TIdx)
Chandler Carruth0539c072012-03-31 12:42:41 +00001213 BBWorklist.insert(TI->getSuccessor(TIdx));
1214
1215 // If we had any successors at this point, than post-inlining is likely to
1216 // have them as well. Note that we assume any basic blocks which existed
1217 // due to branches or switches which folded above will also fold after
1218 // inlining.
1219 if (SingleBB && TI->getNumSuccessors() > 1) {
1220 // Take off the bonus we applied to the threshold.
1221 Threshold -= SingleBBBonus;
1222 SingleBB = false;
Eric Christopher46308e62011-02-01 01:16:32 +00001223 }
1224 }
Andrew Trickcaa500b2011-10-01 01:27:56 +00001225
Chandler Carruthcb5beb32013-12-12 11:59:26 +00001226 // If this is a noduplicate call, we can still inline as long as
James Molloy4f6fb952012-12-20 16:04:27 +00001227 // inlining this would cause the removal of the caller (so the instruction
1228 // is not actually duplicated, just moved).
1229 if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
1230 return false;
1231
Chandler Carruth0539c072012-03-31 12:42:41 +00001232 Threshold += VectorBonus;
1233
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001234 return Cost < Threshold;
Eric Christopher2dfbd7e2011-02-05 00:49:15 +00001235}
1236
Manman Ren49d684e2012-09-12 05:06:18 +00001237#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth0539c072012-03-31 12:42:41 +00001238/// \brief Dump stats about this call's analysis.
1239void CallAnalyzer::dump() {
Eric Christophera13839f2014-02-26 23:27:16 +00001240#define DEBUG_PRINT_STAT(x) dbgs() << " " #x ": " << x << "\n"
Chandler Carruth0539c072012-03-31 12:42:41 +00001241 DEBUG_PRINT_STAT(NumConstantArgs);
1242 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1243 DEBUG_PRINT_STAT(NumAllocaArgs);
1244 DEBUG_PRINT_STAT(NumConstantPtrCmps);
1245 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1246 DEBUG_PRINT_STAT(NumInstructionsSimplified);
1247 DEBUG_PRINT_STAT(SROACostSavings);
1248 DEBUG_PRINT_STAT(SROACostSavingsLost);
James Molloy4f6fb952012-12-20 16:04:27 +00001249 DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
Chandler Carruth394e34f2014-01-31 22:32:32 +00001250 DEBUG_PRINT_STAT(Cost);
1251 DEBUG_PRINT_STAT(Threshold);
1252 DEBUG_PRINT_STAT(VectorBonus);
Chandler Carruth0539c072012-03-31 12:42:41 +00001253#undef DEBUG_PRINT_STAT
Eric Christopher2dfbd7e2011-02-05 00:49:15 +00001254}
Manman Renc3366cc2012-09-06 19:55:56 +00001255#endif
Eric Christopher2dfbd7e2011-02-05 00:49:15 +00001256
Chandler Carruth4319e292013-01-21 11:39:18 +00001257INITIALIZE_PASS_BEGIN(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
1258 true, true)
Chandler Carruth705b1852015-01-31 03:43:40 +00001259INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +00001260INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth4319e292013-01-21 11:39:18 +00001261INITIALIZE_PASS_END(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
1262 true, true)
1263
1264char InlineCostAnalysis::ID = 0;
1265
Rafael Espindola339430f2014-02-25 23:25:17 +00001266InlineCostAnalysis::InlineCostAnalysis() : CallGraphSCCPass(ID) {}
Chandler Carruth4319e292013-01-21 11:39:18 +00001267
1268InlineCostAnalysis::~InlineCostAnalysis() {}
1269
1270void InlineCostAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1271 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001272 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth705b1852015-01-31 03:43:40 +00001273 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth4319e292013-01-21 11:39:18 +00001274 CallGraphSCCPass::getAnalysisUsage(AU);
1275}
1276
1277bool InlineCostAnalysis::runOnSCC(CallGraphSCC &SCC) {
Chandler Carruthfdb9c572015-02-01 12:01:35 +00001278 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
Chandler Carruth66b31302015-01-04 12:03:27 +00001279 ACT = &getAnalysis<AssumptionCacheTracker>();
Chandler Carruth4319e292013-01-21 11:39:18 +00001280 return false;
1281}
1282
1283InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, int Threshold) {
David Chisnallc1c9cda2012-04-06 17:27:41 +00001284 return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1285}
Dan Gohman4552e3c2009-10-13 18:30:07 +00001286
Evgeniy Stepanov2ad36982013-08-08 08:22:39 +00001287/// \brief Test that two functions either have or have not the given attribute
1288/// at the same time.
1289static bool attributeMatches(Function *F1, Function *F2,
1290 Attribute::AttrKind Attr) {
1291 return F1->hasFnAttribute(Attr) == F2->hasFnAttribute(Attr);
1292}
1293
1294/// \brief Test that there are no attribute conflicts between Caller and Callee
1295/// that prevent inlining.
1296static bool functionsHaveCompatibleAttributes(Function *Caller,
1297 Function *Callee) {
1298 return attributeMatches(Caller, Callee, Attribute::SanitizeAddress) &&
1299 attributeMatches(Caller, Callee, Attribute::SanitizeMemory) &&
1300 attributeMatches(Caller, Callee, Attribute::SanitizeThread);
1301}
1302
Chandler Carruth4319e292013-01-21 11:39:18 +00001303InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, Function *Callee,
David Chisnallc1c9cda2012-04-06 17:27:41 +00001304 int Threshold) {
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001305 // Cannot inline indirect calls.
1306 if (!Callee)
1307 return llvm::InlineCost::getNever();
1308
1309 // Calls to functions with always-inline attributes should be inlined
1310 // whenever possible.
Peter Collingbourne68a88972014-05-19 18:25:54 +00001311 if (CS.hasFnAttr(Attribute::AlwaysInline)) {
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001312 if (isInlineViable(*Callee))
1313 return llvm::InlineCost::getAlways();
1314 return llvm::InlineCost::getNever();
1315 }
1316
Evgeniy Stepanov2ad36982013-08-08 08:22:39 +00001317 // Never inline functions with conflicting attributes (unless callee has
1318 // always-inline attribute).
1319 if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee))
1320 return llvm::InlineCost::getNever();
1321
Paul Robinsondcbe35b2013-11-18 21:44:03 +00001322 // Don't inline this call if the caller has the optnone attribute.
1323 if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
1324 return llvm::InlineCost::getNever();
1325
Dan Gohman4552e3c2009-10-13 18:30:07 +00001326 // Don't inline functions which can be redefined at link-time to mean
Eric Christopherb1a382d2010-03-25 04:49:10 +00001327 // something else. Don't inline functions marked noinline or call sites
1328 // marked noinline.
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001329 if (Callee->mayBeOverridden() ||
Evgeniy Stepanov2ad36982013-08-08 08:22:39 +00001330 Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline())
Dan Gohman4552e3c2009-10-13 18:30:07 +00001331 return llvm::InlineCost::getNever();
1332
Nadav Rotem4eb3d4b2012-09-19 08:08:04 +00001333 DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
1334 << "...\n");
Andrew Trickcaa500b2011-10-01 01:27:56 +00001335
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001336 CallAnalyzer CA(TTIWP->getTTI(*Callee), ACT, *Callee, Threshold);
Chandler Carruth0539c072012-03-31 12:42:41 +00001337 bool ShouldInline = CA.analyzeCall(CS);
Dan Gohman4552e3c2009-10-13 18:30:07 +00001338
Chandler Carruth0539c072012-03-31 12:42:41 +00001339 DEBUG(CA.dump());
1340
1341 // Check if there was a reason to force inlining or no inlining.
1342 if (!ShouldInline && CA.getCost() < CA.getThreshold())
Dan Gohman4552e3c2009-10-13 18:30:07 +00001343 return InlineCost::getNever();
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001344 if (ShouldInline && CA.getCost() >= CA.getThreshold())
Dan Gohman4552e3c2009-10-13 18:30:07 +00001345 return InlineCost::getAlways();
Andrew Trickcaa500b2011-10-01 01:27:56 +00001346
Chandler Carruth0539c072012-03-31 12:42:41 +00001347 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
Dan Gohman4552e3c2009-10-13 18:30:07 +00001348}
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001349
Chandler Carruth4319e292013-01-21 11:39:18 +00001350bool InlineCostAnalysis::isInlineViable(Function &F) {
Duncan P. N. Exon Smithb3fc83c2015-02-14 00:12:15 +00001351 bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001352 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
Gerolf Hoflehner734f4c82014-07-01 00:19:34 +00001353 // Disallow inlining of functions which contain indirect branches or
1354 // blockaddresses.
1355 if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
Bob Wilsona5b0dc82012-11-19 07:04:35 +00001356 return false;
1357
1358 for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
1359 ++II) {
1360 CallSite CS(II);
1361 if (!CS)
1362 continue;
1363
1364 // Disallow recursive calls.
1365 if (&F == CS.getCalledFunction())
1366 return false;
1367
1368 // Disallow calls which expose returns-twice to a function not previously
1369 // attributed as such.
1370 if (!ReturnsTwice && CS.isCall() &&
1371 cast<CallInst>(CS.getInstruction())->canReturnTwice())
1372 return false;
1373 }
1374 }
1375
1376 return true;
1377}