blob: 685050765a72c7fda5642fa7e5803fde645834a6 [file] [log] [blame]
Dan Gohmane4aeec02009-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
Chandler Carruthf2286b02012-03-31 12:42:41 +000014#define DEBUG_TYPE "inline-cost"
Dan Gohmane4aeec02009-10-13 18:30:07 +000015#include "llvm/Analysis/InlineCost.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
Chandler Carruthf2286b02012-03-31 12:42:41 +000021#include "llvm/Analysis/ConstantFolding.h"
22#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/CallingConv.h"
24#include "llvm/DataLayout.h"
25#include "llvm/GlobalAlias.h"
26#include "llvm/InstVisitor.h"
27#include "llvm/IntrinsicInst.h"
28#include "llvm/Operator.h"
Dan Gohmane4aeec02009-10-13 18:30:07 +000029#include "llvm/Support/CallSite.h"
Chandler Carruthf2286b02012-03-31 12:42:41 +000030#include "llvm/Support/Debug.h"
Chandler Carruthf2286b02012-03-31 12:42:41 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
32#include "llvm/Support/raw_ostream.h"
Eric Christopher4e8af6d2011-02-05 00:49:15 +000033
Dan Gohmane4aeec02009-10-13 18:30:07 +000034using namespace llvm;
35
Chandler Carruthd6fc2622012-04-11 10:15:10 +000036STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
37
Chandler Carruthf2286b02012-03-31 12:42:41 +000038namespace {
Chandler Carruth3d1d8952012-03-14 07:32:53 +000039
Chandler Carruthf2286b02012-03-31 12:42:41 +000040class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
41 typedef InstVisitor<CallAnalyzer, bool> Base;
42 friend class InstVisitor<CallAnalyzer, bool>;
Owen Anderson082bf2a2010-09-09 16:56:42 +000043
Micah Villmow3574eca2012-10-08 16:38:25 +000044 // DataLayout if available, or null.
45 const DataLayout *const TD;
Owen Anderson082bf2a2010-09-09 16:56:42 +000046
Chandler Carruthf2286b02012-03-31 12:42:41 +000047 // The called function.
48 Function &F;
Owen Anderson082bf2a2010-09-09 16:56:42 +000049
Chandler Carruthf2286b02012-03-31 12:42:41 +000050 int Threshold;
51 int Cost;
Owen Anderson082bf2a2010-09-09 16:56:42 +000052
Nadav Rotem92df0262012-09-19 08:08:04 +000053 bool IsCallerRecursive;
54 bool IsRecursiveCall;
Chandler Carruthf2286b02012-03-31 12:42:41 +000055 bool ExposesReturnsTwice;
56 bool HasDynamicAlloca;
James Molloy67ae1352012-12-20 16:04:27 +000057 bool ContainsNoDuplicateCall;
58
Nadav Rotem92df0262012-09-19 08:08:04 +000059 /// Number of bytes allocated statically by the callee.
60 uint64_t AllocatedSize;
Chandler Carruthf2286b02012-03-31 12:42:41 +000061 unsigned NumInstructions, NumVectorInstructions;
62 int FiftyPercentVectorBonus, TenPercentVectorBonus;
63 int VectorBonus;
64
65 // While we walk the potentially-inlined instructions, we build up and
66 // maintain a mapping of simplified values specific to this callsite. The
67 // idea is to propagate any special information we have about arguments to
68 // this call through the inlinable section of the function, and account for
69 // likely simplifications post-inlining. The most important aspect we track
70 // is CFG altering simplifications -- when we prove a basic block dead, that
71 // can cause dramatic shifts in the cost of inlining a function.
72 DenseMap<Value *, Constant *> SimplifiedValues;
73
74 // Keep track of the values which map back (through function arguments) to
75 // allocas on the caller stack which could be simplified through SROA.
76 DenseMap<Value *, Value *> SROAArgValues;
77
78 // The mapping of caller Alloca values to their accumulated cost savings. If
79 // we have to disable SROA for one of the allocas, this tells us how much
80 // cost must be added.
81 DenseMap<Value *, int> SROAArgCosts;
82
83 // Keep track of values which map to a pointer base and constant offset.
84 DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
85
86 // Custom simplification helper routines.
87 bool isAllocaDerivedArg(Value *V);
88 bool lookupSROAArgAndCost(Value *V, Value *&Arg,
89 DenseMap<Value *, int>::iterator &CostIt);
90 void disableSROA(DenseMap<Value *, int>::iterator CostIt);
91 void disableSROA(Value *V);
92 void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
93 int InstructionCost);
94 bool handleSROACandidate(bool IsSROAValid,
95 DenseMap<Value *, int>::iterator CostIt,
96 int InstructionCost);
97 bool isGEPOffsetConstant(GetElementPtrInst &GEP);
98 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
Chandler Carruthba942042012-12-28 14:23:32 +000099 bool simplifyCallSite(Function *F, CallSite CS);
Chandler Carruthf2286b02012-03-31 12:42:41 +0000100 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
101
102 // Custom analysis routines.
103 bool analyzeBlock(BasicBlock *BB);
104
105 // Disable several entry points to the visitor so we don't accidentally use
106 // them by declaring but not defining them here.
107 void visit(Module *); void visit(Module &);
108 void visit(Function *); void visit(Function &);
109 void visit(BasicBlock *); void visit(BasicBlock &);
110
111 // Provide base case for our instruction visit.
112 bool visitInstruction(Instruction &I);
113
114 // Our visit overrides.
115 bool visitAlloca(AllocaInst &I);
116 bool visitPHI(PHINode &I);
117 bool visitGetElementPtr(GetElementPtrInst &I);
118 bool visitBitCast(BitCastInst &I);
119 bool visitPtrToInt(PtrToIntInst &I);
120 bool visitIntToPtr(IntToPtrInst &I);
121 bool visitCastInst(CastInst &I);
122 bool visitUnaryInstruction(UnaryInstruction &I);
123 bool visitICmp(ICmpInst &I);
124 bool visitSub(BinaryOperator &I);
125 bool visitBinaryOperator(BinaryOperator &I);
126 bool visitLoad(LoadInst &I);
127 bool visitStore(StoreInst &I);
Chandler Carruthba942042012-12-28 14:23:32 +0000128 bool visitExtractValue(ExtractValueInst &I);
129 bool visitInsertValue(InsertValueInst &I);
Chandler Carruthf2286b02012-03-31 12:42:41 +0000130 bool visitCallSite(CallSite CS);
131
132public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000133 CallAnalyzer(const DataLayout *TD, Function &Callee, int Threshold)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000134 : TD(TD), F(Callee), Threshold(Threshold), Cost(0),
Nadav Rotem92df0262012-09-19 08:08:04 +0000135 IsCallerRecursive(false), IsRecursiveCall(false),
James Molloy67ae1352012-12-20 16:04:27 +0000136 ExposesReturnsTwice(false), HasDynamicAlloca(false), ContainsNoDuplicateCall(false),
137 AllocatedSize(0), NumInstructions(0), NumVectorInstructions(0),
Chandler Carruthf2286b02012-03-31 12:42:41 +0000138 FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
139 NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
140 NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
141 NumInstructionsSimplified(0), SROACostSavings(0), SROACostSavingsLost(0) {
142 }
143
144 bool analyzeCall(CallSite CS);
145
146 int getThreshold() { return Threshold; }
147 int getCost() { return Cost; }
148
149 // Keep a bunch of stats about the cost savings found so we can print them
150 // out when debugging.
151 unsigned NumConstantArgs;
152 unsigned NumConstantOffsetPtrArgs;
153 unsigned NumAllocaArgs;
154 unsigned NumConstantPtrCmps;
155 unsigned NumConstantPtrDiffs;
156 unsigned NumInstructionsSimplified;
157 unsigned SROACostSavings;
158 unsigned SROACostSavingsLost;
159
160 void dump();
161};
162
163} // namespace
164
165/// \brief Test whether the given value is an Alloca-derived function argument.
166bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
167 return SROAArgValues.count(V);
Owen Anderson082bf2a2010-09-09 16:56:42 +0000168}
169
Chandler Carruthf2286b02012-03-31 12:42:41 +0000170/// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
171/// Returns false if V does not map to a SROA-candidate.
172bool CallAnalyzer::lookupSROAArgAndCost(
173 Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
174 if (SROAArgValues.empty() || SROAArgCosts.empty())
175 return false;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000176
Chandler Carruthf2286b02012-03-31 12:42:41 +0000177 DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
178 if (ArgIt == SROAArgValues.end())
179 return false;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000180
Chandler Carruthf2286b02012-03-31 12:42:41 +0000181 Arg = ArgIt->second;
182 CostIt = SROAArgCosts.find(Arg);
183 return CostIt != SROAArgCosts.end();
Chandler Carruthe8187e02012-03-09 02:49:36 +0000184}
185
Chandler Carruthf2286b02012-03-31 12:42:41 +0000186/// \brief Disable SROA for the candidate marked by this cost iterator.
Chandler Carruthe8187e02012-03-09 02:49:36 +0000187///
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000188/// This marks the candidate as no longer viable for SROA, and adds the cost
Chandler Carruthf2286b02012-03-31 12:42:41 +0000189/// savings associated with it back into the inline cost measurement.
190void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
191 // If we're no longer able to perform SROA we need to undo its cost savings
192 // and prevent subsequent analysis.
193 Cost += CostIt->second;
194 SROACostSavings -= CostIt->second;
195 SROACostSavingsLost += CostIt->second;
196 SROAArgCosts.erase(CostIt);
197}
198
199/// \brief If 'V' maps to a SROA candidate, disable SROA for it.
200void CallAnalyzer::disableSROA(Value *V) {
201 Value *SROAArg;
202 DenseMap<Value *, int>::iterator CostIt;
203 if (lookupSROAArgAndCost(V, SROAArg, CostIt))
204 disableSROA(CostIt);
205}
206
207/// \brief Accumulate the given cost for a particular SROA candidate.
208void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
209 int InstructionCost) {
210 CostIt->second += InstructionCost;
211 SROACostSavings += InstructionCost;
212}
213
214/// \brief Helper for the common pattern of handling a SROA candidate.
215/// Either accumulates the cost savings if the SROA remains valid, or disables
216/// SROA for the candidate.
217bool CallAnalyzer::handleSROACandidate(bool IsSROAValid,
218 DenseMap<Value *, int>::iterator CostIt,
219 int InstructionCost) {
220 if (IsSROAValid) {
221 accumulateSROACost(CostIt, InstructionCost);
222 return true;
223 }
224
225 disableSROA(CostIt);
226 return false;
227}
228
229/// \brief Check whether a GEP's indices are all constant.
230///
231/// Respects any simplified values known during the analysis of this callsite.
232bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
233 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
234 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
Chandler Carruthe8187e02012-03-09 02:49:36 +0000235 return false;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000236
Chandler Carruthf2286b02012-03-31 12:42:41 +0000237 return true;
238}
239
240/// \brief Accumulate a constant GEP offset into an APInt if possible.
241///
242/// Returns false if unable to compute the offset for any reason. Respects any
243/// simplified values known during the analysis of this callsite.
244bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
245 if (!TD)
246 return false;
247
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000248 unsigned IntPtrWidth = TD->getPointerSizeInBits();
Chandler Carruthf2286b02012-03-31 12:42:41 +0000249 assert(IntPtrWidth == Offset.getBitWidth());
250
251 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
252 GTI != GTE; ++GTI) {
253 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
254 if (!OpC)
255 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
256 OpC = dyn_cast<ConstantInt>(SimpleOp);
257 if (!OpC)
Chandler Carruthe8187e02012-03-09 02:49:36 +0000258 return false;
Chandler Carruthf2286b02012-03-31 12:42:41 +0000259 if (OpC->isZero()) continue;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000260
Chandler Carruthf2286b02012-03-31 12:42:41 +0000261 // Handle a struct index, which adds its field offset to the pointer.
262 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
263 unsigned ElementIdx = OpC->getZExtValue();
264 const StructLayout *SL = TD->getStructLayout(STy);
265 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
266 continue;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000267 }
Chandler Carruthe8187e02012-03-09 02:49:36 +0000268
Chandler Carruthf2286b02012-03-31 12:42:41 +0000269 APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType()));
270 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
271 }
272 return true;
273}
274
275bool CallAnalyzer::visitAlloca(AllocaInst &I) {
276 // FIXME: Check whether inlining will turn a dynamic alloca into a static
277 // alloca, and handle that case.
278
Nadav Rotem92df0262012-09-19 08:08:04 +0000279 // Accumulate the allocated size.
280 if (I.isStaticAlloca()) {
281 Type *Ty = I.getAllocatedType();
282 AllocatedSize += (TD ? TD->getTypeAllocSize(Ty) :
283 Ty->getPrimitiveSizeInBits());
284 }
285
Bob Wilson28f872f2012-11-19 07:04:35 +0000286 // We will happily inline static alloca instructions.
287 if (I.isStaticAlloca())
Chandler Carruthf2286b02012-03-31 12:42:41 +0000288 return Base::visitAlloca(I);
289
290 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
291 // a variety of reasons, and so we would like to not inline them into
292 // functions which don't currently have a dynamic alloca. This simply
293 // disables inlining altogether in the presence of a dynamic alloca.
294 HasDynamicAlloca = true;
295 return false;
296}
297
298bool CallAnalyzer::visitPHI(PHINode &I) {
299 // FIXME: We should potentially be tracking values through phi nodes,
300 // especially when they collapse to a single value due to deleted CFG edges
301 // during inlining.
302
303 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
304 // though we don't want to propagate it's bonuses. The idea is to disable
305 // SROA if it *might* be used in an inappropriate manner.
306
307 // Phi nodes are always zero-cost.
308 return true;
309}
310
311bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
312 Value *SROAArg;
313 DenseMap<Value *, int>::iterator CostIt;
314 bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
315 SROAArg, CostIt);
316
317 // Try to fold GEPs of constant-offset call site argument pointers. This
318 // requires target data and inbounds GEPs.
319 if (TD && I.isInBounds()) {
320 // Check if we have a base + offset for the pointer.
321 Value *Ptr = I.getPointerOperand();
322 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
323 if (BaseAndOffset.first) {
324 // Check if the offset of this GEP is constant, and if so accumulate it
325 // into Offset.
326 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
327 // Non-constant GEPs aren't folded, and disable SROA.
328 if (SROACandidate)
329 disableSROA(CostIt);
330 return false;
331 }
332
333 // Add the result as a new mapping to Base + Offset.
334 ConstantOffsetPtrs[&I] = BaseAndOffset;
335
336 // Also handle SROA candidates here, we already know that the GEP is
337 // all-constant indexed.
338 if (SROACandidate)
339 SROAArgValues[&I] = SROAArg;
340
Chandler Carruthe8187e02012-03-09 02:49:36 +0000341 return true;
342 }
343 }
344
Chandler Carruthf2286b02012-03-31 12:42:41 +0000345 if (isGEPOffsetConstant(I)) {
346 if (SROACandidate)
347 SROAArgValues[&I] = SROAArg;
348
349 // Constant GEPs are modeled as free.
350 return true;
351 }
352
353 // Variable GEPs will require math and will disable SROA.
354 if (SROACandidate)
355 disableSROA(CostIt);
Chandler Carruthe8187e02012-03-09 02:49:36 +0000356 return false;
357}
358
Chandler Carruthf2286b02012-03-31 12:42:41 +0000359bool CallAnalyzer::visitBitCast(BitCastInst &I) {
360 // Propagate constants through bitcasts.
361 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
362 if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
363 SimplifiedValues[&I] = C;
364 return true;
Owen Anderson082bf2a2010-09-09 16:56:42 +0000365 }
Owen Anderson082bf2a2010-09-09 16:56:42 +0000366
Chandler Carruthf2286b02012-03-31 12:42:41 +0000367 // Track base/offsets through casts
368 std::pair<Value *, APInt> BaseAndOffset
369 = ConstantOffsetPtrs.lookup(I.getOperand(0));
370 // Casts don't change the offset, just wrap it up.
371 if (BaseAndOffset.first)
372 ConstantOffsetPtrs[&I] = BaseAndOffset;
373
374 // Also look for SROA candidates here.
375 Value *SROAArg;
376 DenseMap<Value *, int>::iterator CostIt;
377 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
378 SROAArgValues[&I] = SROAArg;
379
380 // Bitcasts are always zero cost.
381 return true;
Owen Anderson082bf2a2010-09-09 16:56:42 +0000382}
383
Chandler Carruthf2286b02012-03-31 12:42:41 +0000384bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
385 // Propagate constants through ptrtoint.
386 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
387 if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
388 SimplifiedValues[&I] = C;
389 return true;
Chandler Carruth274d3772012-03-14 23:19:53 +0000390 }
Chandler Carruthf2286b02012-03-31 12:42:41 +0000391
392 // Track base/offset pairs when converted to a plain integer provided the
393 // integer is large enough to represent the pointer.
394 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000395 if (TD && IntegerSize >= TD->getPointerSizeInBits()) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000396 std::pair<Value *, APInt> BaseAndOffset
397 = ConstantOffsetPtrs.lookup(I.getOperand(0));
398 if (BaseAndOffset.first)
399 ConstantOffsetPtrs[&I] = BaseAndOffset;
400 }
401
402 // This is really weird. Technically, ptrtoint will disable SROA. However,
403 // unless that ptrtoint is *used* somewhere in the live basic blocks after
404 // inlining, it will be nuked, and SROA should proceed. All of the uses which
405 // would block SROA would also block SROA if applied directly to a pointer,
406 // and so we can just add the integer in here. The only places where SROA is
407 // preserved either cannot fire on an integer, or won't in-and-of themselves
408 // disable SROA (ext) w/o some later use that we would see and disable.
409 Value *SROAArg;
410 DenseMap<Value *, int>::iterator CostIt;
411 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
412 SROAArgValues[&I] = SROAArg;
413
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000414 return isInstructionFree(&I, TD);
Chandler Carruth274d3772012-03-14 23:19:53 +0000415}
416
Chandler Carruthf2286b02012-03-31 12:42:41 +0000417bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
418 // Propagate constants through ptrtoint.
419 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
420 if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
421 SimplifiedValues[&I] = C;
422 return true;
423 }
Dan Gohmane4aeec02009-10-13 18:30:07 +0000424
Chandler Carruthf2286b02012-03-31 12:42:41 +0000425 // Track base/offset pairs when round-tripped through a pointer without
426 // modifications provided the integer is not too large.
427 Value *Op = I.getOperand(0);
428 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000429 if (TD && IntegerSize <= TD->getPointerSizeInBits()) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000430 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
431 if (BaseAndOffset.first)
432 ConstantOffsetPtrs[&I] = BaseAndOffset;
433 }
Dan Gohmane4aeec02009-10-13 18:30:07 +0000434
Chandler Carruthf2286b02012-03-31 12:42:41 +0000435 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
436 Value *SROAArg;
437 DenseMap<Value *, int>::iterator CostIt;
438 if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
439 SROAArgValues[&I] = SROAArg;
Chandler Carruth274d3772012-03-14 23:19:53 +0000440
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000441 return isInstructionFree(&I, TD);
Chandler Carruthf2286b02012-03-31 12:42:41 +0000442}
443
444bool CallAnalyzer::visitCastInst(CastInst &I) {
445 // Propagate constants through ptrtoint.
446 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
447 if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
448 SimplifiedValues[&I] = C;
449 return true;
450 }
451
452 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
453 disableSROA(I.getOperand(0));
454
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000455 return isInstructionFree(&I, TD);
Chandler Carruthf2286b02012-03-31 12:42:41 +0000456}
457
458bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
459 Value *Operand = I.getOperand(0);
460 Constant *Ops[1] = { dyn_cast<Constant>(Operand) };
461 if (Ops[0] || (Ops[0] = SimplifiedValues.lookup(Operand)))
462 if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
463 Ops, TD)) {
464 SimplifiedValues[&I] = C;
465 return true;
466 }
467
468 // Disable any SROA on the argument to arbitrary unary operators.
469 disableSROA(Operand);
470
471 return false;
472}
473
474bool CallAnalyzer::visitICmp(ICmpInst &I) {
475 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
476 // First try to handle simplified comparisons.
477 if (!isa<Constant>(LHS))
478 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
479 LHS = SimpleLHS;
480 if (!isa<Constant>(RHS))
481 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
482 RHS = SimpleRHS;
483 if (Constant *CLHS = dyn_cast<Constant>(LHS))
484 if (Constant *CRHS = dyn_cast<Constant>(RHS))
485 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
486 SimplifiedValues[&I] = C;
487 return true;
488 }
489
490 // Otherwise look for a comparison between constant offset pointers with
491 // a common base.
492 Value *LHSBase, *RHSBase;
493 APInt LHSOffset, RHSOffset;
494 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
495 if (LHSBase) {
496 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
497 if (RHSBase && LHSBase == RHSBase) {
498 // We have common bases, fold the icmp to a constant based on the
499 // offsets.
500 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
501 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
502 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
503 SimplifiedValues[&I] = C;
504 ++NumConstantPtrCmps;
505 return true;
506 }
507 }
508 }
509
510 // If the comparison is an equality comparison with null, we can simplify it
511 // for any alloca-derived argument.
512 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
513 if (isAllocaDerivedArg(I.getOperand(0))) {
514 // We can actually predict the result of comparisons between an
515 // alloca-derived value and null. Note that this fires regardless of
516 // SROA firing.
517 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
518 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
519 : ConstantInt::getFalse(I.getType());
520 return true;
521 }
522
523 // Finally check for SROA candidates in comparisons.
524 Value *SROAArg;
525 DenseMap<Value *, int>::iterator CostIt;
526 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
527 if (isa<ConstantPointerNull>(I.getOperand(1))) {
528 accumulateSROACost(CostIt, InlineConstants::InstrCost);
529 return true;
530 }
531
532 disableSROA(CostIt);
533 }
534
535 return false;
536}
537
538bool CallAnalyzer::visitSub(BinaryOperator &I) {
539 // Try to handle a special case: we can fold computing the difference of two
540 // constant-related pointers.
541 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
542 Value *LHSBase, *RHSBase;
543 APInt LHSOffset, RHSOffset;
544 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
545 if (LHSBase) {
546 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
547 if (RHSBase && LHSBase == RHSBase) {
548 // We have common bases, fold the subtract to a constant based on the
549 // offsets.
550 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
551 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
552 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
553 SimplifiedValues[&I] = C;
554 ++NumConstantPtrDiffs;
555 return true;
556 }
557 }
558 }
559
560 // Otherwise, fall back to the generic logic for simplifying and handling
561 // instructions.
562 return Base::visitSub(I);
563}
564
565bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
566 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
567 if (!isa<Constant>(LHS))
568 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
569 LHS = SimpleLHS;
570 if (!isa<Constant>(RHS))
571 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
572 RHS = SimpleRHS;
573 Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, TD);
574 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
575 SimplifiedValues[&I] = C;
576 return true;
577 }
578
579 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
580 disableSROA(LHS);
581 disableSROA(RHS);
582
583 return false;
584}
585
586bool CallAnalyzer::visitLoad(LoadInst &I) {
587 Value *SROAArg;
588 DenseMap<Value *, int>::iterator CostIt;
589 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
590 if (I.isSimple()) {
591 accumulateSROACost(CostIt, InlineConstants::InstrCost);
592 return true;
593 }
594
595 disableSROA(CostIt);
596 }
597
598 return false;
599}
600
601bool CallAnalyzer::visitStore(StoreInst &I) {
602 Value *SROAArg;
603 DenseMap<Value *, int>::iterator CostIt;
604 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
605 if (I.isSimple()) {
606 accumulateSROACost(CostIt, InlineConstants::InstrCost);
607 return true;
608 }
609
610 disableSROA(CostIt);
611 }
612
613 return false;
614}
615
Chandler Carruthba942042012-12-28 14:23:32 +0000616bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
617 // Constant folding for extract value is trivial.
618 Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
619 if (!C)
620 C = SimplifiedValues.lookup(I.getAggregateOperand());
621 if (C) {
622 SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
623 return true;
624 }
625
626 // SROA can look through these but give them a cost.
627 return false;
628}
629
630bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
631 // Constant folding for insert value is trivial.
632 Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
633 if (!AggC)
634 AggC = SimplifiedValues.lookup(I.getAggregateOperand());
635 Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
636 if (!InsertedC)
637 InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
638 if (AggC && InsertedC) {
639 SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
640 I.getIndices());
641 return true;
642 }
643
644 // SROA can look through these but give them a cost.
645 return false;
646}
647
648/// \brief Try to simplify a call site.
649///
650/// Takes a concrete function and callsite and tries to actually simplify it by
651/// analyzing the arguments and call itself with instsimplify. Returns true if
652/// it has simplified the callsite to some other entity (a constant), making it
653/// free.
654bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
655 // FIXME: Using the instsimplify logic directly for this is inefficient
656 // because we have to continually rebuild the argument list even when no
657 // simplifications can be performed. Until that is fixed with remapping
658 // inside of instsimplify, directly constant fold calls here.
659 if (!canConstantFoldCallTo(F))
660 return false;
661
662 // Try to re-map the arguments to constants.
663 SmallVector<Constant *, 4> ConstantArgs;
664 ConstantArgs.reserve(CS.arg_size());
665 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
666 I != E; ++I) {
667 Constant *C = dyn_cast<Constant>(*I);
668 if (!C)
669 C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
670 if (!C)
671 return false; // This argument doesn't map to a constant.
672
673 ConstantArgs.push_back(C);
674 }
675 if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
676 SimplifiedValues[CS.getInstruction()] = C;
677 return true;
678 }
679
680 return false;
681}
682
Chandler Carruthf2286b02012-03-31 12:42:41 +0000683bool CallAnalyzer::visitCallSite(CallSite CS) {
684 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->canReturnTwice() &&
Bill Wendling034b94b2012-12-19 07:18:57 +0000685 !F.getFnAttributes().hasAttribute(Attribute::ReturnsTwice)) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000686 // This aborts the entire analysis.
687 ExposesReturnsTwice = true;
688 return false;
689 }
James Molloy67ae1352012-12-20 16:04:27 +0000690 if (CS.isCall() &&
691 cast<CallInst>(CS.getInstruction())->hasFnAttr(Attribute::NoDuplicate))
692 ContainsNoDuplicateCall = true;
Chandler Carruthf2286b02012-03-31 12:42:41 +0000693
Chandler Carruthf2286b02012-03-31 12:42:41 +0000694 if (Function *F = CS.getCalledFunction()) {
Chandler Carruthba942042012-12-28 14:23:32 +0000695 // When we have a concrete function, first try to simplify it directly.
696 if (simplifyCallSite(F, CS))
697 return true;
698
699 // Next check if it is an intrinsic we know about.
700 // FIXME: Lift this into part of the InstVisitor.
701 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
702 switch (II->getIntrinsicID()) {
703 default:
704 return Base::visitCallSite(CS);
705
706 case Intrinsic::memset:
707 case Intrinsic::memcpy:
708 case Intrinsic::memmove:
709 // SROA can usually chew through these intrinsics, but they aren't free.
710 return false;
711 }
712 }
713
Chandler Carruthf2286b02012-03-31 12:42:41 +0000714 if (F == CS.getInstruction()->getParent()->getParent()) {
715 // This flag will fully abort the analysis, so don't bother with anything
716 // else.
Nadav Rotem92df0262012-09-19 08:08:04 +0000717 IsRecursiveCall = true;
Chandler Carruthf2286b02012-03-31 12:42:41 +0000718 return false;
719 }
720
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000721 if (!callIsSmall(CS)) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000722 // We account for the average 1 instruction per call argument setup
723 // here.
724 Cost += CS.arg_size() * InlineConstants::InstrCost;
725
726 // Everything other than inline ASM will also have a significant cost
727 // merely from making the call.
728 if (!isa<InlineAsm>(CS.getCalledValue()))
729 Cost += InlineConstants::CallPenalty;
730 }
731
732 return Base::visitCallSite(CS);
733 }
734
735 // Otherwise we're in a very special case -- an indirect function call. See
736 // if we can be particularly clever about this.
737 Value *Callee = CS.getCalledValue();
738
739 // First, pay the price of the argument setup. We account for the average
740 // 1 instruction per call argument setup here.
741 Cost += CS.arg_size() * InlineConstants::InstrCost;
742
743 // Next, check if this happens to be an indirect function call to a known
744 // function in this inline context. If not, we've done all we can.
745 Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
746 if (!F)
747 return Base::visitCallSite(CS);
748
749 // If we have a constant that we are calling as a function, we can peer
750 // through it and see the function target. This happens not infrequently
751 // during devirtualization and so we want to give it a hefty bonus for
752 // inlining, but cap that bonus in the event that inlining wouldn't pan
753 // out. Pretend to inline the function, with a custom threshold.
754 CallAnalyzer CA(TD, *F, InlineConstants::IndirectCallThreshold);
755 if (CA.analyzeCall(CS)) {
756 // We were able to inline the indirect call! Subtract the cost from the
757 // bonus we want to apply, but don't go below zero.
758 Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
759 }
760
761 return Base::visitCallSite(CS);
762}
763
764bool CallAnalyzer::visitInstruction(Instruction &I) {
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000765 // Some instructions are free. All of the free intrinsics can also be
766 // handled by SROA, etc.
767 if (isInstructionFree(&I, TD))
768 return true;
769
Chandler Carruthf2286b02012-03-31 12:42:41 +0000770 // We found something we don't understand or can't handle. Mark any SROA-able
771 // values in the operand list as no longer viable.
772 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
773 disableSROA(*OI);
774
775 return false;
776}
777
778
779/// \brief Analyze a basic block for its contribution to the inline cost.
780///
781/// This method walks the analyzer over every instruction in the given basic
782/// block and accounts for their cost during inlining at this callsite. It
783/// aborts early if the threshold has been exceeded or an impossible to inline
784/// construct has been detected. It returns false if inlining is no longer
785/// viable, and true if inlining remains viable.
786bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
787 for (BasicBlock::iterator I = BB->begin(), E = llvm::prior(BB->end());
788 I != E; ++I) {
789 ++NumInstructions;
790 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
791 ++NumVectorInstructions;
792
793 // If the instruction simplified to a constant, there is no cost to this
794 // instruction. Visit the instructions using our InstVisitor to account for
795 // all of the per-instruction logic. The visit tree returns true if we
796 // consumed the instruction in any way, and false if the instruction's base
797 // cost should count against inlining.
798 if (Base::visit(I))
799 ++NumInstructionsSimplified;
800 else
801 Cost += InlineConstants::InstrCost;
802
803 // If the visit this instruction detected an uninlinable pattern, abort.
Nadav Rotem92df0262012-09-19 08:08:04 +0000804 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
805 return false;
806
807 // If the caller is a recursive function then we don't want to inline
808 // functions which allocate a lot of stack space because it would increase
809 // the caller stack usage dramatically.
810 if (IsCallerRecursive &&
811 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000812 return false;
813
814 if (NumVectorInstructions > NumInstructions/2)
815 VectorBonus = FiftyPercentVectorBonus;
816 else if (NumVectorInstructions > NumInstructions/10)
817 VectorBonus = TenPercentVectorBonus;
818 else
819 VectorBonus = 0;
820
821 // Check if we've past the threshold so we don't spin in huge basic
822 // blocks that will never inline.
Bob Wilson28f872f2012-11-19 07:04:35 +0000823 if (Cost > (Threshold + VectorBonus))
Chandler Carruthf2286b02012-03-31 12:42:41 +0000824 return false;
825 }
826
827 return true;
828}
829
830/// \brief Compute the base pointer and cumulative constant offsets for V.
831///
832/// This strips all constant offsets off of V, leaving it the base pointer, and
833/// accumulates the total constant offset applied in the returned constant. It
834/// returns 0 if V is not a pointer, and returns the constant '0' if there are
835/// no constant offsets applied.
836ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
837 if (!TD || !V->getType()->isPointerTy())
838 return 0;
839
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000840 unsigned IntPtrWidth = TD->getPointerSizeInBits();
Chandler Carruthf2286b02012-03-31 12:42:41 +0000841 APInt Offset = APInt::getNullValue(IntPtrWidth);
842
843 // Even though we don't look through PHI nodes, we could be called on an
844 // instruction in an unreachable block, which may be on a cycle.
845 SmallPtrSet<Value *, 4> Visited;
846 Visited.insert(V);
847 do {
848 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
849 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
850 return 0;
851 V = GEP->getPointerOperand();
852 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
853 V = cast<Operator>(V)->getOperand(0);
854 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
855 if (GA->mayBeOverridden())
856 break;
857 V = GA->getAliasee();
858 } else {
859 break;
860 }
861 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
862 } while (Visited.insert(V));
863
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000864 Type *IntPtrTy = TD->getIntPtrType(V->getContext());
Chandler Carruthf2286b02012-03-31 12:42:41 +0000865 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
866}
867
868/// \brief Analyze a call site for potential inlining.
869///
870/// Returns true if inlining this call is viable, and false if it is not
871/// viable. It computes the cost and adjusts the threshold based on numerous
872/// factors and heuristics. If this method returns false but the computed cost
873/// is below the computed threshold, then inlining was forcibly disabled by
Bob Wilson593423f2012-11-19 07:04:30 +0000874/// some artifact of the routine.
Chandler Carruthf2286b02012-03-31 12:42:41 +0000875bool CallAnalyzer::analyzeCall(CallSite CS) {
Chandler Carruthd6fc2622012-04-11 10:15:10 +0000876 ++NumCallsAnalyzed;
877
Chandler Carruthf2286b02012-03-31 12:42:41 +0000878 // Track whether the post-inlining function would have more than one basic
879 // block. A single basic block is often intended for inlining. Balloon the
880 // threshold by 50% until we pass the single-BB phase.
881 bool SingleBB = true;
882 int SingleBBBonus = Threshold / 2;
883 Threshold += SingleBBBonus;
884
Bob Wilson28f872f2012-11-19 07:04:35 +0000885 // Perform some tweaks to the cost and threshold based on the direct
886 // callsite information.
Chandler Carruthf2286b02012-03-31 12:42:41 +0000887
Bob Wilson28f872f2012-11-19 07:04:35 +0000888 // We want to more aggressively inline vector-dense kernels, so up the
889 // threshold, and we'll lower it if the % of vector instructions gets too
890 // low.
891 assert(NumInstructions == 0);
892 assert(NumVectorInstructions == 0);
893 FiftyPercentVectorBonus = Threshold;
894 TenPercentVectorBonus = Threshold / 2;
Benjamin Kramerb6fdd022012-08-07 11:13:19 +0000895
Bob Wilson28f872f2012-11-19 07:04:35 +0000896 // Give out bonuses per argument, as the instructions setting them up will
897 // be gone after inlining.
898 for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
899 if (TD && CS.isByValArgument(I)) {
900 // We approximate the number of loads and stores needed by dividing the
901 // size of the byval type by the target's pointer size.
902 PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
903 unsigned TypeSize = TD->getTypeSizeInBits(PTy->getElementType());
904 unsigned PointerSize = TD->getPointerSizeInBits();
905 // Ceiling division.
906 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
Benjamin Kramerb6fdd022012-08-07 11:13:19 +0000907
Bob Wilson28f872f2012-11-19 07:04:35 +0000908 // If it generates more than 8 stores it is likely to be expanded as an
909 // inline memcpy so we take that as an upper bound. Otherwise we assume
910 // one load and one store per word copied.
911 // FIXME: The maxStoresPerMemcpy setting from the target should be used
912 // here instead of a magic number of 8, but it's not available via
913 // DataLayout.
914 NumStores = std::min(NumStores, 8U);
915
916 Cost -= 2 * NumStores * InlineConstants::InstrCost;
917 } else {
918 // For non-byval arguments subtract off one instruction per call
919 // argument.
920 Cost -= InlineConstants::InstrCost;
Benjamin Kramerb6fdd022012-08-07 11:13:19 +0000921 }
Chandler Carruthf2286b02012-03-31 12:42:41 +0000922 }
923
Bob Wilson28f872f2012-11-19 07:04:35 +0000924 // If there is only one call of the function, and it has internal linkage,
925 // the cost of inlining it drops dramatically.
James Molloy67ae1352012-12-20 16:04:27 +0000926 bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
927 &F == CS.getCalledFunction();
928 if (OnlyOneCallAndLocalLinkage)
Bob Wilson28f872f2012-11-19 07:04:35 +0000929 Cost += InlineConstants::LastCallToStaticBonus;
930
931 // If the instruction after the call, or if the normal destination of the
932 // invoke is an unreachable instruction, the function is noreturn. As such,
933 // there is little point in inlining this unless there is literally zero
934 // cost.
935 Instruction *Instr = CS.getInstruction();
936 if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
937 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
938 Threshold = 1;
939 } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
940 Threshold = 1;
941
942 // If this function uses the coldcc calling convention, prefer not to inline
943 // it.
944 if (F.getCallingConv() == CallingConv::Cold)
945 Cost += InlineConstants::ColdccPenalty;
946
947 // Check if we're done. This can happen due to bonuses and penalties.
948 if (Cost > Threshold)
949 return false;
950
Chandler Carruthf2286b02012-03-31 12:42:41 +0000951 if (F.empty())
952 return true;
953
Nadav Rotem92df0262012-09-19 08:08:04 +0000954 Function *Caller = CS.getInstruction()->getParent()->getParent();
955 // Check if the caller function is recursive itself.
956 for (Value::use_iterator U = Caller->use_begin(), E = Caller->use_end();
957 U != E; ++U) {
958 CallSite Site(cast<Value>(*U));
959 if (!Site)
960 continue;
961 Instruction *I = Site.getInstruction();
962 if (I->getParent()->getParent() == Caller) {
963 IsCallerRecursive = true;
964 break;
965 }
966 }
967
Chandler Carruthf2286b02012-03-31 12:42:41 +0000968 // Track whether we've seen a return instruction. The first return
969 // instruction is free, as at least one will usually disappear in inlining.
970 bool HasReturn = false;
971
972 // Populate our simplified values by mapping from function arguments to call
973 // arguments with known important simplifications.
974 CallSite::arg_iterator CAI = CS.arg_begin();
975 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
976 FAI != FAE; ++FAI, ++CAI) {
977 assert(CAI != CS.arg_end());
978 if (Constant *C = dyn_cast<Constant>(CAI))
979 SimplifiedValues[FAI] = C;
980
981 Value *PtrArg = *CAI;
982 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
983 ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
984
985 // We can SROA any pointer arguments derived from alloca instructions.
986 if (isa<AllocaInst>(PtrArg)) {
987 SROAArgValues[FAI] = PtrArg;
988 SROAArgCosts[PtrArg] = 0;
989 }
990 }
991 }
992 NumConstantArgs = SimplifiedValues.size();
993 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
994 NumAllocaArgs = SROAArgValues.size();
995
996 // The worklist of live basic blocks in the callee *after* inlining. We avoid
997 // adding basic blocks of the callee which can be proven to be dead for this
998 // particular call site in order to get more accurate cost estimates. This
999 // requires a somewhat heavyweight iteration pattern: we need to walk the
1000 // basic blocks in a breadth-first order as we insert live successors. To
1001 // accomplish this, prioritizing for small iterations because we exit after
1002 // crossing our threshold, we use a small-size optimized SetVector.
1003 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1004 SmallPtrSet<BasicBlock *, 16> > BBSetVector;
1005 BBSetVector BBWorklist;
1006 BBWorklist.insert(&F.getEntryBlock());
1007 // Note that we *must not* cache the size, this loop grows the worklist.
1008 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1009 // Bail out the moment we cross the threshold. This means we'll under-count
1010 // the cost, but only when undercounting doesn't matter.
Bob Wilson28f872f2012-11-19 07:04:35 +00001011 if (Cost > (Threshold + VectorBonus))
Chandler Carruthf2286b02012-03-31 12:42:41 +00001012 break;
1013
1014 BasicBlock *BB = BBWorklist[Idx];
1015 if (BB->empty())
Chandler Carruth274d3772012-03-14 23:19:53 +00001016 continue;
Dan Gohmane4aeec02009-10-13 18:30:07 +00001017
Chandler Carruthf2286b02012-03-31 12:42:41 +00001018 // Handle the terminator cost here where we can track returns and other
1019 // function-wide constructs.
1020 TerminatorInst *TI = BB->getTerminator();
Kenneth Uildriks74fa7322010-10-09 22:06:36 +00001021
Chandler Carruthf2286b02012-03-31 12:42:41 +00001022 // We never want to inline functions that contain an indirectbr. This is
1023 // incorrect because all the blockaddress's (in static global initializers
Nadav Rotem92df0262012-09-19 08:08:04 +00001024 // for example) would be referring to the original function, and this
1025 // indirect jump would jump from the inlined copy of the function into the
1026 // original function which is extremely undefined behavior.
Chandler Carruthf2286b02012-03-31 12:42:41 +00001027 // FIXME: This logic isn't really right; we can safely inline functions
1028 // with indirectbr's as long as no other function or global references the
1029 // blockaddress of a block within the current function. And as a QOI issue,
1030 // if someone is using a blockaddress without an indirectbr, and that
1031 // reference somehow ends up in another function or global, we probably
1032 // don't want to inline this function.
1033 if (isa<IndirectBrInst>(TI))
1034 return false;
Andrew Trick5c655412011-10-01 01:27:56 +00001035
Chandler Carruthf2286b02012-03-31 12:42:41 +00001036 if (!HasReturn && isa<ReturnInst>(TI))
1037 HasReturn = true;
1038 else
1039 Cost += InlineConstants::InstrCost;
Andrew Trick5c655412011-10-01 01:27:56 +00001040
Chandler Carruthf2286b02012-03-31 12:42:41 +00001041 // Analyze the cost of this block. If we blow through the threshold, this
1042 // returns false, and we can bail on out.
1043 if (!analyzeBlock(BB)) {
Nadav Rotem92df0262012-09-19 08:08:04 +00001044 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
Chandler Carruthf2286b02012-03-31 12:42:41 +00001045 return false;
Nadav Rotem92df0262012-09-19 08:08:04 +00001046
1047 // If the caller is a recursive function then we don't want to inline
1048 // functions which allocate a lot of stack space because it would increase
1049 // the caller stack usage dramatically.
1050 if (IsCallerRecursive &&
1051 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
1052 return false;
1053
Chandler Carruthf2286b02012-03-31 12:42:41 +00001054 break;
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001055 }
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001056
Chandler Carruthf2286b02012-03-31 12:42:41 +00001057 // Add in the live successors by first checking whether we have terminator
1058 // that may be simplified based on the values simplified by this call.
1059 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1060 if (BI->isConditional()) {
1061 Value *Cond = BI->getCondition();
1062 if (ConstantInt *SimpleCond
1063 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1064 BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
1065 continue;
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001066 }
Chandler Carruthf2286b02012-03-31 12:42:41 +00001067 }
1068 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1069 Value *Cond = SI->getCondition();
1070 if (ConstantInt *SimpleCond
1071 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1072 BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
1073 continue;
1074 }
1075 }
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001076
Chandler Carruthf2286b02012-03-31 12:42:41 +00001077 // If we're unable to select a particular successor, just count all of
1078 // them.
Nadav Rotem92df0262012-09-19 08:08:04 +00001079 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1080 ++TIdx)
Chandler Carruthf2286b02012-03-31 12:42:41 +00001081 BBWorklist.insert(TI->getSuccessor(TIdx));
1082
1083 // If we had any successors at this point, than post-inlining is likely to
1084 // have them as well. Note that we assume any basic blocks which existed
1085 // due to branches or switches which folded above will also fold after
1086 // inlining.
1087 if (SingleBB && TI->getNumSuccessors() > 1) {
1088 // Take off the bonus we applied to the threshold.
1089 Threshold -= SingleBBBonus;
1090 SingleBB = false;
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001091 }
1092 }
Andrew Trick5c655412011-10-01 01:27:56 +00001093
James Molloy67ae1352012-12-20 16:04:27 +00001094 // If this is a noduplicate call, we can still inline as long as
1095 // inlining this would cause the removal of the caller (so the instruction
1096 // is not actually duplicated, just moved).
1097 if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
1098 return false;
1099
Chandler Carruthf2286b02012-03-31 12:42:41 +00001100 Threshold += VectorBonus;
1101
Bob Wilson28f872f2012-11-19 07:04:35 +00001102 return Cost < Threshold;
Eric Christopher4e8af6d2011-02-05 00:49:15 +00001103}
1104
Manman Ren286c4dc2012-09-12 05:06:18 +00001105#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthf2286b02012-03-31 12:42:41 +00001106/// \brief Dump stats about this call's analysis.
1107void CallAnalyzer::dump() {
1108#define DEBUG_PRINT_STAT(x) llvm::dbgs() << " " #x ": " << x << "\n"
1109 DEBUG_PRINT_STAT(NumConstantArgs);
1110 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1111 DEBUG_PRINT_STAT(NumAllocaArgs);
1112 DEBUG_PRINT_STAT(NumConstantPtrCmps);
1113 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1114 DEBUG_PRINT_STAT(NumInstructionsSimplified);
1115 DEBUG_PRINT_STAT(SROACostSavings);
1116 DEBUG_PRINT_STAT(SROACostSavingsLost);
James Molloy67ae1352012-12-20 16:04:27 +00001117 DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
Chandler Carruthf2286b02012-03-31 12:42:41 +00001118#undef DEBUG_PRINT_STAT
Eric Christopher4e8af6d2011-02-05 00:49:15 +00001119}
Manman Rencc77eec2012-09-06 19:55:56 +00001120#endif
Eric Christopher4e8af6d2011-02-05 00:49:15 +00001121
Chandler Carruthf2286b02012-03-31 12:42:41 +00001122InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, int Threshold) {
David Chisnallb3815782012-04-06 17:27:41 +00001123 return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1124}
Dan Gohmane4aeec02009-10-13 18:30:07 +00001125
David Chisnallb3815782012-04-06 17:27:41 +00001126InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, Function *Callee,
1127 int Threshold) {
Bob Wilson28f872f2012-11-19 07:04:35 +00001128 // Cannot inline indirect calls.
1129 if (!Callee)
1130 return llvm::InlineCost::getNever();
1131
1132 // Calls to functions with always-inline attributes should be inlined
1133 // whenever possible.
Bill Wendling034b94b2012-12-19 07:18:57 +00001134 if (Callee->getFnAttributes().hasAttribute(Attribute::AlwaysInline)) {
Bob Wilson28f872f2012-11-19 07:04:35 +00001135 if (isInlineViable(*Callee))
1136 return llvm::InlineCost::getAlways();
1137 return llvm::InlineCost::getNever();
1138 }
1139
Dan Gohmane4aeec02009-10-13 18:30:07 +00001140 // Don't inline functions which can be redefined at link-time to mean
Eric Christopherf27e6082010-03-25 04:49:10 +00001141 // something else. Don't inline functions marked noinline or call sites
1142 // marked noinline.
Bob Wilson28f872f2012-11-19 07:04:35 +00001143 if (Callee->mayBeOverridden() ||
Bill Wendling034b94b2012-12-19 07:18:57 +00001144 Callee->getFnAttributes().hasAttribute(Attribute::NoInline) ||
Bill Wendling67658342012-10-09 07:45:08 +00001145 CS.isNoInline())
Dan Gohmane4aeec02009-10-13 18:30:07 +00001146 return llvm::InlineCost::getNever();
1147
Nadav Rotem92df0262012-09-19 08:08:04 +00001148 DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
1149 << "...\n");
Andrew Trick5c655412011-10-01 01:27:56 +00001150
Chandler Carruthf2286b02012-03-31 12:42:41 +00001151 CallAnalyzer CA(TD, *Callee, Threshold);
1152 bool ShouldInline = CA.analyzeCall(CS);
Dan Gohmane4aeec02009-10-13 18:30:07 +00001153
Chandler Carruthf2286b02012-03-31 12:42:41 +00001154 DEBUG(CA.dump());
1155
1156 // Check if there was a reason to force inlining or no inlining.
1157 if (!ShouldInline && CA.getCost() < CA.getThreshold())
Dan Gohmane4aeec02009-10-13 18:30:07 +00001158 return InlineCost::getNever();
Bob Wilson28f872f2012-11-19 07:04:35 +00001159 if (ShouldInline && CA.getCost() >= CA.getThreshold())
Dan Gohmane4aeec02009-10-13 18:30:07 +00001160 return InlineCost::getAlways();
Andrew Trick5c655412011-10-01 01:27:56 +00001161
Chandler Carruthf2286b02012-03-31 12:42:41 +00001162 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
Dan Gohmane4aeec02009-10-13 18:30:07 +00001163}
Bob Wilson28f872f2012-11-19 07:04:35 +00001164
1165bool InlineCostAnalyzer::isInlineViable(Function &F) {
Bill Wendling034b94b2012-12-19 07:18:57 +00001166 bool ReturnsTwice =F.getFnAttributes().hasAttribute(Attribute::ReturnsTwice);
Bob Wilson28f872f2012-11-19 07:04:35 +00001167 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1168 // Disallow inlining of functions which contain an indirect branch.
1169 if (isa<IndirectBrInst>(BI->getTerminator()))
1170 return false;
1171
1172 for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
1173 ++II) {
1174 CallSite CS(II);
1175 if (!CS)
1176 continue;
1177
1178 // Disallow recursive calls.
1179 if (&F == CS.getCalledFunction())
1180 return false;
1181
1182 // Disallow calls which expose returns-twice to a function not previously
1183 // attributed as such.
1184 if (!ReturnsTwice && CS.isCall() &&
1185 cast<CallInst>(CS.getInstruction())->canReturnTwice())
1186 return false;
1187 }
1188 }
1189
1190 return true;
1191}