1 //===- Inliner.cpp - Code common to all inliners --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // 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.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "inline"
17 #include "llvm/Transforms/IPO/InlinerPass.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/CallGraph.h"
21 #include "llvm/Analysis/InlineCost.h"
22 #include "llvm/DataLayout.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Module.h"
26 #include "llvm/Support/CallSite.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetLibraryInfo.h"
31 #include "llvm/Transforms/Utils/Cloning.h"
32 #include "llvm/Transforms/Utils/Local.h"
35 STATISTIC(NumInlined, "Number of functions inlined");
36 STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
37 STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
38 STATISTIC(NumMergedAllocas, "Number of allocas merged together");
40 // This weirdly named statistic tracks the number of times that, when attempting
41 // to inline a function A into B, we analyze the callers of B in order to see
42 // if those would be more profitable and blocked inline steps.
43 STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
46 InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
47 cl::desc("Control the amount of inlining to perform (default = 225)"));
50 HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
51 cl::desc("Threshold for inlining functions with inline hint"));
53 // Threshold to use when optsize is specified (and there is no -inline-limit).
54 const int OptSizeThreshold = 75;
56 Inliner::Inliner(char &ID)
57 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(true) {}
59 Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
60 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
61 InlineLimit : Threshold),
62 InsertLifetime(InsertLifetime) {}
64 /// getAnalysisUsage - For this class, we declare that we require and preserve
65 /// the call graph. If the derived class implements this method, it should
66 /// always explicitly call the implementation here.
67 void Inliner::getAnalysisUsage(AnalysisUsage &AU) const {
68 CallGraphSCCPass::getAnalysisUsage(AU);
72 typedef DenseMap<ArrayType*, std::vector<AllocaInst*> >
73 InlinedArrayAllocasTy;
75 /// InlineCallIfPossible - If it is possible to inline the specified call site,
76 /// do so and update the CallGraph for this operation.
78 /// This function also does some basic book-keeping to update the IR. The
79 /// InlinedArrayAllocas map keeps track of any allocas that are already
80 /// available from other functions inlined into the caller. If we are able to
81 /// inline this call site we attempt to reuse already available allocas or add
82 /// any new allocas to the set if not possible.
83 static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
84 InlinedArrayAllocasTy &InlinedArrayAllocas,
85 int InlineHistory, bool InsertLifetime) {
86 Function *Callee = CS.getCalledFunction();
87 Function *Caller = CS.getCaller();
89 // Try to inline the function. Get the list of static allocas that were
91 if (!InlineFunction(CS, IFI, InsertLifetime))
94 // If the inlined function had a higher stack protection level than the
95 // calling function, then bump up the caller's stack protection level.
96 if (Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
97 Attribute::StackProtectReq))
98 Caller->addFnAttr(Attribute::StackProtectReq);
99 else if (Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
100 Attribute::StackProtect) &&
101 !Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
102 Attribute::StackProtectReq))
103 Caller->addFnAttr(Attribute::StackProtect);
105 // Look at all of the allocas that we inlined through this call site. If we
106 // have already inlined other allocas through other calls into this function,
107 // then we know that they have disjoint lifetimes and that we can merge them.
109 // There are many heuristics possible for merging these allocas, and the
110 // different options have different tradeoffs. One thing that we *really*
111 // don't want to hurt is SRoA: once inlining happens, often allocas are no
112 // longer address taken and so they can be promoted.
114 // Our "solution" for that is to only merge allocas whose outermost type is an
115 // array type. These are usually not promoted because someone is using a
116 // variable index into them. These are also often the most important ones to
119 // A better solution would be to have real memory lifetime markers in the IR
120 // and not have the inliner do any merging of allocas at all. This would
121 // allow the backend to do proper stack slot coloring of all allocas that
122 // *actually make it to the backend*, which is really what we want.
124 // Because we don't have this information, we do this simple and useful hack.
126 SmallPtrSet<AllocaInst*, 16> UsedAllocas;
128 // When processing our SCC, check to see if CS was inlined from some other
129 // call site. For example, if we're processing "A" in this code:
131 // B() { x = alloca ... C() }
132 // C() { y = alloca ... }
133 // Assume that C was not inlined into B initially, and so we're processing A
134 // and decide to inline B into A. Doing this makes an alloca available for
135 // reuse and makes a callsite (C) available for inlining. When we process
136 // the C call site we don't want to do any alloca merging between X and Y
137 // because their scopes are not disjoint. We could make this smarter by
138 // keeping track of the inline history for each alloca in the
139 // InlinedArrayAllocas but this isn't likely to be a significant win.
140 if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
143 // Loop over all the allocas we have so far and see if they can be merged with
144 // a previously inlined alloca. If not, remember that we had it.
145 for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
146 AllocaNo != e; ++AllocaNo) {
147 AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
149 // Don't bother trying to merge array allocations (they will usually be
150 // canonicalized to be an allocation *of* an array), or allocations whose
151 // type is not itself an array (because we're afraid of pessimizing SRoA).
152 ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
153 if (ATy == 0 || AI->isArrayAllocation())
156 // Get the list of all available allocas for this array type.
157 std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
159 // Loop over the allocas in AllocasForType to see if we can reuse one. Note
160 // that we have to be careful not to reuse the same "available" alloca for
161 // multiple different allocas that we just inlined, we use the 'UsedAllocas'
162 // set to keep track of which "available" allocas are being used by this
163 // function. Also, AllocasForType can be empty of course!
164 bool MergedAwayAlloca = false;
165 for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
166 AllocaInst *AvailableAlloca = AllocasForType[i];
168 // The available alloca has to be in the right function, not in some other
169 // function in this SCC.
170 if (AvailableAlloca->getParent() != AI->getParent())
173 // If the inlined function already uses this alloca then we can't reuse
175 if (!UsedAllocas.insert(AvailableAlloca))
178 // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
180 DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
181 << *AvailableAlloca << '\n');
183 AI->replaceAllUsesWith(AvailableAlloca);
184 AI->eraseFromParent();
185 MergedAwayAlloca = true;
187 IFI.StaticAllocas[AllocaNo] = 0;
191 // If we already nuked the alloca, we're done with it.
192 if (MergedAwayAlloca)
195 // If we were unable to merge away the alloca either because there are no
196 // allocas of the right type available or because we reused them all
197 // already, remember that this alloca came from an inlined function and mark
198 // it used so we don't reuse it for other allocas from this inline
200 AllocasForType.push_back(AI);
201 UsedAllocas.insert(AI);
207 unsigned Inliner::getInlineThreshold(CallSite CS) const {
208 int thres = InlineThreshold; // -inline-threshold or else selected by
211 // If -inline-threshold is not given, listen to the optsize attribute when it
212 // would decrease the threshold.
213 Function *Caller = CS.getCaller();
214 bool OptSize = Caller && !Caller->isDeclaration() &&
215 Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
216 Attribute::OptimizeForSize);
217 if (!(InlineLimit.getNumOccurrences() > 0) && OptSize &&
218 OptSizeThreshold < thres)
219 thres = OptSizeThreshold;
221 // Listen to the inlinehint attribute when it would increase the threshold
222 // and the caller does not need to minimize its size.
223 Function *Callee = CS.getCalledFunction();
224 bool InlineHint = Callee && !Callee->isDeclaration() &&
225 Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
226 Attribute::InlineHint);
227 if (InlineHint && HintThreshold > thres
228 && !Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
230 thres = HintThreshold;
235 /// shouldInline - Return true if the inliner should attempt to inline
236 /// at the given CallSite.
237 bool Inliner::shouldInline(CallSite CS) {
238 InlineCost IC = getInlineCost(CS);
241 DEBUG(dbgs() << " Inlining: cost=always"
242 << ", Call: " << *CS.getInstruction() << "\n");
247 DEBUG(dbgs() << " NOT Inlining: cost=never"
248 << ", Call: " << *CS.getInstruction() << "\n");
252 Function *Caller = CS.getCaller();
254 DEBUG(dbgs() << " NOT Inlining: cost=" << IC.getCost()
255 << ", thres=" << (IC.getCostDelta() + IC.getCost())
256 << ", Call: " << *CS.getInstruction() << "\n");
260 // Try to detect the case where the current inlining candidate caller (call
261 // it B) is a static or linkonce-ODR function and is an inlining candidate
262 // elsewhere, and the current candidate callee (call it C) is large enough
263 // that inlining it into B would make B too big to inline later. In these
264 // circumstances it may be best not to inline C into B, but to inline B into
267 // This only applies to static and linkonce-ODR functions because those are
268 // expected to be available for inlining in the translation units where they
269 // are used. Thus we will always have the opportunity to make local inlining
270 // decisions. Importantly the linkonce-ODR linkage covers inline functions
271 // and templates in C++.
273 // FIXME: All of this logic should be sunk into getInlineCost. It relies on
274 // the internal implementation of the inline cost metrics rather than
275 // treating them as truly abstract units etc.
276 if (Caller->hasLocalLinkage() ||
277 Caller->getLinkage() == GlobalValue::LinkOnceODRLinkage) {
278 int TotalSecondaryCost = 0;
279 // The candidate cost to be imposed upon the current function.
280 int CandidateCost = IC.getCost() - (InlineConstants::CallPenalty + 1);
281 // This bool tracks what happens if we do NOT inline C into B.
282 bool callerWillBeRemoved = Caller->hasLocalLinkage();
283 // This bool tracks what happens if we DO inline C into B.
284 bool inliningPreventsSomeOuterInline = false;
285 for (Value::use_iterator I = Caller->use_begin(), E =Caller->use_end();
289 // If this isn't a call to Caller (it could be some other sort
290 // of reference) skip it. Such references will prevent the caller
291 // from being removed.
292 if (!CS2 || CS2.getCalledFunction() != Caller) {
293 callerWillBeRemoved = false;
297 InlineCost IC2 = getInlineCost(CS2);
298 ++NumCallerCallersAnalyzed;
300 callerWillBeRemoved = false;
306 // See if inlining or original callsite would erase the cost delta of
307 // this callsite. We subtract off the penalty for the call instruction,
308 // which we would be deleting.
309 if (IC2.getCostDelta() <= CandidateCost) {
310 inliningPreventsSomeOuterInline = true;
311 TotalSecondaryCost += IC2.getCost();
314 // If all outer calls to Caller would get inlined, the cost for the last
315 // one is set very low by getInlineCost, in anticipation that Caller will
316 // be removed entirely. We did not account for this above unless there
317 // is only one caller of Caller.
318 if (callerWillBeRemoved && Caller->use_begin() != Caller->use_end())
319 TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
321 if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) {
322 DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction() <<
323 " Cost = " << IC.getCost() <<
324 ", outer Cost = " << TotalSecondaryCost << '\n');
329 DEBUG(dbgs() << " Inlining: cost=" << IC.getCost()
330 << ", thres=" << (IC.getCostDelta() + IC.getCost())
331 << ", Call: " << *CS.getInstruction() << '\n');
335 /// InlineHistoryIncludes - Return true if the specified inline history ID
336 /// indicates an inline history that includes the specified function.
337 static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
338 const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
339 while (InlineHistoryID != -1) {
340 assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
341 "Invalid inline history ID");
342 if (InlineHistory[InlineHistoryID].first == F)
344 InlineHistoryID = InlineHistory[InlineHistoryID].second;
349 bool Inliner::runOnSCC(CallGraphSCC &SCC) {
350 CallGraph &CG = getAnalysis<CallGraph>();
351 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
352 const TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
354 SmallPtrSet<Function*, 8> SCCFunctions;
355 DEBUG(dbgs() << "Inliner visiting SCC:");
356 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
357 Function *F = (*I)->getFunction();
358 if (F) SCCFunctions.insert(F);
359 DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
362 // Scan through and identify all call sites ahead of time so that we only
363 // inline call sites in the original functions, not call sites that result
364 // from inlining other functions.
365 SmallVector<std::pair<CallSite, int>, 16> CallSites;
367 // When inlining a callee produces new call sites, we want to keep track of
368 // the fact that they were inlined from the callee. This allows us to avoid
369 // infinite inlining in some obscure cases. To represent this, we use an
370 // index into the InlineHistory vector.
371 SmallVector<std::pair<Function*, int>, 8> InlineHistory;
373 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
374 Function *F = (*I)->getFunction();
377 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
378 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
379 CallSite CS(cast<Value>(I));
380 // If this isn't a call, or it is a call to an intrinsic, it can
382 if (!CS || isa<IntrinsicInst>(I))
385 // If this is a direct call to an external function, we can never inline
386 // it. If it is an indirect call, inlining may resolve it to be a
387 // direct call, so we keep it.
388 if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
391 CallSites.push_back(std::make_pair(CS, -1));
395 DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
397 // If there are no calls in this function, exit early.
398 if (CallSites.empty())
401 // Now that we have all of the call sites, move the ones to functions in the
402 // current SCC to the end of the list.
403 unsigned FirstCallInSCC = CallSites.size();
404 for (unsigned i = 0; i < FirstCallInSCC; ++i)
405 if (Function *F = CallSites[i].first.getCalledFunction())
406 if (SCCFunctions.count(F))
407 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
410 InlinedArrayAllocasTy InlinedArrayAllocas;
411 InlineFunctionInfo InlineInfo(&CG, TD);
413 // Now that we have all of the call sites, loop over them and inline them if
414 // it looks profitable to do so.
415 bool Changed = false;
419 // Iterate over the outer loop because inlining functions can cause indirect
420 // calls to become direct calls.
421 for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
422 CallSite CS = CallSites[CSi].first;
424 Function *Caller = CS.getCaller();
425 Function *Callee = CS.getCalledFunction();
427 // If this call site is dead and it is to a readonly function, we should
428 // just delete the call instead of trying to inline it, regardless of
429 // size. This happens because IPSCCP propagates the result out of the
430 // call and then we're left with the dead call.
431 if (isInstructionTriviallyDead(CS.getInstruction(), TLI)) {
432 DEBUG(dbgs() << " -> Deleting dead call: "
433 << *CS.getInstruction() << "\n");
434 // Update the call graph by deleting the edge from Callee to Caller.
435 CG[Caller]->removeCallEdgeFor(CS);
436 CS.getInstruction()->eraseFromParent();
439 // We can only inline direct calls to non-declarations.
440 if (Callee == 0 || Callee->isDeclaration()) continue;
442 // If this call site was obtained by inlining another function, verify
443 // that the include path for the function did not include the callee
444 // itself. If so, we'd be recursively inlining the same function,
445 // which would provide the same callsites, which would cause us to
446 // infinitely inline.
447 int InlineHistoryID = CallSites[CSi].second;
448 if (InlineHistoryID != -1 &&
449 InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
453 // If the policy determines that we should inline this function,
455 if (!shouldInline(CS))
458 // Attempt to inline the function.
459 if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
460 InlineHistoryID, InsertLifetime))
464 // If inlining this function gave us any new call sites, throw them
465 // onto our worklist to process. They are useful inline candidates.
466 if (!InlineInfo.InlinedCalls.empty()) {
467 // Create a new inline history entry for this, so that we remember
468 // that these new callsites came about due to inlining Callee.
469 int NewHistoryID = InlineHistory.size();
470 InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
472 for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
474 Value *Ptr = InlineInfo.InlinedCalls[i];
475 CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
480 // If we inlined or deleted the last possible call site to the function,
481 // delete the function body now.
482 if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
483 // TODO: Can remove if in SCC now.
484 !SCCFunctions.count(Callee) &&
486 // The function may be apparently dead, but if there are indirect
487 // callgraph references to the node, we cannot delete it yet, this
488 // could invalidate the CGSCC iterator.
489 CG[Callee]->getNumReferences() == 0) {
490 DEBUG(dbgs() << " -> Deleting dead function: "
491 << Callee->getName() << "\n");
492 CallGraphNode *CalleeNode = CG[Callee];
494 // Remove any call graph edges from the callee to its callees.
495 CalleeNode->removeAllCalledFunctions();
497 // Removing the node for callee from the call graph and delete it.
498 delete CG.removeFunctionFromModule(CalleeNode);
502 // Remove this call site from the list. If possible, use
503 // swap/pop_back for efficiency, but do not use it if doing so would
504 // move a call site to a function in this SCC before the
505 // 'FirstCallInSCC' barrier.
506 if (SCC.isSingular()) {
507 CallSites[CSi] = CallSites.back();
508 CallSites.pop_back();
510 CallSites.erase(CallSites.begin()+CSi);
517 } while (LocalChange);
522 // doFinalization - Remove now-dead linkonce functions at the end of
523 // processing to avoid breaking the SCC traversal.
524 bool Inliner::doFinalization(CallGraph &CG) {
525 return removeDeadFunctions(CG);
528 /// removeDeadFunctions - Remove dead functions that are not included in
529 /// DNR (Do Not Remove) list.
530 bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
531 SmallVector<CallGraphNode*, 16> FunctionsToRemove;
533 // Scan for all of the functions, looking for ones that should now be removed
534 // from the program. Insert the dead ones in the FunctionsToRemove set.
535 for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
536 CallGraphNode *CGN = I->second;
537 Function *F = CGN->getFunction();
538 if (!F || F->isDeclaration())
541 // Handle the case when this function is called and we only want to care
542 // about always-inline functions. This is a bit of a hack to share code
543 // between here and the InlineAlways pass.
544 if (AlwaysInlineOnly &&
545 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
546 Attribute::AlwaysInline))
549 // If the only remaining users of the function are dead constants, remove
551 F->removeDeadConstantUsers();
553 if (!F->isDefTriviallyDead())
556 // Remove any call graph edges from the function to its callees.
557 CGN->removeAllCalledFunctions();
559 // Remove any edges from the external node to the function's call graph
560 // node. These edges might have been made irrelegant due to
561 // optimization of the program.
562 CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
564 // Removing the node for callee from the call graph and delete it.
565 FunctionsToRemove.push_back(CGN);
567 if (FunctionsToRemove.empty())
570 // Now that we know which functions to delete, do so. We didn't want to do
571 // this inline, because that would invalidate our CallGraph::iterator
574 // Note that it doesn't matter that we are iterating over a non-stable order
575 // here to do this, it doesn't matter which order the functions are deleted
577 array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
578 FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
579 FunctionsToRemove.end()),
580 FunctionsToRemove.end());
581 for (SmallVectorImpl<CallGraphNode *>::iterator I = FunctionsToRemove.begin(),
582 E = FunctionsToRemove.end();
584 delete CG.removeFunctionFromModule(*I);