blob: 9975333976ded7fc43afc15dc67a36eb10a91f6c [file] [log] [blame]
Chris Lattnercf5933a2004-06-20 04:11:48 +00001//===- Inliner.cpp - Code common to all inliners --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner237ef562003-08-31 19:10:30 +00009//
Chris Lattnerbefa4992004-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 Lattner237ef562003-08-31 19:10:30 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner86453c52006-12-19 22:09:18 +000016#define DEBUG_TYPE "inline"
Chris Lattner237ef562003-08-31 19:10:30 +000017#include "llvm/Module.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Dale Johannesen1f67ce42009-03-19 18:03:56 +000019#include "llvm/IntrinsicInst.h"
Chris Lattner237ef562003-08-31 19:10:30 +000020#include "llvm/Analysis/CallGraph.h"
Dan Gohmane4aeec02009-10-13 18:30:07 +000021#include "llvm/Analysis/InlineCost.h"
Chandler Carruth6c0b3ac2012-03-12 11:19:33 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerff2dad32007-01-30 23:28:39 +000023#include "llvm/Target/TargetData.h"
Tanya Lattner6f7426e2007-06-19 22:29:50 +000024#include "llvm/Transforms/IPO/InlinerPass.h"
Chris Lattner237ef562003-08-31 19:10:30 +000025#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner4ff41412009-11-12 21:58:18 +000026#include "llvm/Transforms/Utils/Local.h"
27#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner12f0bab2009-08-27 04:32:07 +000031#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/ADT/Statistic.h"
Chris Lattnera51bcb52003-11-21 21:45:31 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattner86453c52006-12-19 22:09:18 +000035STATISTIC(NumInlined, "Number of functions inlined");
Chris Lattner83f66fe2010-05-01 17:19:38 +000036STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
Chris Lattner86453c52006-12-19 22:09:18 +000037STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
Chris Lattner199ba422009-08-27 06:29:33 +000038STATISTIC(NumMergedAllocas, "Number of allocas merged together");
Chris Lattner86453c52006-12-19 22:09:18 +000039
Dan Gohman844731a2008-05-13 00:00:25 +000040static cl::opt<int>
Jakob Stoklund Olesenf9c3b222010-02-04 18:48:20 +000041InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
42 cl::desc("Control the amount of inlining to perform (default = 225)"));
Chris Lattner237ef562003-08-31 19:10:30 +000043
Jakob Stoklund Olesenf0907fe2010-02-13 01:51:53 +000044static cl::opt<int>
45HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
46 cl::desc("Threshold for inlining functions with inline hint"));
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +000047
48// Threshold to use when optsize is specified (and there is no -inline-limit).
49const int OptSizeThreshold = 75;
50
Owen Anderson90c579d2010-08-06 18:33:48 +000051Inliner::Inliner(char &ID)
Chad Rosierfa086f12012-02-25 02:56:01 +000052 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(true) {}
Chris Lattner237ef562003-08-31 19:10:30 +000053
Chad Rosierfa086f12012-02-25 02:56:01 +000054Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
Jakob Stoklund Olesen930f5ef2010-11-02 23:40:26 +000055 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
Chad Rosierfa086f12012-02-25 02:56:01 +000056 InlineLimit : Threshold),
57 InsertLifetime(InsertLifetime) {}
Chris Lattner120d0532008-01-12 06:49:13 +000058
Chris Lattnerff2dad32007-01-30 23:28:39 +000059/// getAnalysisUsage - For this class, we declare that we require and preserve
60/// the call graph. If the derived class implements this method, it should
61/// always explicitly call the implementation here.
62void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
Chris Lattnerff2dad32007-01-30 23:28:39 +000063 CallGraphSCCPass::getAnalysisUsage(Info);
64}
65
Chris Lattner199ba422009-08-27 06:29:33 +000066
Chris Lattnerdb125cf2011-07-18 04:54:35 +000067typedef DenseMap<ArrayType*, std::vector<AllocaInst*> >
Chris Lattner199ba422009-08-27 06:29:33 +000068InlinedArrayAllocasTy;
69
70/// InlineCallIfPossible - If it is possible to inline the specified call site,
71/// do so and update the CallGraph for this operation.
72///
73/// This function also does some basic book-keeping to update the IR. The
Chris Lattnercc0a0292009-08-28 04:48:54 +000074/// InlinedArrayAllocas map keeps track of any allocas that are already
75/// available from other functions inlined into the caller. If we are able to
76/// inline this call site we attempt to reuse already available allocas or add
77/// any new allocas to the set if not possible.
Chris Lattner60915142010-04-22 23:07:58 +000078static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
Chris Lattner6c3ee0f2010-12-06 07:52:42 +000079 InlinedArrayAllocasTy &InlinedArrayAllocas,
Chad Rosierfa086f12012-02-25 02:56:01 +000080 int InlineHistory, bool InsertLifetime) {
Chris Lattnerbefa4992004-05-23 21:22:17 +000081 Function *Callee = CS.getCalledFunction();
Bill Wendling66c75aa2008-11-21 00:09:21 +000082 Function *Caller = CS.getCaller();
83
Chris Lattner199ba422009-08-27 06:29:33 +000084 // Try to inline the function. Get the list of static allocas that were
85 // inlined.
Chad Rosierfa086f12012-02-25 02:56:01 +000086 if (!InlineFunction(CS, IFI, InsertLifetime))
Chris Lattner12f0bab2009-08-27 04:32:07 +000087 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000088
Bill Wendling8c1604e2008-11-21 00:06:32 +000089 // If the inlined function had a higher stack protection level than the
90 // calling function, then bump up the caller's stack protection level.
Bill Wendling8c1604e2008-11-21 00:06:32 +000091 if (Callee->hasFnAttr(Attribute::StackProtectReq))
92 Caller->addFnAttr(Attribute::StackProtectReq);
93 else if (Callee->hasFnAttr(Attribute::StackProtect) &&
94 !Caller->hasFnAttr(Attribute::StackProtectReq))
95 Caller->addFnAttr(Attribute::StackProtect);
96
Chris Lattner199ba422009-08-27 06:29:33 +000097 // Look at all of the allocas that we inlined through this call site. If we
98 // have already inlined other allocas through other calls into this function,
99 // then we know that they have disjoint lifetimes and that we can merge them.
100 //
101 // There are many heuristics possible for merging these allocas, and the
102 // different options have different tradeoffs. One thing that we *really*
103 // don't want to hurt is SRoA: once inlining happens, often allocas are no
104 // longer address taken and so they can be promoted.
105 //
106 // Our "solution" for that is to only merge allocas whose outermost type is an
107 // array type. These are usually not promoted because someone is using a
108 // variable index into them. These are also often the most important ones to
109 // merge.
110 //
111 // A better solution would be to have real memory lifetime markers in the IR
112 // and not have the inliner do any merging of allocas at all. This would
113 // allow the backend to do proper stack slot coloring of all allocas that
114 // *actually make it to the backend*, which is really what we want.
115 //
116 // Because we don't have this information, we do this simple and useful hack.
117 //
118 SmallPtrSet<AllocaInst*, 16> UsedAllocas;
119
Chris Lattner6c3ee0f2010-12-06 07:52:42 +0000120 // When processing our SCC, check to see if CS was inlined from some other
121 // call site. For example, if we're processing "A" in this code:
122 // A() { B() }
123 // B() { x = alloca ... C() }
124 // C() { y = alloca ... }
125 // Assume that C was not inlined into B initially, and so we're processing A
126 // and decide to inline B into A. Doing this makes an alloca available for
127 // reuse and makes a callsite (C) available for inlining. When we process
128 // the C call site we don't want to do any alloca merging between X and Y
129 // because their scopes are not disjoint. We could make this smarter by
130 // keeping track of the inline history for each alloca in the
131 // InlinedArrayAllocas but this isn't likely to be a significant win.
132 if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
133 return true;
134
Chris Lattner199ba422009-08-27 06:29:33 +0000135 // Loop over all the allocas we have so far and see if they can be merged with
136 // a previously inlined alloca. If not, remember that we had it.
Chris Lattner60915142010-04-22 23:07:58 +0000137 for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
Chris Lattner199ba422009-08-27 06:29:33 +0000138 AllocaNo != e; ++AllocaNo) {
Chris Lattner60915142010-04-22 23:07:58 +0000139 AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
Chris Lattner199ba422009-08-27 06:29:33 +0000140
141 // Don't bother trying to merge array allocations (they will usually be
142 // canonicalized to be an allocation *of* an array), or allocations whose
143 // type is not itself an array (because we're afraid of pessimizing SRoA).
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000144 ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
Chris Lattner199ba422009-08-27 06:29:33 +0000145 if (ATy == 0 || AI->isArrayAllocation())
146 continue;
147
148 // Get the list of all available allocas for this array type.
149 std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
150
151 // Loop over the allocas in AllocasForType to see if we can reuse one. Note
152 // that we have to be careful not to reuse the same "available" alloca for
153 // multiple different allocas that we just inlined, we use the 'UsedAllocas'
154 // set to keep track of which "available" allocas are being used by this
155 // function. Also, AllocasForType can be empty of course!
156 bool MergedAwayAlloca = false;
157 for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
158 AllocaInst *AvailableAlloca = AllocasForType[i];
159
160 // The available alloca has to be in the right function, not in some other
161 // function in this SCC.
162 if (AvailableAlloca->getParent() != AI->getParent())
163 continue;
164
165 // If the inlined function already uses this alloca then we can't reuse
166 // it.
167 if (!UsedAllocas.insert(AvailableAlloca))
168 continue;
169
170 // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
171 // success!
Chris Lattner7d32b802010-12-06 07:38:40 +0000172 DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
173 << *AvailableAlloca << '\n');
Chris Lattner199ba422009-08-27 06:29:33 +0000174
175 AI->replaceAllUsesWith(AvailableAlloca);
176 AI->eraseFromParent();
177 MergedAwayAlloca = true;
178 ++NumMergedAllocas;
Chris Lattner7d32b802010-12-06 07:38:40 +0000179 IFI.StaticAllocas[AllocaNo] = 0;
Chris Lattner199ba422009-08-27 06:29:33 +0000180 break;
181 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000182
Chris Lattner199ba422009-08-27 06:29:33 +0000183 // If we already nuked the alloca, we're done with it.
184 if (MergedAwayAlloca)
185 continue;
Chris Lattner7d32b802010-12-06 07:38:40 +0000186
Chris Lattner199ba422009-08-27 06:29:33 +0000187 // If we were unable to merge away the alloca either because there are no
188 // allocas of the right type available or because we reused them all
189 // already, remember that this alloca came from an inlined function and mark
190 // it used so we don't reuse it for other allocas from this inline
191 // operation.
192 AllocasForType.push_back(AI);
193 UsedAllocas.insert(AI);
Chris Lattnerbefa4992004-05-23 21:22:17 +0000194 }
Chris Lattner199ba422009-08-27 06:29:33 +0000195
Chris Lattnerbefa4992004-05-23 21:22:17 +0000196 return true;
Chris Lattner237ef562003-08-31 19:10:30 +0000197}
Jakob Stoklund Olesenf8526cb2010-01-20 17:51:28 +0000198
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000199unsigned Inliner::getInlineThreshold(CallSite CS) const {
Jakob Stoklund Olesenf0907fe2010-02-13 01:51:53 +0000200 int thres = InlineThreshold;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000201
202 // Listen to optsize when -inline-limit is not given.
203 Function *Caller = CS.getCaller();
Jakob Stoklund Olesenf8526cb2010-01-20 17:51:28 +0000204 if (Caller && !Caller->isDeclaration() &&
205 Caller->hasFnAttr(Attribute::OptimizeForSize) &&
206 InlineLimit.getNumOccurrences() == 0)
Jakob Stoklund Olesenf0907fe2010-02-13 01:51:53 +0000207 thres = OptSizeThreshold;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000208
Jakob Stoklund Olesenf0907fe2010-02-13 01:51:53 +0000209 // Listen to inlinehint when it would increase the threshold.
210 Function *Callee = CS.getCalledFunction();
211 if (HintThreshold > thres && Callee && !Callee->isDeclaration() &&
212 Callee->hasFnAttr(Attribute::InlineHint))
213 thres = HintThreshold;
214
215 return thres;
Jakob Stoklund Olesenf8526cb2010-01-20 17:51:28 +0000216}
217
Daniel Dunbar1a99dbf2008-10-29 01:02:02 +0000218/// shouldInline - Return true if the inliner should attempt to inline
219/// at the given CallSite.
220bool Inliner::shouldInline(CallSite CS) {
Daniel Dunbarc5e1ec42008-10-30 19:26:59 +0000221 InlineCost IC = getInlineCost(CS);
Daniel Dunbar1a99dbf2008-10-29 01:02:02 +0000222
Daniel Dunbarc5e1ec42008-10-30 19:26:59 +0000223 if (IC.isAlways()) {
David Greenec0aa6792010-01-05 01:27:51 +0000224 DEBUG(dbgs() << " Inlining: cost=always"
Bill Wendling84a832f2009-07-31 19:52:24 +0000225 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbarc5e1ec42008-10-30 19:26:59 +0000226 return true;
227 }
228
229 if (IC.isNever()) {
David Greenec0aa6792010-01-05 01:27:51 +0000230 DEBUG(dbgs() << " NOT Inlining: cost=never"
Bill Wendling84a832f2009-07-31 19:52:24 +0000231 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbarc5e1ec42008-10-30 19:26:59 +0000232 return false;
233 }
234
235 int Cost = IC.getValue();
Dale Johannesene91b9a32009-10-09 00:11:32 +0000236 Function *Caller = CS.getCaller();
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000237 int CurrentThreshold = getInlineThreshold(CS);
Chris Lattner135755d2009-08-27 03:51:50 +0000238 float FudgeFactor = getInlineFudgeFactor(CS);
Jakob Stoklund Olesen2ddbf822010-03-09 00:59:53 +0000239 int AdjThreshold = (int)(CurrentThreshold * FudgeFactor);
240 if (Cost >= AdjThreshold) {
David Greenec0aa6792010-01-05 01:27:51 +0000241 DEBUG(dbgs() << " NOT Inlining: cost=" << Cost
Jakob Stoklund Olesen2ddbf822010-03-09 00:59:53 +0000242 << ", thres=" << AdjThreshold
Bill Wendling84a832f2009-07-31 19:52:24 +0000243 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbar1a99dbf2008-10-29 01:02:02 +0000244 return false;
Daniel Dunbar1a99dbf2008-10-29 01:02:02 +0000245 }
Chris Lattner135755d2009-08-27 03:51:50 +0000246
Chandler Carruthb16117c2012-03-14 20:16:41 +0000247 // Try to detect the case where the current inlining candidate caller (call
248 // it B) is a static or linkonce-ODR function and is an inlining candidate
249 // elsewhere, and the current candidate callee (call it C) is large enough
250 // that inlining it into B would make B too big to inline later. In these
251 // circumstances it may be best not to inline C into B, but to inline B into
252 // its callers.
253 //
254 // This only applies to static and linkonce-ODR functions because those are
255 // expected to be available for inlining in the translation units where they
256 // are used. Thus we will always have the opportunity to make local inlining
257 // decisions. Importantly the linkonce-ODR linkage covers inline functions
258 // and templates in C++.
259 if (Caller->hasLocalLinkage() ||
260 Caller->getLinkage() == GlobalValue::LinkOnceODRLinkage) {
Dale Johannesene91b9a32009-10-09 00:11:32 +0000261 int TotalSecondaryCost = 0;
262 bool outerCallsFound = false;
Dale Johannesenc84e3c02011-01-04 19:01:54 +0000263 // This bool tracks what happens if we do NOT inline C into B.
264 bool callerWillBeRemoved = true;
265 // This bool tracks what happens if we DO inline C into B.
266 bool inliningPreventsSomeOuterInline = false;
Dale Johannesene91b9a32009-10-09 00:11:32 +0000267 for (Value::use_iterator I = Caller->use_begin(), E =Caller->use_end();
268 I != E; ++I) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000269 CallSite CS2(*I);
Dale Johannesene91b9a32009-10-09 00:11:32 +0000270
271 // If this isn't a call to Caller (it could be some other sort
Dale Johannesenc84e3c02011-01-04 19:01:54 +0000272 // of reference) skip it. Such references will prevent the caller
273 // from being removed.
274 if (!CS2 || CS2.getCalledFunction() != Caller) {
275 callerWillBeRemoved = false;
Dale Johannesene91b9a32009-10-09 00:11:32 +0000276 continue;
Dale Johannesenc84e3c02011-01-04 19:01:54 +0000277 }
Dale Johannesene91b9a32009-10-09 00:11:32 +0000278
279 InlineCost IC2 = getInlineCost(CS2);
280 if (IC2.isNever())
Dale Johannesenc84e3c02011-01-04 19:01:54 +0000281 callerWillBeRemoved = false;
Dale Johannesene91b9a32009-10-09 00:11:32 +0000282 if (IC2.isAlways() || IC2.isNever())
283 continue;
284
285 outerCallsFound = true;
286 int Cost2 = IC2.getValue();
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000287 int CurrentThreshold2 = getInlineThreshold(CS2);
Dale Johannesene91b9a32009-10-09 00:11:32 +0000288 float FudgeFactor2 = getInlineFudgeFactor(CS2);
289
290 if (Cost2 >= (int)(CurrentThreshold2 * FudgeFactor2))
Dale Johannesenc84e3c02011-01-04 19:01:54 +0000291 callerWillBeRemoved = false;
Dale Johannesene91b9a32009-10-09 00:11:32 +0000292
Dale Johannesenbdb984b2009-10-09 21:42:02 +0000293 // See if we have this case. We subtract off the penalty
Dale Johannesene91b9a32009-10-09 00:11:32 +0000294 // for the call instruction, which we would be deleting.
295 if (Cost2 < (int)(CurrentThreshold2 * FudgeFactor2) &&
Dale Johannesenbdb984b2009-10-09 21:42:02 +0000296 Cost2 + Cost - (InlineConstants::CallPenalty + 1) >=
297 (int)(CurrentThreshold2 * FudgeFactor2)) {
Dale Johannesenc84e3c02011-01-04 19:01:54 +0000298 inliningPreventsSomeOuterInline = true;
Dale Johannesene91b9a32009-10-09 00:11:32 +0000299 TotalSecondaryCost += Cost2;
300 }
301 }
302 // If all outer calls to Caller would get inlined, the cost for the last
303 // one is set very low by getInlineCost, in anticipation that Caller will
304 // be removed entirely. We did not account for this above unless there
305 // is only one caller of Caller.
Dale Johannesenc84e3c02011-01-04 19:01:54 +0000306 if (callerWillBeRemoved && Caller->use_begin() != Caller->use_end())
Dale Johannesenbdb984b2009-10-09 21:42:02 +0000307 TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
Dale Johannesene91b9a32009-10-09 00:11:32 +0000308
Dale Johannesenc84e3c02011-01-04 19:01:54 +0000309 if (outerCallsFound && inliningPreventsSomeOuterInline &&
Dale Johannesene91b9a32009-10-09 00:11:32 +0000310 TotalSecondaryCost < Cost) {
David Greenec0aa6792010-01-05 01:27:51 +0000311 DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction() <<
Dale Johannesene91b9a32009-10-09 00:11:32 +0000312 " Cost = " << Cost <<
313 ", outer Cost = " << TotalSecondaryCost << '\n');
314 return false;
315 }
316 }
317
David Greenec0aa6792010-01-05 01:27:51 +0000318 DEBUG(dbgs() << " Inlining: cost=" << Cost
Jakob Stoklund Olesen2ddbf822010-03-09 00:59:53 +0000319 << ", thres=" << AdjThreshold
Dale Johannesene91b9a32009-10-09 00:11:32 +0000320 << ", Call: " << *CS.getInstruction() << '\n');
Chris Lattner135755d2009-08-27 03:51:50 +0000321 return true;
Daniel Dunbar1a99dbf2008-10-29 01:02:02 +0000322}
Chris Lattner237ef562003-08-31 19:10:30 +0000323
Chris Lattner15952872010-05-01 01:05:10 +0000324/// InlineHistoryIncludes - Return true if the specified inline history ID
325/// indicates an inline history that includes the specified function.
326static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
327 const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
328 while (InlineHistoryID != -1) {
329 assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
330 "Invalid inline history ID");
331 if (InlineHistory[InlineHistoryID].first == F)
332 return true;
333 InlineHistoryID = InlineHistory[InlineHistoryID].second;
334 }
335 return false;
336}
337
Chandler Carruth6c0b3ac2012-03-12 11:19:33 +0000338/// \brief Simplify arguments going into a particular callsite.
339///
340/// This is important to do each time we add a callsite due to inlining so that
341/// constants and other entities which feed into inline cost estimation are
342/// properly recognized when analyzing the new callsite. Consider:
343/// void outer(int x) {
344/// if (x < 42)
345/// return inner(42 - x);
346/// ...
347/// }
348/// void inner(int x) {
349/// ...
350/// }
351///
352/// The inliner gives calls to 'outer' with a constant argument a bonus because
353/// it will delete one side of a branch. But the resulting call to 'inner'
354/// will, after inlining, also have a constant operand. We need to do just
355/// enough constant folding to expose this for callsite arguments. The rest
356/// will be taken care of after the inliner finishes running.
357static void simplifyCallSiteArguments(const TargetData *TD, CallSite CS) {
358 // FIXME: It would be nice to avoid this smallvector if RAUW doesn't
359 // invalidate operand iterators in any cases.
360 SmallVector<std::pair<Value *, Value*>, 4> SimplifiedArgs;
361 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
362 I != E; ++I)
363 if (Instruction *Inst = dyn_cast<Instruction>(*I))
364 if (Value *SimpleArg = SimplifyInstruction(Inst, TD))
365 SimplifiedArgs.push_back(std::make_pair(Inst, SimpleArg));
366 for (unsigned Idx = 0, Size = SimplifiedArgs.size(); Idx != Size; ++Idx)
367 SimplifiedArgs[Idx].first->replaceAllUsesWith(SimplifiedArgs[Idx].second);
368}
Chris Lattner15952872010-05-01 01:05:10 +0000369
Chris Lattner2decb222010-04-16 22:42:17 +0000370bool Inliner::runOnSCC(CallGraphSCC &SCC) {
Chris Lattner237ef562003-08-31 19:10:30 +0000371 CallGraph &CG = getAnalysis<CallGraph>();
Dan Gohman02a436c2009-07-24 18:13:53 +0000372 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner237ef562003-08-31 19:10:30 +0000373
Dale Johannesen16581bf2009-03-23 23:39:20 +0000374 SmallPtrSet<Function*, 8> SCCFunctions;
David Greenec0aa6792010-01-05 01:27:51 +0000375 DEBUG(dbgs() << "Inliner visiting SCC:");
Chris Lattner2decb222010-04-16 22:42:17 +0000376 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
377 Function *F = (*I)->getFunction();
Chris Lattnerbefa4992004-05-23 21:22:17 +0000378 if (F) SCCFunctions.insert(F);
David Greenec0aa6792010-01-05 01:27:51 +0000379 DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
Chris Lattner237ef562003-08-31 19:10:30 +0000380 }
Chris Lattner237ef562003-08-31 19:10:30 +0000381
Chris Lattnerbefa4992004-05-23 21:22:17 +0000382 // Scan through and identify all call sites ahead of time so that we only
383 // inline call sites in the original functions, not call sites that result
384 // from inlining other functions.
Chris Lattner15952872010-05-01 01:05:10 +0000385 SmallVector<std::pair<CallSite, int>, 16> CallSites;
386
387 // When inlining a callee produces new call sites, we want to keep track of
388 // the fact that they were inlined from the callee. This allows us to avoid
389 // infinite inlining in some obscure cases. To represent this, we use an
390 // index into the InlineHistory vector.
391 SmallVector<std::pair<Function*, int>, 8> InlineHistory;
Chris Lattnerbefa4992004-05-23 21:22:17 +0000392
Chris Lattner2decb222010-04-16 22:42:17 +0000393 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
394 Function *F = (*I)->getFunction();
Chris Lattner135755d2009-08-27 03:51:50 +0000395 if (!F) continue;
396
397 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
398 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000399 CallSite CS(cast<Value>(I));
Dale Johannesene91b9a32009-10-09 00:11:32 +0000400 // If this isn't a call, or it is a call to an intrinsic, it can
Chris Lattnerd43d5e82009-08-31 05:34:32 +0000401 // never be inlined.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000402 if (!CS || isa<IntrinsicInst>(I))
Chris Lattner135755d2009-08-27 03:51:50 +0000403 continue;
404
Chris Lattnerd43d5e82009-08-31 05:34:32 +0000405 // If this is a direct call to an external function, we can never inline
406 // it. If it is an indirect call, inlining may resolve it to be a
407 // direct call, so we keep it.
408 if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
409 continue;
410
Chris Lattner15952872010-05-01 01:05:10 +0000411 CallSites.push_back(std::make_pair(CS, -1));
Chris Lattner135755d2009-08-27 03:51:50 +0000412 }
413 }
Chris Lattner237ef562003-08-31 19:10:30 +0000414
David Greenec0aa6792010-01-05 01:27:51 +0000415 DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
Misha Brukmanfd939082005-04-21 23:48:37 +0000416
Chris Lattner44711362010-04-20 00:47:08 +0000417 // If there are no calls in this function, exit early.
418 if (CallSites.empty())
419 return false;
420
Chris Lattnerbefa4992004-05-23 21:22:17 +0000421 // Now that we have all of the call sites, move the ones to functions in the
422 // current SCC to the end of the list.
423 unsigned FirstCallInSCC = CallSites.size();
424 for (unsigned i = 0; i < FirstCallInSCC; ++i)
Chris Lattner15952872010-05-01 01:05:10 +0000425 if (Function *F = CallSites[i].first.getCalledFunction())
Chris Lattnerbefa4992004-05-23 21:22:17 +0000426 if (SCCFunctions.count(F))
427 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
Misha Brukmanfd939082005-04-21 23:48:37 +0000428
Chris Lattner199ba422009-08-27 06:29:33 +0000429
430 InlinedArrayAllocasTy InlinedArrayAllocas;
Chris Lattner60915142010-04-22 23:07:58 +0000431 InlineFunctionInfo InlineInfo(&CG, TD);
Chris Lattner199ba422009-08-27 06:29:33 +0000432
Chris Lattnerbefa4992004-05-23 21:22:17 +0000433 // Now that we have all of the call sites, loop over them and inline them if
434 // it looks profitable to do so.
435 bool Changed = false;
436 bool LocalChange;
437 do {
438 LocalChange = false;
439 // Iterate over the outer loop because inlining functions can cause indirect
440 // calls to become direct calls.
Chris Lattner135755d2009-08-27 03:51:50 +0000441 for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
Chris Lattner15952872010-05-01 01:05:10 +0000442 CallSite CS = CallSites[CSi].first;
Chris Lattner199ba422009-08-27 06:29:33 +0000443
Chris Lattner135755d2009-08-27 03:51:50 +0000444 Function *Caller = CS.getCaller();
Chris Lattnerdbab4dc2009-11-12 07:56:08 +0000445 Function *Callee = CS.getCalledFunction();
446
447 // If this call site is dead and it is to a readonly function, we should
448 // just delete the call instead of trying to inline it, regardless of
449 // size. This happens because IPSCCP propagates the result out of the
450 // call and then we're left with the dead call.
Chris Lattner4ff41412009-11-12 21:58:18 +0000451 if (isInstructionTriviallyDead(CS.getInstruction())) {
David Greenec0aa6792010-01-05 01:27:51 +0000452 DEBUG(dbgs() << " -> Deleting dead call: "
Chris Lattnerdbab4dc2009-11-12 07:56:08 +0000453 << *CS.getInstruction() << "\n");
454 // Update the call graph by deleting the edge from Callee to Caller.
455 CG[Caller]->removeCallEdgeFor(CS);
456 CS.getInstruction()->eraseFromParent();
457 ++NumCallsDeleted;
Jakob Stoklund Olesenf7477472010-03-09 23:02:17 +0000458 // Update the cached cost info with the missing call
459 growCachedCostInfo(Caller, NULL);
Chris Lattnerdbab4dc2009-11-12 07:56:08 +0000460 } else {
461 // We can only inline direct calls to non-declarations.
462 if (Callee == 0 || Callee->isDeclaration()) continue;
Chris Lattner135755d2009-08-27 03:51:50 +0000463
Eric Christopherf0193ed2010-07-13 18:27:13 +0000464 // If this call site was obtained by inlining another function, verify
Chris Lattner15952872010-05-01 01:05:10 +0000465 // that the include path for the function did not include the callee
Chris Lattner7d32b802010-12-06 07:38:40 +0000466 // itself. If so, we'd be recursively inlining the same function,
Chris Lattner15952872010-05-01 01:05:10 +0000467 // which would provide the same callsites, which would cause us to
468 // infinitely inline.
469 int InlineHistoryID = CallSites[CSi].second;
470 if (InlineHistoryID != -1 &&
471 InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
472 continue;
473
474
Chris Lattnerdbab4dc2009-11-12 07:56:08 +0000475 // If the policy determines that we should inline this function,
476 // try to do so.
477 if (!shouldInline(CS))
478 continue;
479
Chris Lattnerfe9af3b2010-04-22 23:37:35 +0000480 // Attempt to inline the function.
Chris Lattner6c3ee0f2010-12-06 07:52:42 +0000481 if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
Chad Rosierfa086f12012-02-25 02:56:01 +0000482 InlineHistoryID, InsertLifetime))
Chris Lattnerdbab4dc2009-11-12 07:56:08 +0000483 continue;
484 ++NumInlined;
Chris Lattner15952872010-05-01 01:05:10 +0000485
Chris Lattner0ca2f282010-05-01 01:26:13 +0000486 // If inlining this function gave us any new call sites, throw them
Chris Lattnerfe9af3b2010-04-22 23:37:35 +0000487 // onto our worklist to process. They are useful inline candidates.
Chris Lattner0ca2f282010-05-01 01:26:13 +0000488 if (!InlineInfo.InlinedCalls.empty()) {
Chris Lattner15952872010-05-01 01:05:10 +0000489 // Create a new inline history entry for this, so that we remember
490 // that these new callsites came about due to inlining Callee.
491 int NewHistoryID = InlineHistory.size();
492 InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
493
Chris Lattner0ca2f282010-05-01 01:26:13 +0000494 for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
Chris Lattner15952872010-05-01 01:05:10 +0000495 i != e; ++i) {
Chris Lattner0ca2f282010-05-01 01:26:13 +0000496 Value *Ptr = InlineInfo.InlinedCalls[i];
Chandler Carruth6c0b3ac2012-03-12 11:19:33 +0000497 CallSite NewCS = Ptr;
498 simplifyCallSiteArguments(TD, NewCS);
499 CallSites.push_back(std::make_pair(NewCS, NewHistoryID));
Chris Lattner15952872010-05-01 01:05:10 +0000500 }
Chris Lattner07686322010-04-23 18:37:01 +0000501 }
Chris Lattnerfe9af3b2010-04-22 23:37:35 +0000502
Jakob Stoklund Olesenf7477472010-03-09 23:02:17 +0000503 // Update the cached cost info with the inlined call.
504 growCachedCostInfo(Caller, Callee);
Chris Lattnerdbab4dc2009-11-12 07:56:08 +0000505 }
506
507 // If we inlined or deleted the last possible call site to the function,
508 // delete the function body now.
509 if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
Chris Lattnerd43d5e82009-08-31 05:34:32 +0000510 // TODO: Can remove if in SCC now.
Chris Lattnerb374b902009-08-31 03:15:49 +0000511 !SCCFunctions.count(Callee) &&
Chris Lattnerd43d5e82009-08-31 05:34:32 +0000512
Chris Lattnerb374b902009-08-31 03:15:49 +0000513 // The function may be apparently dead, but if there are indirect
514 // callgraph references to the node, we cannot delete it yet, this
515 // could invalidate the CGSCC iterator.
516 CG[Callee]->getNumReferences() == 0) {
David Greenec0aa6792010-01-05 01:27:51 +0000517 DEBUG(dbgs() << " -> Deleting dead function: "
Chris Lattner199ba422009-08-27 06:29:33 +0000518 << Callee->getName() << "\n");
519 CallGraphNode *CalleeNode = CG[Callee];
520
521 // Remove any call graph edges from the callee to its callees.
522 CalleeNode->removeAllCalledFunctions();
523
524 resetCachedCostInfo(Callee);
525
526 // Removing the node for callee from the call graph and delete it.
527 delete CG.removeFunctionFromModule(CalleeNode);
528 ++NumDeleted;
529 }
Chris Lattner135755d2009-08-27 03:51:50 +0000530
531 // Remove this call site from the list. If possible, use
532 // swap/pop_back for efficiency, but do not use it if doing so would
533 // move a call site to a function in this SCC before the
534 // 'FirstCallInSCC' barrier.
Chris Lattner2decb222010-04-16 22:42:17 +0000535 if (SCC.isSingular()) {
Benjamin Kramerc29df3c2010-05-31 12:50:41 +0000536 CallSites[CSi] = CallSites.back();
Chris Lattner135755d2009-08-27 03:51:50 +0000537 CallSites.pop_back();
538 } else {
539 CallSites.erase(CallSites.begin()+CSi);
540 }
541 --CSi;
542
Chris Lattner135755d2009-08-27 03:51:50 +0000543 Changed = true;
544 LocalChange = true;
545 }
Chris Lattnerbefa4992004-05-23 21:22:17 +0000546 } while (LocalChange);
Chris Lattner775cbdd2004-04-08 06:34:31 +0000547
Chris Lattner237ef562003-08-31 19:10:30 +0000548 return Changed;
549}
550
Chris Lattner68d57e72004-04-20 22:06:53 +0000551// doFinalization - Remove now-dead linkonce functions at the end of
552// processing to avoid breaking the SCC traversal.
553bool Inliner::doFinalization(CallGraph &CG) {
Devang Patelb7c6bf12008-11-05 01:39:16 +0000554 return removeDeadFunctions(CG);
555}
556
Chris Lattner135755d2009-08-27 03:51:50 +0000557/// removeDeadFunctions - Remove dead functions that are not included in
558/// DNR (Do Not Remove) list.
Chandler Carruthf91f5af2012-03-16 06:10:13 +0000559bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
560 SmallVector<CallGraphNode*, 16> FunctionsToRemove;
Chris Lattner3e1358a2004-04-21 20:44:33 +0000561
562 // Scan for all of the functions, looking for ones that should now be removed
563 // from the program. Insert the dead ones in the FunctionsToRemove set.
564 for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
565 CallGraphNode *CGN = I->second;
Chris Lattner135755d2009-08-27 03:51:50 +0000566 Function *F = CGN->getFunction();
Chandler Carruthf91f5af2012-03-16 06:10:13 +0000567 if (!F || F->isDeclaration())
568 continue;
569
570 // Handle the case when this function is called and we only want to care
571 // about always-inline functions. This is a bit of a hack to share code
572 // between here and the InlineAlways pass.
573 if (AlwaysInlineOnly && !F->hasFnAttr(Attribute::AlwaysInline))
574 continue;
575
Chris Lattner135755d2009-08-27 03:51:50 +0000576 // If the only remaining users of the function are dead constants, remove
577 // them.
578 F->removeDeadConstantUsers();
Chris Lattner3e1358a2004-04-21 20:44:33 +0000579
Eli Friedmanc6633052011-10-20 05:23:42 +0000580 if (!F->isDefTriviallyDead())
Chris Lattner135755d2009-08-27 03:51:50 +0000581 continue;
582
583 // Remove any call graph edges from the function to its callees.
584 CGN->removeAllCalledFunctions();
Devang Patelb7c6bf12008-11-05 01:39:16 +0000585
Chris Lattner135755d2009-08-27 03:51:50 +0000586 // Remove any edges from the external node to the function's call graph
587 // node. These edges might have been made irrelegant due to
588 // optimization of the program.
589 CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
Chris Lattner0c0aa712004-09-18 21:37:03 +0000590
Chris Lattner135755d2009-08-27 03:51:50 +0000591 // Removing the node for callee from the call graph and delete it.
Chandler Carruthf91f5af2012-03-16 06:10:13 +0000592 FunctionsToRemove.push_back(CGN);
Chris Lattner68d57e72004-04-20 22:06:53 +0000593 }
Chandler Carruthf91f5af2012-03-16 06:10:13 +0000594 if (FunctionsToRemove.empty())
595 return false;
Chris Lattner3e1358a2004-04-21 20:44:33 +0000596
597 // Now that we know which functions to delete, do so. We didn't want to do
598 // this inline, because that would invalidate our CallGraph::iterator
599 // objects. :(
Chris Lattner135755d2009-08-27 03:51:50 +0000600 //
Chandler Carruthf91f5af2012-03-16 06:10:13 +0000601 // Note that it doesn't matter that we are iterating over a non-stable order
Chris Lattner135755d2009-08-27 03:51:50 +0000602 // here to do this, it doesn't matter which order the functions are deleted
603 // in.
Chandler Carruthf91f5af2012-03-16 06:10:13 +0000604 std::sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
605 FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
606 FunctionsToRemove.end()),
607 FunctionsToRemove.end());
608 for (SmallVectorImpl<CallGraphNode *>::iterator I = FunctionsToRemove.begin(),
609 E = FunctionsToRemove.end();
610 I != E; ++I) {
Dale Johannesen1f67ce42009-03-19 18:03:56 +0000611 resetCachedCostInfo((*I)->getFunction());
Chris Lattner3e1358a2004-04-21 20:44:33 +0000612 delete CG.removeFunctionFromModule(*I);
613 ++NumDeleted;
Chris Lattner3e1358a2004-04-21 20:44:33 +0000614 }
Chandler Carruthf91f5af2012-03-16 06:10:13 +0000615 return true;
Chris Lattner68d57e72004-04-20 22:06:53 +0000616}