blob: 17be3b2b4472b7281cf835c5cba31cd61a2cb448 [file] [log] [blame]
Chris Lattner7d30a6c2004-06-20 04:11:48 +00001//===- Inliner.cpp - Code common to all inliners --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerd075cc22003-08-31 19:10:30 +00009//
Chris Lattner6754b822004-05-23 21:22:17 +000010// This file implements the mechanics required to implement inlining without
11// missing any calls and updating the call graph. The decisions of which calls
12// are profitable to inline are implemented elsewhere.
Chris Lattnerd075cc22003-08-31 19:10:30 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner1631bcb2006-12-19 22:09:18 +000016#define DEBUG_TYPE "inline"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/Transforms/IPO/InlinerPass.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/Statistic.h"
Chris Lattnerd075cc22003-08-31 19:10:30 +000020#include "llvm/Analysis/CallGraph.h"
Dan Gohman4552e3c2009-10-13 18:30:07 +000021#include "llvm/Analysis/InlineCost.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000022#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Diego Novilloa9298b22014-04-08 16:42:34 +000024#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Instructions.h"
26#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/Module.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000030#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetLibraryInfo.h"
32#include "llvm/Transforms/Utils/Cloning.h"
33#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera82f1312003-11-21 21:45:31 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Chris Lattner1631bcb2006-12-19 22:09:18 +000036STATISTIC(NumInlined, "Number of functions inlined");
Chris Lattnerb49a6222010-05-01 17:19:38 +000037STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
Chris Lattner1631bcb2006-12-19 22:09:18 +000038STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
Chris Lattnerd3374e82009-08-27 06:29:33 +000039STATISTIC(NumMergedAllocas, "Number of allocas merged together");
Chris Lattner1631bcb2006-12-19 22:09:18 +000040
Benjamin Kramerbde91762012-06-02 10:20:22 +000041// This weirdly named statistic tracks the number of times that, when attempting
Chandler Carruth7ae90d42012-04-11 10:15:10 +000042// to inline a function A into B, we analyze the callers of B in order to see
43// if those would be more profitable and blocked inline steps.
44STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
45
Dan Gohmand78c4002008-05-13 00:00:25 +000046static cl::opt<int>
Jakob Stoklund Olesen113fb542010-02-04 18:48:20 +000047InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
48 cl::desc("Control the amount of inlining to perform (default = 225)"));
Chris Lattnerd075cc22003-08-31 19:10:30 +000049
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +000050static cl::opt<int>
51HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
52 cl::desc("Threshold for inlining functions with inline hint"));
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +000053
Manman Rend4612442014-02-06 01:59:22 +000054// We instroduce this threshold to help performance of instrumentation based
55// PGO before we actually hook up inliner with analysis passes such as BPI and
56// BFI.
Manman Rene8781b12014-02-05 22:53:44 +000057static cl::opt<int>
Manman Rend4612442014-02-06 01:59:22 +000058ColdThreshold("inlinecold-threshold", cl::Hidden, cl::init(225),
Manman Rene8781b12014-02-05 22:53:44 +000059 cl::desc("Threshold for inlining functions with cold attribute"));
60
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +000061// Threshold to use when optsize is specified (and there is no -inline-limit).
62const int OptSizeThreshold = 75;
63
Owen Andersona7aed182010-08-06 18:33:48 +000064Inliner::Inliner(char &ID)
Chad Rosier07d37bc2012-02-25 02:56:01 +000065 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(true) {}
Chris Lattnerd075cc22003-08-31 19:10:30 +000066
Chad Rosier07d37bc2012-02-25 02:56:01 +000067Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
Jakob Stoklund Olesen31a7eb42010-11-02 23:40:26 +000068 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
Chad Rosier07d37bc2012-02-25 02:56:01 +000069 InlineLimit : Threshold),
70 InsertLifetime(InsertLifetime) {}
Chris Lattner22ad7ab2008-01-12 06:49:13 +000071
Chris Lattnerf94bed32007-01-30 23:28:39 +000072/// getAnalysisUsage - For this class, we declare that we require and preserve
73/// the call graph. If the derived class implements this method, it should
74/// always explicitly call the implementation here.
Chandler Carruthe40e60e2012-12-27 11:17:15 +000075void Inliner::getAnalysisUsage(AnalysisUsage &AU) const {
76 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattnerf94bed32007-01-30 23:28:39 +000077}
78
Chris Lattnerd3374e82009-08-27 06:29:33 +000079
Chris Lattner229907c2011-07-18 04:54:35 +000080typedef DenseMap<ArrayType*, std::vector<AllocaInst*> >
Chris Lattnerd3374e82009-08-27 06:29:33 +000081InlinedArrayAllocasTy;
82
Bill Wendlingd154e2832013-01-23 06:41:41 +000083/// \brief If the inlined function had a higher stack protection level than the
84/// calling function, then bump up the caller's stack protection level.
85static void AdjustCallerSSPLevel(Function *Caller, Function *Callee) {
86 // If upgrading the SSP attribute, clear out the old SSP Attributes first.
87 // Having multiple SSP attributes doesn't actually hurt, but it adds useless
88 // clutter to the IR.
89 AttrBuilder B;
90 B.addAttribute(Attribute::StackProtect)
91 .addAttribute(Attribute::StackProtectStrong);
92 AttributeSet OldSSPAttr = AttributeSet::get(Caller->getContext(),
93 AttributeSet::FunctionIndex,
94 B);
95 AttributeSet CallerAttr = Caller->getAttributes(),
96 CalleeAttr = Callee->getAttributes();
97
98 if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
99 Attribute::StackProtectReq)) {
100 Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
101 Caller->addFnAttr(Attribute::StackProtectReq);
102 } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
103 Attribute::StackProtectStrong) &&
104 !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
105 Attribute::StackProtectReq)) {
106 Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
107 Caller->addFnAttr(Attribute::StackProtectStrong);
108 } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
109 Attribute::StackProtect) &&
110 !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
111 Attribute::StackProtectReq) &&
112 !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
113 Attribute::StackProtectStrong))
114 Caller->addFnAttr(Attribute::StackProtect);
115}
116
Chris Lattnerd3374e82009-08-27 06:29:33 +0000117/// InlineCallIfPossible - If it is possible to inline the specified call site,
118/// do so and update the CallGraph for this operation.
119///
120/// This function also does some basic book-keeping to update the IR. The
Chris Lattner0e890182009-08-28 04:48:54 +0000121/// InlinedArrayAllocas map keeps track of any allocas that are already
122/// available from other functions inlined into the caller. If we are able to
123/// inline this call site we attempt to reuse already available allocas or add
124/// any new allocas to the set if not possible.
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000125static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
Chris Lattnerfb212de2010-12-06 07:52:42 +0000126 InlinedArrayAllocasTy &InlinedArrayAllocas,
Hal Finkel9caa8f72013-07-16 17:10:55 +0000127 int InlineHistory, bool InsertLifetime,
Rafael Espindola612886f2014-02-21 01:53:35 +0000128 const DataLayout *DL) {
Chris Lattner6754b822004-05-23 21:22:17 +0000129 Function *Callee = CS.getCalledFunction();
Bill Wendlingf5260d22008-11-21 00:09:21 +0000130 Function *Caller = CS.getCaller();
131
Chris Lattnerd3374e82009-08-27 06:29:33 +0000132 // Try to inline the function. Get the list of static allocas that were
133 // inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +0000134 if (!InlineFunction(CS, IFI, InsertLifetime))
Chris Lattnerb9d0a962009-08-27 04:32:07 +0000135 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000136
Bill Wendlingd154e2832013-01-23 06:41:41 +0000137 AdjustCallerSSPLevel(Caller, Callee);
Bill Wendling26c6a3e2008-11-21 00:06:32 +0000138
Chris Lattnerd3374e82009-08-27 06:29:33 +0000139 // Look at all of the allocas that we inlined through this call site. If we
140 // have already inlined other allocas through other calls into this function,
141 // then we know that they have disjoint lifetimes and that we can merge them.
142 //
143 // There are many heuristics possible for merging these allocas, and the
144 // different options have different tradeoffs. One thing that we *really*
145 // don't want to hurt is SRoA: once inlining happens, often allocas are no
146 // longer address taken and so they can be promoted.
147 //
148 // Our "solution" for that is to only merge allocas whose outermost type is an
149 // array type. These are usually not promoted because someone is using a
150 // variable index into them. These are also often the most important ones to
151 // merge.
152 //
153 // A better solution would be to have real memory lifetime markers in the IR
154 // and not have the inliner do any merging of allocas at all. This would
155 // allow the backend to do proper stack slot coloring of all allocas that
156 // *actually make it to the backend*, which is really what we want.
157 //
158 // Because we don't have this information, we do this simple and useful hack.
159 //
160 SmallPtrSet<AllocaInst*, 16> UsedAllocas;
161
Chris Lattnerfb212de2010-12-06 07:52:42 +0000162 // When processing our SCC, check to see if CS was inlined from some other
163 // call site. For example, if we're processing "A" in this code:
164 // A() { B() }
165 // B() { x = alloca ... C() }
166 // C() { y = alloca ... }
167 // Assume that C was not inlined into B initially, and so we're processing A
168 // and decide to inline B into A. Doing this makes an alloca available for
169 // reuse and makes a callsite (C) available for inlining. When we process
170 // the C call site we don't want to do any alloca merging between X and Y
171 // because their scopes are not disjoint. We could make this smarter by
172 // keeping track of the inline history for each alloca in the
173 // InlinedArrayAllocas but this isn't likely to be a significant win.
174 if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
175 return true;
176
Chris Lattnerd3374e82009-08-27 06:29:33 +0000177 // Loop over all the allocas we have so far and see if they can be merged with
178 // a previously inlined alloca. If not, remember that we had it.
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000179 for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
Chris Lattnerd3374e82009-08-27 06:29:33 +0000180 AllocaNo != e; ++AllocaNo) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000181 AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
Chris Lattnerd3374e82009-08-27 06:29:33 +0000182
183 // Don't bother trying to merge array allocations (they will usually be
184 // canonicalized to be an allocation *of* an array), or allocations whose
185 // type is not itself an array (because we're afraid of pessimizing SRoA).
Chris Lattner229907c2011-07-18 04:54:35 +0000186 ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
Chris Lattnerd3374e82009-08-27 06:29:33 +0000187 if (ATy == 0 || AI->isArrayAllocation())
188 continue;
189
190 // Get the list of all available allocas for this array type.
191 std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
192
193 // Loop over the allocas in AllocasForType to see if we can reuse one. Note
194 // that we have to be careful not to reuse the same "available" alloca for
195 // multiple different allocas that we just inlined, we use the 'UsedAllocas'
196 // set to keep track of which "available" allocas are being used by this
197 // function. Also, AllocasForType can be empty of course!
198 bool MergedAwayAlloca = false;
199 for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
200 AllocaInst *AvailableAlloca = AllocasForType[i];
Hal Finkel9caa8f72013-07-16 17:10:55 +0000201
202 unsigned Align1 = AI->getAlignment(),
203 Align2 = AvailableAlloca->getAlignment();
204 // If we don't have data layout information, and only one alloca is using
205 // the target default, then we can't safely merge them because we can't
206 // pick the greater alignment.
Rafael Espindola612886f2014-02-21 01:53:35 +0000207 if (!DL && (!Align1 || !Align2) && Align1 != Align2)
Hal Finkel9caa8f72013-07-16 17:10:55 +0000208 continue;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000209
210 // The available alloca has to be in the right function, not in some other
211 // function in this SCC.
212 if (AvailableAlloca->getParent() != AI->getParent())
213 continue;
214
215 // If the inlined function already uses this alloca then we can't reuse
216 // it.
217 if (!UsedAllocas.insert(AvailableAlloca))
218 continue;
219
220 // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
221 // success!
Chris Lattner5b6a8652010-12-06 07:38:40 +0000222 DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
223 << *AvailableAlloca << '\n');
Chris Lattnerd3374e82009-08-27 06:29:33 +0000224
225 AI->replaceAllUsesWith(AvailableAlloca);
Hal Finkel9caa8f72013-07-16 17:10:55 +0000226
Hal Finkelec7cd262013-07-17 14:32:41 +0000227 if (Align1 != Align2) {
228 if (!Align1 || !Align2) {
Rafael Espindola612886f2014-02-21 01:53:35 +0000229 assert(DL && "DataLayout required to compare default alignments");
230 unsigned TypeAlign = DL->getABITypeAlignment(AI->getAllocatedType());
Hal Finkelec7cd262013-07-17 14:32:41 +0000231
232 Align1 = Align1 ? Align1 : TypeAlign;
233 Align2 = Align2 ? Align2 : TypeAlign;
234 }
235
236 if (Align1 > Align2)
237 AvailableAlloca->setAlignment(AI->getAlignment());
238 }
Hal Finkel9caa8f72013-07-16 17:10:55 +0000239
Chris Lattnerd3374e82009-08-27 06:29:33 +0000240 AI->eraseFromParent();
241 MergedAwayAlloca = true;
242 ++NumMergedAllocas;
Chris Lattner5b6a8652010-12-06 07:38:40 +0000243 IFI.StaticAllocas[AllocaNo] = 0;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000244 break;
245 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000246
Chris Lattnerd3374e82009-08-27 06:29:33 +0000247 // If we already nuked the alloca, we're done with it.
248 if (MergedAwayAlloca)
249 continue;
Chris Lattner5b6a8652010-12-06 07:38:40 +0000250
Chris Lattnerd3374e82009-08-27 06:29:33 +0000251 // If we were unable to merge away the alloca either because there are no
252 // allocas of the right type available or because we reused them all
253 // already, remember that this alloca came from an inlined function and mark
254 // it used so we don't reuse it for other allocas from this inline
255 // operation.
256 AllocasForType.push_back(AI);
257 UsedAllocas.insert(AI);
Chris Lattner6754b822004-05-23 21:22:17 +0000258 }
Chris Lattnerd3374e82009-08-27 06:29:33 +0000259
Chris Lattner6754b822004-05-23 21:22:17 +0000260 return true;
Chris Lattnerd075cc22003-08-31 19:10:30 +0000261}
Jakob Stoklund Olesen8a19d3c2010-01-20 17:51:28 +0000262
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000263unsigned Inliner::getInlineThreshold(CallSite CS) const {
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000264 int thres = InlineThreshold; // -inline-threshold or else selected by
265 // overall opt level
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000266
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000267 // If -inline-threshold is not given, listen to the optsize attribute when it
268 // would decrease the threshold.
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000269 Function *Caller = CS.getCaller();
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000270 bool OptSize = Caller && !Caller->isDeclaration() &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000271 Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
272 Attribute::OptimizeForSize);
Nadav Rotem97d44342012-09-13 16:27:32 +0000273 if (!(InlineLimit.getNumOccurrences() > 0) && OptSize &&
274 OptSizeThreshold < thres)
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000275 thres = OptSizeThreshold;
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000276
Quentin Colombetc0dba202012-12-13 01:05:25 +0000277 // Listen to the inlinehint attribute when it would increase the threshold
278 // and the caller does not need to minimize its size.
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000279 Function *Callee = CS.getCalledFunction();
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000280 bool InlineHint = Callee && !Callee->isDeclaration() &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000281 Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
282 Attribute::InlineHint);
Quentin Colombetc0dba202012-12-13 01:05:25 +0000283 if (InlineHint && HintThreshold > thres
Bill Wendling698e84f2012-12-30 10:32:01 +0000284 && !Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
285 Attribute::MinSize))
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000286 thres = HintThreshold;
287
Manman Rene8781b12014-02-05 22:53:44 +0000288 // Listen to the cold attribute when it would decrease the threshold.
289 bool ColdCallee = Callee && !Callee->isDeclaration() &&
290 Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
291 Attribute::Cold);
292 if (ColdCallee && ColdThreshold < thres)
293 thres = ColdThreshold;
294
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000295 return thres;
Jakob Stoklund Olesen8a19d3c2010-01-20 17:51:28 +0000296}
297
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000298/// shouldInline - Return true if the inliner should attempt to inline
299/// at the given CallSite.
300bool Inliner::shouldInline(CallSite CS) {
Daniel Dunbar3933e662008-10-30 19:26:59 +0000301 InlineCost IC = getInlineCost(CS);
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000302
Daniel Dunbar3933e662008-10-30 19:26:59 +0000303 if (IC.isAlways()) {
David Greene0122fc42010-01-05 01:27:51 +0000304 DEBUG(dbgs() << " Inlining: cost=always"
Bill Wendling2602bb42009-07-31 19:52:24 +0000305 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbar3933e662008-10-30 19:26:59 +0000306 return true;
307 }
308
309 if (IC.isNever()) {
David Greene0122fc42010-01-05 01:27:51 +0000310 DEBUG(dbgs() << " NOT Inlining: cost=never"
Bill Wendling2602bb42009-07-31 19:52:24 +0000311 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbar3933e662008-10-30 19:26:59 +0000312 return false;
313 }
314
Dale Johannesen30599242009-10-09 00:11:32 +0000315 Function *Caller = CS.getCaller();
Chandler Carruth0539c072012-03-31 12:42:41 +0000316 if (!IC) {
317 DEBUG(dbgs() << " NOT Inlining: cost=" << IC.getCost()
318 << ", thres=" << (IC.getCostDelta() + IC.getCost())
Bill Wendling2602bb42009-07-31 19:52:24 +0000319 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000320 return false;
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000321 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000322
Chandler Carruth30b84162012-03-14 20:16:41 +0000323 // Try to detect the case where the current inlining candidate caller (call
324 // it B) is a static or linkonce-ODR function and is an inlining candidate
325 // elsewhere, and the current candidate callee (call it C) is large enough
326 // that inlining it into B would make B too big to inline later. In these
327 // circumstances it may be best not to inline C into B, but to inline B into
328 // its callers.
329 //
330 // This only applies to static and linkonce-ODR functions because those are
331 // expected to be available for inlining in the translation units where they
332 // are used. Thus we will always have the opportunity to make local inlining
333 // decisions. Importantly the linkonce-ODR linkage covers inline functions
334 // and templates in C++.
Chandler Carruth0539c072012-03-31 12:42:41 +0000335 //
336 // FIXME: All of this logic should be sunk into getInlineCost. It relies on
337 // the internal implementation of the inline cost metrics rather than
338 // treating them as truly abstract units etc.
Chandler Carruth30b84162012-03-14 20:16:41 +0000339 if (Caller->hasLocalLinkage() ||
340 Caller->getLinkage() == GlobalValue::LinkOnceODRLinkage) {
Dale Johannesen30599242009-10-09 00:11:32 +0000341 int TotalSecondaryCost = 0;
Chandler Carruth0539c072012-03-31 12:42:41 +0000342 // The candidate cost to be imposed upon the current function.
343 int CandidateCost = IC.getCost() - (InlineConstants::CallPenalty + 1);
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000344 // This bool tracks what happens if we do NOT inline C into B.
Chandler Carruthb9e35fb2012-03-27 10:48:28 +0000345 bool callerWillBeRemoved = Caller->hasLocalLinkage();
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000346 // This bool tracks what happens if we DO inline C into B.
347 bool inliningPreventsSomeOuterInline = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000348 for (User *U : Caller->users()) {
349 CallSite CS2(U);
Dale Johannesen30599242009-10-09 00:11:32 +0000350
351 // If this isn't a call to Caller (it could be some other sort
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000352 // of reference) skip it. Such references will prevent the caller
353 // from being removed.
354 if (!CS2 || CS2.getCalledFunction() != Caller) {
355 callerWillBeRemoved = false;
Dale Johannesen30599242009-10-09 00:11:32 +0000356 continue;
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000357 }
Dale Johannesen30599242009-10-09 00:11:32 +0000358
359 InlineCost IC2 = getInlineCost(CS2);
Chandler Carruth7ae90d42012-04-11 10:15:10 +0000360 ++NumCallerCallersAnalyzed;
Chandler Carruth0539c072012-03-31 12:42:41 +0000361 if (!IC2) {
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000362 callerWillBeRemoved = false;
Chandler Carruth0539c072012-03-31 12:42:41 +0000363 continue;
364 }
365 if (IC2.isAlways())
Dale Johannesen30599242009-10-09 00:11:32 +0000366 continue;
367
Chandler Carruth0539c072012-03-31 12:42:41 +0000368 // See if inlining or original callsite would erase the cost delta of
369 // this callsite. We subtract off the penalty for the call instruction,
370 // which we would be deleting.
371 if (IC2.getCostDelta() <= CandidateCost) {
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000372 inliningPreventsSomeOuterInline = true;
Chandler Carruth0539c072012-03-31 12:42:41 +0000373 TotalSecondaryCost += IC2.getCost();
Dale Johannesen30599242009-10-09 00:11:32 +0000374 }
375 }
376 // If all outer calls to Caller would get inlined, the cost for the last
377 // one is set very low by getInlineCost, in anticipation that Caller will
378 // be removed entirely. We did not account for this above unless there
379 // is only one caller of Caller.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000380 if (callerWillBeRemoved && !Caller->use_empty())
Dale Johannesen96a5b872009-10-09 21:42:02 +0000381 TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
Dale Johannesen30599242009-10-09 00:11:32 +0000382
Chandler Carruth0539c072012-03-31 12:42:41 +0000383 if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) {
384 DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction() <<
385 " Cost = " << IC.getCost() <<
Dale Johannesen30599242009-10-09 00:11:32 +0000386 ", outer Cost = " << TotalSecondaryCost << '\n');
387 return false;
388 }
389 }
390
Chandler Carruth0539c072012-03-31 12:42:41 +0000391 DEBUG(dbgs() << " Inlining: cost=" << IC.getCost()
392 << ", thres=" << (IC.getCostDelta() + IC.getCost())
Dale Johannesen30599242009-10-09 00:11:32 +0000393 << ", Call: " << *CS.getInstruction() << '\n');
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000394 return true;
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000395}
Chris Lattnerd075cc22003-08-31 19:10:30 +0000396
Chris Lattnere8262672010-05-01 01:05:10 +0000397/// InlineHistoryIncludes - Return true if the specified inline history ID
398/// indicates an inline history that includes the specified function.
399static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
400 const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
401 while (InlineHistoryID != -1) {
402 assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
403 "Invalid inline history ID");
404 if (InlineHistory[InlineHistoryID].first == F)
405 return true;
406 InlineHistoryID = InlineHistory[InlineHistoryID].second;
407 }
408 return false;
409}
410
Chris Lattner4422d312010-04-16 22:42:17 +0000411bool Inliner::runOnSCC(CallGraphSCC &SCC) {
Chandler Carruth6378cf52013-11-26 04:19:30 +0000412 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
Rafael Espindola93512512014-02-25 17:30:31 +0000413 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
414 const DataLayout *DL = DLP ? &DLP->getDataLayout() : 0;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000415 const TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
Chris Lattnerd075cc22003-08-31 19:10:30 +0000416
Dale Johannesen32dfb352009-03-23 23:39:20 +0000417 SmallPtrSet<Function*, 8> SCCFunctions;
David Greene0122fc42010-01-05 01:27:51 +0000418 DEBUG(dbgs() << "Inliner visiting SCC:");
Chris Lattner4422d312010-04-16 22:42:17 +0000419 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
420 Function *F = (*I)->getFunction();
Chris Lattner6754b822004-05-23 21:22:17 +0000421 if (F) SCCFunctions.insert(F);
David Greene0122fc42010-01-05 01:27:51 +0000422 DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
Chris Lattnerd075cc22003-08-31 19:10:30 +0000423 }
Chris Lattnerd075cc22003-08-31 19:10:30 +0000424
Chris Lattner6754b822004-05-23 21:22:17 +0000425 // Scan through and identify all call sites ahead of time so that we only
426 // inline call sites in the original functions, not call sites that result
427 // from inlining other functions.
Chris Lattnere8262672010-05-01 01:05:10 +0000428 SmallVector<std::pair<CallSite, int>, 16> CallSites;
429
430 // When inlining a callee produces new call sites, we want to keep track of
431 // the fact that they were inlined from the callee. This allows us to avoid
432 // infinite inlining in some obscure cases. To represent this, we use an
433 // index into the InlineHistory vector.
434 SmallVector<std::pair<Function*, int>, 8> InlineHistory;
Chris Lattner6754b822004-05-23 21:22:17 +0000435
Chris Lattner4422d312010-04-16 22:42:17 +0000436 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
437 Function *F = (*I)->getFunction();
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000438 if (!F) continue;
439
440 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
441 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000442 CallSite CS(cast<Value>(I));
Dale Johannesen30599242009-10-09 00:11:32 +0000443 // If this isn't a call, or it is a call to an intrinsic, it can
Chris Lattner9e507472009-08-31 05:34:32 +0000444 // never be inlined.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000445 if (!CS || isa<IntrinsicInst>(I))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000446 continue;
447
Chris Lattner9e507472009-08-31 05:34:32 +0000448 // If this is a direct call to an external function, we can never inline
449 // it. If it is an indirect call, inlining may resolve it to be a
450 // direct call, so we keep it.
451 if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
452 continue;
453
Chris Lattnere8262672010-05-01 01:05:10 +0000454 CallSites.push_back(std::make_pair(CS, -1));
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000455 }
456 }
Chris Lattnerd075cc22003-08-31 19:10:30 +0000457
David Greene0122fc42010-01-05 01:27:51 +0000458 DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000459
Chris Lattnera5cdd5e2010-04-20 00:47:08 +0000460 // If there are no calls in this function, exit early.
461 if (CallSites.empty())
462 return false;
463
Chris Lattner6754b822004-05-23 21:22:17 +0000464 // Now that we have all of the call sites, move the ones to functions in the
465 // current SCC to the end of the list.
466 unsigned FirstCallInSCC = CallSites.size();
467 for (unsigned i = 0; i < FirstCallInSCC; ++i)
Chris Lattnere8262672010-05-01 01:05:10 +0000468 if (Function *F = CallSites[i].first.getCalledFunction())
Chris Lattner6754b822004-05-23 21:22:17 +0000469 if (SCCFunctions.count(F))
470 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000471
Chris Lattnerd3374e82009-08-27 06:29:33 +0000472
473 InlinedArrayAllocasTy InlinedArrayAllocas;
Rafael Espindola612886f2014-02-21 01:53:35 +0000474 InlineFunctionInfo InlineInfo(&CG, DL);
Chris Lattnerd3374e82009-08-27 06:29:33 +0000475
Chris Lattner6754b822004-05-23 21:22:17 +0000476 // Now that we have all of the call sites, loop over them and inline them if
477 // it looks profitable to do so.
478 bool Changed = false;
479 bool LocalChange;
480 do {
481 LocalChange = false;
482 // Iterate over the outer loop because inlining functions can cause indirect
483 // calls to become direct calls.
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000484 for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
Chris Lattnere8262672010-05-01 01:05:10 +0000485 CallSite CS = CallSites[CSi].first;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000486
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000487 Function *Caller = CS.getCaller();
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000488 Function *Callee = CS.getCalledFunction();
489
490 // If this call site is dead and it is to a readonly function, we should
491 // just delete the call instead of trying to inline it, regardless of
492 // size. This happens because IPSCCP propagates the result out of the
493 // call and then we're left with the dead call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000494 if (isInstructionTriviallyDead(CS.getInstruction(), TLI)) {
David Greene0122fc42010-01-05 01:27:51 +0000495 DEBUG(dbgs() << " -> Deleting dead call: "
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000496 << *CS.getInstruction() << "\n");
497 // Update the call graph by deleting the edge from Callee to Caller.
498 CG[Caller]->removeCallEdgeFor(CS);
499 CS.getInstruction()->eraseFromParent();
500 ++NumCallsDeleted;
501 } else {
502 // We can only inline direct calls to non-declarations.
503 if (Callee == 0 || Callee->isDeclaration()) continue;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000504
Eric Christopherea2820342010-07-13 18:27:13 +0000505 // If this call site was obtained by inlining another function, verify
Chris Lattnere8262672010-05-01 01:05:10 +0000506 // that the include path for the function did not include the callee
Chris Lattner5b6a8652010-12-06 07:38:40 +0000507 // itself. If so, we'd be recursively inlining the same function,
Chris Lattnere8262672010-05-01 01:05:10 +0000508 // which would provide the same callsites, which would cause us to
509 // infinitely inline.
510 int InlineHistoryID = CallSites[CSi].second;
511 if (InlineHistoryID != -1 &&
512 InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
513 continue;
514
515
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000516 // If the policy determines that we should inline this function,
517 // try to do so.
518 if (!shouldInline(CS))
519 continue;
520
Chris Lattner2eee5d32010-04-22 23:37:35 +0000521 // Attempt to inline the function.
Chris Lattnerfb212de2010-12-06 07:52:42 +0000522 if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
Rafael Espindola612886f2014-02-21 01:53:35 +0000523 InlineHistoryID, InsertLifetime, DL))
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000524 continue;
525 ++NumInlined;
Diego Novilloa9298b22014-04-08 16:42:34 +0000526
527 // Report the inline decision.
528 Caller->getContext().emitOptimizationRemark(
529 DEBUG_TYPE, *Caller, CS.getInstruction()->getDebugLoc(),
530 Twine(Callee->getName() + " inlined into " + Caller->getName()));
531
Chris Lattnerc2432b92010-05-01 01:26:13 +0000532 // If inlining this function gave us any new call sites, throw them
Chris Lattner2eee5d32010-04-22 23:37:35 +0000533 // onto our worklist to process. They are useful inline candidates.
Chris Lattnerc2432b92010-05-01 01:26:13 +0000534 if (!InlineInfo.InlinedCalls.empty()) {
Chris Lattnere8262672010-05-01 01:05:10 +0000535 // Create a new inline history entry for this, so that we remember
536 // that these new callsites came about due to inlining Callee.
537 int NewHistoryID = InlineHistory.size();
538 InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
539
Chris Lattnerc2432b92010-05-01 01:26:13 +0000540 for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
Chris Lattnere8262672010-05-01 01:05:10 +0000541 i != e; ++i) {
Chris Lattnerc2432b92010-05-01 01:26:13 +0000542 Value *Ptr = InlineInfo.InlinedCalls[i];
Chandler Carruth21211992012-03-25 04:03:40 +0000543 CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
Chris Lattnere8262672010-05-01 01:05:10 +0000544 }
Chris Lattnerc691de32010-04-23 18:37:01 +0000545 }
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000546 }
547
548 // If we inlined or deleted the last possible call site to the function,
549 // delete the function body now.
550 if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
Chris Lattner9e507472009-08-31 05:34:32 +0000551 // TODO: Can remove if in SCC now.
Chris Lattner081375b2009-08-31 03:15:49 +0000552 !SCCFunctions.count(Callee) &&
Chris Lattner9e507472009-08-31 05:34:32 +0000553
Chris Lattner081375b2009-08-31 03:15:49 +0000554 // The function may be apparently dead, but if there are indirect
555 // callgraph references to the node, we cannot delete it yet, this
556 // could invalidate the CGSCC iterator.
557 CG[Callee]->getNumReferences() == 0) {
David Greene0122fc42010-01-05 01:27:51 +0000558 DEBUG(dbgs() << " -> Deleting dead function: "
Chris Lattnerd3374e82009-08-27 06:29:33 +0000559 << Callee->getName() << "\n");
560 CallGraphNode *CalleeNode = CG[Callee];
561
562 // Remove any call graph edges from the callee to its callees.
563 CalleeNode->removeAllCalledFunctions();
564
Chris Lattnerd3374e82009-08-27 06:29:33 +0000565 // Removing the node for callee from the call graph and delete it.
566 delete CG.removeFunctionFromModule(CalleeNode);
567 ++NumDeleted;
568 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000569
570 // Remove this call site from the list. If possible, use
571 // swap/pop_back for efficiency, but do not use it if doing so would
572 // move a call site to a function in this SCC before the
573 // 'FirstCallInSCC' barrier.
Chris Lattner4422d312010-04-16 22:42:17 +0000574 if (SCC.isSingular()) {
Benjamin Kramer5ac57e32010-05-31 12:50:41 +0000575 CallSites[CSi] = CallSites.back();
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000576 CallSites.pop_back();
577 } else {
578 CallSites.erase(CallSites.begin()+CSi);
579 }
580 --CSi;
581
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000582 Changed = true;
583 LocalChange = true;
584 }
Chris Lattner6754b822004-05-23 21:22:17 +0000585 } while (LocalChange);
Chris Lattner4d25c862004-04-08 06:34:31 +0000586
Chris Lattnerd075cc22003-08-31 19:10:30 +0000587 return Changed;
588}
589
Chris Lattnerc87784f2004-04-20 22:06:53 +0000590// doFinalization - Remove now-dead linkonce functions at the end of
591// processing to avoid breaking the SCC traversal.
592bool Inliner::doFinalization(CallGraph &CG) {
Devang Patelf0ef3572008-11-05 01:39:16 +0000593 return removeDeadFunctions(CG);
594}
595
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000596/// removeDeadFunctions - Remove dead functions that are not included in
597/// DNR (Do Not Remove) list.
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000598bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
599 SmallVector<CallGraphNode*, 16> FunctionsToRemove;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000600
601 // Scan for all of the functions, looking for ones that should now be removed
602 // from the program. Insert the dead ones in the FunctionsToRemove set.
603 for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
604 CallGraphNode *CGN = I->second;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000605 Function *F = CGN->getFunction();
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000606 if (!F || F->isDeclaration())
607 continue;
608
609 // Handle the case when this function is called and we only want to care
610 // about always-inline functions. This is a bit of a hack to share code
611 // between here and the InlineAlways pass.
Bill Wendlingc9b22d72012-10-09 07:45:08 +0000612 if (AlwaysInlineOnly &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000613 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
614 Attribute::AlwaysInline))
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000615 continue;
616
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000617 // If the only remaining users of the function are dead constants, remove
618 // them.
619 F->removeDeadConstantUsers();
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000620
Eli Friedman1923a332011-10-20 05:23:42 +0000621 if (!F->isDefTriviallyDead())
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000622 continue;
623
624 // Remove any call graph edges from the function to its callees.
625 CGN->removeAllCalledFunctions();
Devang Patelf0ef3572008-11-05 01:39:16 +0000626
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000627 // Remove any edges from the external node to the function's call graph
628 // node. These edges might have been made irrelegant due to
629 // optimization of the program.
630 CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
Chris Lattner6455c512004-09-18 21:37:03 +0000631
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000632 // Removing the node for callee from the call graph and delete it.
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000633 FunctionsToRemove.push_back(CGN);
Chris Lattnerc87784f2004-04-20 22:06:53 +0000634 }
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000635 if (FunctionsToRemove.empty())
636 return false;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000637
638 // Now that we know which functions to delete, do so. We didn't want to do
639 // this inline, because that would invalidate our CallGraph::iterator
640 // objects. :(
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000641 //
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000642 // Note that it doesn't matter that we are iterating over a non-stable order
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000643 // here to do this, it doesn't matter which order the functions are deleted
644 // in.
Chandler Carruth45ae88f2012-04-01 10:41:24 +0000645 array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000646 FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
647 FunctionsToRemove.end()),
648 FunctionsToRemove.end());
649 for (SmallVectorImpl<CallGraphNode *>::iterator I = FunctionsToRemove.begin(),
650 E = FunctionsToRemove.end();
651 I != E; ++I) {
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000652 delete CG.removeFunctionFromModule(*I);
653 ++NumDeleted;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000654 }
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000655 return true;
Chris Lattnerc87784f2004-04-20 22:06:53 +0000656}