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/Module.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Analysis/CallGraph.h"
21 #include "llvm/Analysis/InlineCost.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/IPO/InlinerPass.h"
24 #include "llvm/Transforms/Utils/Cloning.h"
25 #include "llvm/Transforms/Utils/Local.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/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/Statistic.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");
41 InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
42 cl::desc("Control the amount of inlining to perform (default = 225)"));
45 HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
46 cl::desc("Threshold for inlining functions with inline hint"));
48 // Threshold to use when optsize is specified (and there is no -inline-limit).
49 const int OptSizeThreshold = 75;
51 Inliner::Inliner(char &ID)
52 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
54 Inliner::Inliner(char &ID, int Threshold)
55 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
56 InlineLimit : Threshold) {}
58 /// getAnalysisUsage - For this class, we declare that we require and preserve
59 /// the call graph. If the derived class implements this method, it should
60 /// always explicitly call the implementation here.
61 void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
62 CallGraphSCCPass::getAnalysisUsage(Info);
66 typedef DenseMap<const ArrayType*, std::vector<AllocaInst*> >
67 InlinedArrayAllocasTy;
69 /// InlineCallIfPossible - If it is possible to inline the specified call site,
70 /// do so and update the CallGraph for this operation.
72 /// This function also does some basic book-keeping to update the IR. The
73 /// InlinedArrayAllocas map keeps track of any allocas that are already
74 /// available from other functions inlined into the caller. If we are able to
75 /// inline this call site we attempt to reuse already available allocas or add
76 /// any new allocas to the set if not possible.
77 static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
78 InlinedArrayAllocasTy &InlinedArrayAllocas) {
79 Function *Callee = CS.getCalledFunction();
80 Function *Caller = CS.getCaller();
82 // Try to inline the function. Get the list of static allocas that were
84 if (!InlineFunction(CS, IFI))
87 // If the inlined function had a higher stack protection level than the
88 // calling function, then bump up the caller's stack protection level.
89 if (Callee->hasFnAttr(Attribute::StackProtectReq))
90 Caller->addFnAttr(Attribute::StackProtectReq);
91 else if (Callee->hasFnAttr(Attribute::StackProtect) &&
92 !Caller->hasFnAttr(Attribute::StackProtectReq))
93 Caller->addFnAttr(Attribute::StackProtect);
96 // Look at all of the allocas that we inlined through this call site. If we
97 // have already inlined other allocas through other calls into this function,
98 // then we know that they have disjoint lifetimes and that we can merge them.
100 // There are many heuristics possible for merging these allocas, and the
101 // different options have different tradeoffs. One thing that we *really*
102 // don't want to hurt is SRoA: once inlining happens, often allocas are no
103 // longer address taken and so they can be promoted.
105 // Our "solution" for that is to only merge allocas whose outermost type is an
106 // array type. These are usually not promoted because someone is using a
107 // variable index into them. These are also often the most important ones to
110 // A better solution would be to have real memory lifetime markers in the IR
111 // and not have the inliner do any merging of allocas at all. This would
112 // allow the backend to do proper stack slot coloring of all allocas that
113 // *actually make it to the backend*, which is really what we want.
115 // Because we don't have this information, we do this simple and useful hack.
117 SmallPtrSet<AllocaInst*, 16> UsedAllocas;
119 // Loop over all the allocas we have so far and see if they can be merged with
120 // a previously inlined alloca. If not, remember that we had it.
121 for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
122 AllocaNo != e; ++AllocaNo) {
123 AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
125 // Don't bother trying to merge array allocations (they will usually be
126 // canonicalized to be an allocation *of* an array), or allocations whose
127 // type is not itself an array (because we're afraid of pessimizing SRoA).
128 const ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
129 if (ATy == 0 || AI->isArrayAllocation())
132 // Get the list of all available allocas for this array type.
133 std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
135 // Loop over the allocas in AllocasForType to see if we can reuse one. Note
136 // that we have to be careful not to reuse the same "available" alloca for
137 // multiple different allocas that we just inlined, we use the 'UsedAllocas'
138 // set to keep track of which "available" allocas are being used by this
139 // function. Also, AllocasForType can be empty of course!
140 bool MergedAwayAlloca = false;
141 for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
142 AllocaInst *AvailableAlloca = AllocasForType[i];
144 // The available alloca has to be in the right function, not in some other
145 // function in this SCC.
146 if (AvailableAlloca->getParent() != AI->getParent())
149 // If the inlined function already uses this alloca then we can't reuse
151 if (!UsedAllocas.insert(AvailableAlloca))
154 // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
156 DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
157 << *AvailableAlloca << '\n');
159 AI->replaceAllUsesWith(AvailableAlloca);
160 AI->eraseFromParent();
161 MergedAwayAlloca = true;
163 IFI.StaticAllocas[AllocaNo] = 0;
167 // If we already nuked the alloca, we're done with it.
168 if (MergedAwayAlloca)
171 // If we were unable to merge away the alloca either because there are no
172 // allocas of the right type available or because we reused them all
173 // already, remember that this alloca came from an inlined function and mark
174 // it used so we don't reuse it for other allocas from this inline
176 AllocasForType.push_back(AI);
177 UsedAllocas.insert(AI);
183 unsigned Inliner::getInlineThreshold(CallSite CS) const {
184 int thres = InlineThreshold;
186 // Listen to optsize when -inline-limit is not given.
187 Function *Caller = CS.getCaller();
188 if (Caller && !Caller->isDeclaration() &&
189 Caller->hasFnAttr(Attribute::OptimizeForSize) &&
190 InlineLimit.getNumOccurrences() == 0)
191 thres = OptSizeThreshold;
193 // Listen to inlinehint when it would increase the threshold.
194 Function *Callee = CS.getCalledFunction();
195 if (HintThreshold > thres && Callee && !Callee->isDeclaration() &&
196 Callee->hasFnAttr(Attribute::InlineHint))
197 thres = HintThreshold;
202 /// shouldInline - Return true if the inliner should attempt to inline
203 /// at the given CallSite.
204 bool Inliner::shouldInline(CallSite CS) {
205 InlineCost IC = getInlineCost(CS);
208 DEBUG(dbgs() << " Inlining: cost=always"
209 << ", Call: " << *CS.getInstruction() << "\n");
214 DEBUG(dbgs() << " NOT Inlining: cost=never"
215 << ", Call: " << *CS.getInstruction() << "\n");
219 int Cost = IC.getValue();
220 Function *Caller = CS.getCaller();
221 int CurrentThreshold = getInlineThreshold(CS);
222 float FudgeFactor = getInlineFudgeFactor(CS);
223 int AdjThreshold = (int)(CurrentThreshold * FudgeFactor);
224 if (Cost >= AdjThreshold) {
225 DEBUG(dbgs() << " NOT Inlining: cost=" << Cost
226 << ", thres=" << AdjThreshold
227 << ", Call: " << *CS.getInstruction() << "\n");
231 // Try to detect the case where the current inlining candidate caller
232 // (call it B) is a static function and is an inlining candidate elsewhere,
233 // and the current candidate callee (call it C) is large enough that
234 // inlining it into B would make B too big to inline later. In these
235 // circumstances it may be best not to inline C into B, but to inline B
237 if (Caller->hasLocalLinkage()) {
238 int TotalSecondaryCost = 0;
239 bool outerCallsFound = false;
240 bool allOuterCallsWillBeInlined = true;
241 bool someOuterCallWouldNotBeInlined = false;
242 for (Value::use_iterator I = Caller->use_begin(), E =Caller->use_end();
246 // If this isn't a call to Caller (it could be some other sort
247 // of reference) skip it.
248 if (!CS2 || CS2.getCalledFunction() != Caller)
251 InlineCost IC2 = getInlineCost(CS2);
253 allOuterCallsWillBeInlined = false;
254 if (IC2.isAlways() || IC2.isNever())
257 outerCallsFound = true;
258 int Cost2 = IC2.getValue();
259 int CurrentThreshold2 = getInlineThreshold(CS2);
260 float FudgeFactor2 = getInlineFudgeFactor(CS2);
262 if (Cost2 >= (int)(CurrentThreshold2 * FudgeFactor2))
263 allOuterCallsWillBeInlined = false;
265 // See if we have this case. We subtract off the penalty
266 // for the call instruction, which we would be deleting.
267 if (Cost2 < (int)(CurrentThreshold2 * FudgeFactor2) &&
268 Cost2 + Cost - (InlineConstants::CallPenalty + 1) >=
269 (int)(CurrentThreshold2 * FudgeFactor2)) {
270 someOuterCallWouldNotBeInlined = true;
271 TotalSecondaryCost += Cost2;
274 // If all outer calls to Caller would get inlined, the cost for the last
275 // one is set very low by getInlineCost, in anticipation that Caller will
276 // be removed entirely. We did not account for this above unless there
277 // is only one caller of Caller.
278 if (allOuterCallsWillBeInlined && Caller->use_begin() != Caller->use_end())
279 TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
281 if (outerCallsFound && someOuterCallWouldNotBeInlined &&
282 TotalSecondaryCost < Cost) {
283 DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction() <<
284 " Cost = " << Cost <<
285 ", outer Cost = " << TotalSecondaryCost << '\n');
290 DEBUG(dbgs() << " Inlining: cost=" << Cost
291 << ", thres=" << AdjThreshold
292 << ", Call: " << *CS.getInstruction() << '\n');
296 /// InlineHistoryIncludes - Return true if the specified inline history ID
297 /// indicates an inline history that includes the specified function.
298 static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
299 const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
300 while (InlineHistoryID != -1) {
301 assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
302 "Invalid inline history ID");
303 if (InlineHistory[InlineHistoryID].first == F)
305 InlineHistoryID = InlineHistory[InlineHistoryID].second;
311 bool Inliner::runOnSCC(CallGraphSCC &SCC) {
312 CallGraph &CG = getAnalysis<CallGraph>();
313 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
315 SmallPtrSet<Function*, 8> SCCFunctions;
316 DEBUG(dbgs() << "Inliner visiting SCC:");
317 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
318 Function *F = (*I)->getFunction();
319 if (F) SCCFunctions.insert(F);
320 DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
323 // Scan through and identify all call sites ahead of time so that we only
324 // inline call sites in the original functions, not call sites that result
325 // from inlining other functions.
326 SmallVector<std::pair<CallSite, int>, 16> CallSites;
328 // When inlining a callee produces new call sites, we want to keep track of
329 // the fact that they were inlined from the callee. This allows us to avoid
330 // infinite inlining in some obscure cases. To represent this, we use an
331 // index into the InlineHistory vector.
332 SmallVector<std::pair<Function*, int>, 8> InlineHistory;
334 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
335 Function *F = (*I)->getFunction();
338 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
339 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
340 CallSite CS(cast<Value>(I));
341 // If this isn't a call, or it is a call to an intrinsic, it can
343 if (!CS || isa<IntrinsicInst>(I))
346 // If this is a direct call to an external function, we can never inline
347 // it. If it is an indirect call, inlining may resolve it to be a
348 // direct call, so we keep it.
349 if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
352 CallSites.push_back(std::make_pair(CS, -1));
356 DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
358 // If there are no calls in this function, exit early.
359 if (CallSites.empty())
362 // Now that we have all of the call sites, move the ones to functions in the
363 // current SCC to the end of the list.
364 unsigned FirstCallInSCC = CallSites.size();
365 for (unsigned i = 0; i < FirstCallInSCC; ++i)
366 if (Function *F = CallSites[i].first.getCalledFunction())
367 if (SCCFunctions.count(F))
368 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
371 InlinedArrayAllocasTy InlinedArrayAllocas;
372 InlineFunctionInfo InlineInfo(&CG, TD);
374 // Now that we have all of the call sites, loop over them and inline them if
375 // it looks profitable to do so.
376 bool Changed = false;
380 // Iterate over the outer loop because inlining functions can cause indirect
381 // calls to become direct calls.
382 for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
383 CallSite CS = CallSites[CSi].first;
385 Function *Caller = CS.getCaller();
386 Function *Callee = CS.getCalledFunction();
388 // If this call site is dead and it is to a readonly function, we should
389 // just delete the call instead of trying to inline it, regardless of
390 // size. This happens because IPSCCP propagates the result out of the
391 // call and then we're left with the dead call.
392 if (isInstructionTriviallyDead(CS.getInstruction())) {
393 DEBUG(dbgs() << " -> Deleting dead call: "
394 << *CS.getInstruction() << "\n");
395 // Update the call graph by deleting the edge from Callee to Caller.
396 CG[Caller]->removeCallEdgeFor(CS);
397 CS.getInstruction()->eraseFromParent();
399 // Update the cached cost info with the missing call
400 growCachedCostInfo(Caller, NULL);
402 // We can only inline direct calls to non-declarations.
403 if (Callee == 0 || Callee->isDeclaration()) continue;
405 // If this call site was obtained by inlining another function, verify
406 // that the include path for the function did not include the callee
407 // itself. If so, we'd be recursively inlining the same function,
408 // which would provide the same callsites, which would cause us to
409 // infinitely inline.
410 int InlineHistoryID = CallSites[CSi].second;
411 if (InlineHistoryID != -1 &&
412 InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
416 // If the policy determines that we should inline this function,
418 if (!shouldInline(CS))
421 // Attempt to inline the function.
422 if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas))
426 // If inlining this function gave us any new call sites, throw them
427 // onto our worklist to process. They are useful inline candidates.
428 if (!InlineInfo.InlinedCalls.empty()) {
429 // Create a new inline history entry for this, so that we remember
430 // that these new callsites came about due to inlining Callee.
431 int NewHistoryID = InlineHistory.size();
432 InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
434 for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
436 Value *Ptr = InlineInfo.InlinedCalls[i];
437 CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
441 // Update the cached cost info with the inlined call.
442 growCachedCostInfo(Caller, Callee);
445 // If we inlined or deleted the last possible call site to the function,
446 // delete the function body now.
447 if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
448 // TODO: Can remove if in SCC now.
449 !SCCFunctions.count(Callee) &&
451 // The function may be apparently dead, but if there are indirect
452 // callgraph references to the node, we cannot delete it yet, this
453 // could invalidate the CGSCC iterator.
454 CG[Callee]->getNumReferences() == 0) {
455 DEBUG(dbgs() << " -> Deleting dead function: "
456 << Callee->getName() << "\n");
457 CallGraphNode *CalleeNode = CG[Callee];
459 // Remove any call graph edges from the callee to its callees.
460 CalleeNode->removeAllCalledFunctions();
462 resetCachedCostInfo(Callee);
464 // Removing the node for callee from the call graph and delete it.
465 delete CG.removeFunctionFromModule(CalleeNode);
469 // Remove this call site from the list. If possible, use
470 // swap/pop_back for efficiency, but do not use it if doing so would
471 // move a call site to a function in this SCC before the
472 // 'FirstCallInSCC' barrier.
473 if (SCC.isSingular()) {
474 CallSites[CSi] = CallSites.back();
475 CallSites.pop_back();
477 CallSites.erase(CallSites.begin()+CSi);
484 } while (LocalChange);
489 // doFinalization - Remove now-dead linkonce functions at the end of
490 // processing to avoid breaking the SCC traversal.
491 bool Inliner::doFinalization(CallGraph &CG) {
492 return removeDeadFunctions(CG);
495 /// removeDeadFunctions - Remove dead functions that are not included in
496 /// DNR (Do Not Remove) list.
497 bool Inliner::removeDeadFunctions(CallGraph &CG,
498 SmallPtrSet<const Function *, 16> *DNR) {
499 SmallPtrSet<CallGraphNode*, 16> FunctionsToRemove;
501 // Scan for all of the functions, looking for ones that should now be removed
502 // from the program. Insert the dead ones in the FunctionsToRemove set.
503 for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
504 CallGraphNode *CGN = I->second;
505 if (CGN->getFunction() == 0)
508 Function *F = CGN->getFunction();
510 // If the only remaining users of the function are dead constants, remove
512 F->removeDeadConstantUsers();
514 if (DNR && DNR->count(F))
516 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
517 !F->hasAvailableExternallyLinkage())
522 // Remove any call graph edges from the function to its callees.
523 CGN->removeAllCalledFunctions();
525 // Remove any edges from the external node to the function's call graph
526 // node. These edges might have been made irrelegant due to
527 // optimization of the program.
528 CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
530 // Removing the node for callee from the call graph and delete it.
531 FunctionsToRemove.insert(CGN);
534 // Now that we know which functions to delete, do so. We didn't want to do
535 // this inline, because that would invalidate our CallGraph::iterator
538 // Note that it doesn't matter that we are iterating over a non-stable set
539 // here to do this, it doesn't matter which order the functions are deleted
541 bool Changed = false;
542 for (SmallPtrSet<CallGraphNode*, 16>::iterator I = FunctionsToRemove.begin(),
543 E = FunctionsToRemove.end(); I != E; ++I) {
544 resetCachedCostInfo((*I)->getFunction());
545 delete CG.removeFunctionFromModule(*I);