Move the InlineCost code from Transforms/Utils to Analysis.
[oota-llvm.git] / lib / Transforms / IPO / Inliner.cpp
1 //===- Inliner.cpp - Code common to all inliners --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements 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.
13 //
14 //===----------------------------------------------------------------------===//
15
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/Support/CallSite.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Transforms/IPO/InlinerPass.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include <set>
32 using namespace llvm;
33
34 STATISTIC(NumInlined, "Number of functions inlined");
35 STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
36 STATISTIC(NumMergedAllocas, "Number of allocas merged together");
37
38 static cl::opt<int>
39 InlineLimit("inline-threshold", cl::Hidden, cl::init(200), cl::ZeroOrMore,
40         cl::desc("Control the amount of inlining to perform (default = 200)"));
41
42 Inliner::Inliner(void *ID) 
43   : CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
44
45 Inliner::Inliner(void *ID, int Threshold) 
46   : CallGraphSCCPass(ID), InlineThreshold(Threshold) {}
47
48 /// getAnalysisUsage - For this class, we declare that we require and preserve
49 /// the call graph.  If the derived class implements this method, it should
50 /// always explicitly call the implementation here.
51 void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
52   CallGraphSCCPass::getAnalysisUsage(Info);
53 }
54
55
56 typedef DenseMap<const ArrayType*, std::vector<AllocaInst*> >
57 InlinedArrayAllocasTy;
58
59 /// InlineCallIfPossible - If it is possible to inline the specified call site,
60 /// do so and update the CallGraph for this operation.
61 ///
62 /// This function also does some basic book-keeping to update the IR.  The
63 /// InlinedArrayAllocas map keeps track of any allocas that are already
64 /// available from other  functions inlined into the caller.  If we are able to
65 /// inline this call site we attempt to reuse already available allocas or add
66 /// any new allocas to the set if not possible.
67 static bool InlineCallIfPossible(CallSite CS, CallGraph &CG,
68                                  const TargetData *TD,
69                                  InlinedArrayAllocasTy &InlinedArrayAllocas) {
70   Function *Callee = CS.getCalledFunction();
71   Function *Caller = CS.getCaller();
72
73   // Try to inline the function.  Get the list of static allocas that were
74   // inlined.
75   SmallVector<AllocaInst*, 16> StaticAllocas;
76   if (!InlineFunction(CS, &CG, TD, &StaticAllocas))
77     return false;
78
79   // If the inlined function had a higher stack protection level than the
80   // calling function, then bump up the caller's stack protection level.
81   if (Callee->hasFnAttr(Attribute::StackProtectReq))
82     Caller->addFnAttr(Attribute::StackProtectReq);
83   else if (Callee->hasFnAttr(Attribute::StackProtect) &&
84            !Caller->hasFnAttr(Attribute::StackProtectReq))
85     Caller->addFnAttr(Attribute::StackProtect);
86
87   
88   // Look at all of the allocas that we inlined through this call site.  If we
89   // have already inlined other allocas through other calls into this function,
90   // then we know that they have disjoint lifetimes and that we can merge them.
91   //
92   // There are many heuristics possible for merging these allocas, and the
93   // different options have different tradeoffs.  One thing that we *really*
94   // don't want to hurt is SRoA: once inlining happens, often allocas are no
95   // longer address taken and so they can be promoted.
96   //
97   // Our "solution" for that is to only merge allocas whose outermost type is an
98   // array type.  These are usually not promoted because someone is using a
99   // variable index into them.  These are also often the most important ones to
100   // merge.
101   //
102   // A better solution would be to have real memory lifetime markers in the IR
103   // and not have the inliner do any merging of allocas at all.  This would
104   // allow the backend to do proper stack slot coloring of all allocas that
105   // *actually make it to the backend*, which is really what we want.
106   //
107   // Because we don't have this information, we do this simple and useful hack.
108   //
109   SmallPtrSet<AllocaInst*, 16> UsedAllocas;
110   
111   // Loop over all the allocas we have so far and see if they can be merged with
112   // a previously inlined alloca.  If not, remember that we had it.
113   for (unsigned AllocaNo = 0, e = StaticAllocas.size();
114        AllocaNo != e; ++AllocaNo) {
115     AllocaInst *AI = StaticAllocas[AllocaNo];
116     
117     // Don't bother trying to merge array allocations (they will usually be
118     // canonicalized to be an allocation *of* an array), or allocations whose
119     // type is not itself an array (because we're afraid of pessimizing SRoA).
120     const ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
121     if (ATy == 0 || AI->isArrayAllocation())
122       continue;
123     
124     // Get the list of all available allocas for this array type.
125     std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
126     
127     // Loop over the allocas in AllocasForType to see if we can reuse one.  Note
128     // that we have to be careful not to reuse the same "available" alloca for
129     // multiple different allocas that we just inlined, we use the 'UsedAllocas'
130     // set to keep track of which "available" allocas are being used by this
131     // function.  Also, AllocasForType can be empty of course!
132     bool MergedAwayAlloca = false;
133     for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
134       AllocaInst *AvailableAlloca = AllocasForType[i];
135       
136       // The available alloca has to be in the right function, not in some other
137       // function in this SCC.
138       if (AvailableAlloca->getParent() != AI->getParent())
139         continue;
140       
141       // If the inlined function already uses this alloca then we can't reuse
142       // it.
143       if (!UsedAllocas.insert(AvailableAlloca))
144         continue;
145       
146       // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
147       // success!
148       DEBUG(errs() << "    ***MERGED ALLOCA: " << *AI);
149       
150       AI->replaceAllUsesWith(AvailableAlloca);
151       AI->eraseFromParent();
152       MergedAwayAlloca = true;
153       ++NumMergedAllocas;
154       break;
155     }
156
157     // If we already nuked the alloca, we're done with it.
158     if (MergedAwayAlloca)
159       continue;
160
161     // If we were unable to merge away the alloca either because there are no
162     // allocas of the right type available or because we reused them all
163     // already, remember that this alloca came from an inlined function and mark
164     // it used so we don't reuse it for other allocas from this inline
165     // operation.
166     AllocasForType.push_back(AI);
167     UsedAllocas.insert(AI);
168   }
169   
170   return true;
171 }
172         
173 /// shouldInline - Return true if the inliner should attempt to inline
174 /// at the given CallSite.
175 bool Inliner::shouldInline(CallSite CS) {
176   InlineCost IC = getInlineCost(CS);
177   
178   if (IC.isAlways()) {
179     DEBUG(errs() << "    Inlining: cost=always"
180           << ", Call: " << *CS.getInstruction() << "\n");
181     return true;
182   }
183   
184   if (IC.isNever()) {
185     DEBUG(errs() << "    NOT Inlining: cost=never"
186           << ", Call: " << *CS.getInstruction() << "\n");
187     return false;
188   }
189   
190   int Cost = IC.getValue();
191   int CurrentThreshold = InlineThreshold;
192   Function *Caller = CS.getCaller();
193   if (Caller && !Caller->isDeclaration() &&
194       Caller->hasFnAttr(Attribute::OptimizeForSize) &&
195       InlineLimit.getNumOccurrences() == 0 &&
196       InlineThreshold != 50)
197     CurrentThreshold = 50;
198   
199   float FudgeFactor = getInlineFudgeFactor(CS);
200   if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {
201     DEBUG(errs() << "    NOT Inlining: cost=" << Cost
202           << ", Call: " << *CS.getInstruction() << "\n");
203     return false;
204   }
205   
206   // Try to detect the case where the current inlining candidate caller
207   // (call it B) is a static function and is an inlining candidate elsewhere,
208   // and the current candidate callee (call it C) is large enough that
209   // inlining it into B would make B too big to inline later.  In these
210   // circumstances it may be best not to inline C into B, but to inline B
211   // into its callers.
212   if (Caller->hasLocalLinkage()) {
213     int TotalSecondaryCost = 0;
214     bool outerCallsFound = false;
215     bool allOuterCallsWillBeInlined = true;
216     bool someOuterCallWouldNotBeInlined = false;
217     for (Value::use_iterator I = Caller->use_begin(), E =Caller->use_end(); 
218          I != E; ++I) {
219       CallSite CS2 = CallSite::get(*I);
220
221       // If this isn't a call to Caller (it could be some other sort
222       // of reference) skip it.
223       if (CS2.getInstruction() == 0 || CS2.getCalledFunction() != Caller)
224         continue;
225
226       InlineCost IC2 = getInlineCost(CS2);
227       if (IC2.isNever())
228         allOuterCallsWillBeInlined = false;
229       if (IC2.isAlways() || IC2.isNever())
230         continue;
231
232       outerCallsFound = true;
233       int Cost2 = IC2.getValue();
234       int CurrentThreshold2 = InlineThreshold;
235       Function *Caller2 = CS2.getCaller();
236       if (Caller2 && !Caller2->isDeclaration() &&
237           Caller2->hasFnAttr(Attribute::OptimizeForSize) &&
238           InlineThreshold != 50)
239         CurrentThreshold2 = 50;
240
241       float FudgeFactor2 = getInlineFudgeFactor(CS2);
242
243       if (Cost2 >= (int)(CurrentThreshold2 * FudgeFactor2))
244         allOuterCallsWillBeInlined = false;
245
246       // See if we have this case.  We subtract off the penalty
247       // for the call instruction, which we would be deleting.
248       if (Cost2 < (int)(CurrentThreshold2 * FudgeFactor2) &&
249           Cost2 + Cost - (InlineConstants::CallPenalty + 1) >= 
250                 (int)(CurrentThreshold2 * FudgeFactor2)) {
251         someOuterCallWouldNotBeInlined = true;
252         TotalSecondaryCost += Cost2;
253       }
254     }
255     // If all outer calls to Caller would get inlined, the cost for the last
256     // one is set very low by getInlineCost, in anticipation that Caller will
257     // be removed entirely.  We did not account for this above unless there
258     // is only one caller of Caller.
259     if (allOuterCallsWillBeInlined && Caller->use_begin() != Caller->use_end())
260       TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
261
262     if (outerCallsFound && someOuterCallWouldNotBeInlined && 
263         TotalSecondaryCost < Cost) {
264       DEBUG(errs() << "    NOT Inlining: " << *CS.getInstruction() << 
265            " Cost = " << Cost << 
266            ", outer Cost = " << TotalSecondaryCost << '\n');
267       return false;
268     }
269   }
270
271   DEBUG(errs() << "    Inlining: cost=" << Cost
272         << ", Call: " << *CS.getInstruction() << '\n');
273   return true;
274 }
275
276 bool Inliner::runOnSCC(std::vector<CallGraphNode*> &SCC) {
277   CallGraph &CG = getAnalysis<CallGraph>();
278   const TargetData *TD = getAnalysisIfAvailable<TargetData>();
279
280   SmallPtrSet<Function*, 8> SCCFunctions;
281   DEBUG(errs() << "Inliner visiting SCC:");
282   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
283     Function *F = SCC[i]->getFunction();
284     if (F) SCCFunctions.insert(F);
285     DEBUG(errs() << " " << (F ? F->getName() : "INDIRECTNODE"));
286   }
287
288   // Scan through and identify all call sites ahead of time so that we only
289   // inline call sites in the original functions, not call sites that result
290   // from inlining other functions.
291   SmallVector<CallSite, 16> CallSites;
292
293   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
294     Function *F = SCC[i]->getFunction();
295     if (!F) continue;
296     
297     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
298       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
299         CallSite CS = CallSite::get(I);
300         // If this isn't a call, or it is a call to an intrinsic, it can
301         // never be inlined.
302         if (CS.getInstruction() == 0 || isa<IntrinsicInst>(I))
303           continue;
304         
305         // If this is a direct call to an external function, we can never inline
306         // it.  If it is an indirect call, inlining may resolve it to be a
307         // direct call, so we keep it.
308         if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
309           continue;
310         
311         CallSites.push_back(CS);
312       }
313   }
314
315   DEBUG(errs() << ": " << CallSites.size() << " call sites.\n");
316
317   // Now that we have all of the call sites, move the ones to functions in the
318   // current SCC to the end of the list.
319   unsigned FirstCallInSCC = CallSites.size();
320   for (unsigned i = 0; i < FirstCallInSCC; ++i)
321     if (Function *F = CallSites[i].getCalledFunction())
322       if (SCCFunctions.count(F))
323         std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
324
325   
326   InlinedArrayAllocasTy InlinedArrayAllocas;
327   
328   // Now that we have all of the call sites, loop over them and inline them if
329   // it looks profitable to do so.
330   bool Changed = false;
331   bool LocalChange;
332   do {
333     LocalChange = false;
334     // Iterate over the outer loop because inlining functions can cause indirect
335     // calls to become direct calls.
336     for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
337       CallSite CS = CallSites[CSi];
338       
339       Function *Callee = CS.getCalledFunction();
340       // We can only inline direct calls to non-declarations.
341       if (Callee == 0 || Callee->isDeclaration()) continue;
342       
343       // If the policy determines that we should inline this function,
344       // try to do so.
345       if (!shouldInline(CS))
346         continue;
347
348       Function *Caller = CS.getCaller();
349       // Attempt to inline the function...
350       if (!InlineCallIfPossible(CS, CG, TD, InlinedArrayAllocas))
351         continue;
352       
353       // If we inlined the last possible call site to the function, delete the
354       // function body now.
355       if (Callee->use_empty() && Callee->hasLocalLinkage() &&
356           // TODO: Can remove if in SCC now.
357           !SCCFunctions.count(Callee) &&
358           
359           // The function may be apparently dead, but if there are indirect
360           // callgraph references to the node, we cannot delete it yet, this
361           // could invalidate the CGSCC iterator.
362           CG[Callee]->getNumReferences() == 0) {
363         DEBUG(errs() << "    -> Deleting dead function: "
364               << Callee->getName() << "\n");
365         CallGraphNode *CalleeNode = CG[Callee];
366         
367         // Remove any call graph edges from the callee to its callees.
368         CalleeNode->removeAllCalledFunctions();
369         
370         resetCachedCostInfo(Callee);
371         
372         // Removing the node for callee from the call graph and delete it.
373         delete CG.removeFunctionFromModule(CalleeNode);
374         ++NumDeleted;
375       }
376       
377       // Remove any cached cost info for this caller, as inlining the
378       // callee has increased the size of the caller (which may be the
379       // same as the callee).
380       resetCachedCostInfo(Caller);
381
382       // Remove this call site from the list.  If possible, use 
383       // swap/pop_back for efficiency, but do not use it if doing so would
384       // move a call site to a function in this SCC before the
385       // 'FirstCallInSCC' barrier.
386       if (SCC.size() == 1) {
387         std::swap(CallSites[CSi], CallSites.back());
388         CallSites.pop_back();
389       } else {
390         CallSites.erase(CallSites.begin()+CSi);
391       }
392       --CSi;
393
394       ++NumInlined;
395       Changed = true;
396       LocalChange = true;
397     }
398   } while (LocalChange);
399
400   return Changed;
401 }
402
403 // doFinalization - Remove now-dead linkonce functions at the end of
404 // processing to avoid breaking the SCC traversal.
405 bool Inliner::doFinalization(CallGraph &CG) {
406   return removeDeadFunctions(CG);
407 }
408
409 /// removeDeadFunctions - Remove dead functions that are not included in
410 /// DNR (Do Not Remove) list.
411 bool Inliner::removeDeadFunctions(CallGraph &CG, 
412                                   SmallPtrSet<const Function *, 16> *DNR) {
413   SmallPtrSet<CallGraphNode*, 16> FunctionsToRemove;
414
415   // Scan for all of the functions, looking for ones that should now be removed
416   // from the program.  Insert the dead ones in the FunctionsToRemove set.
417   for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
418     CallGraphNode *CGN = I->second;
419     if (CGN->getFunction() == 0)
420       continue;
421     
422     Function *F = CGN->getFunction();
423     
424     // If the only remaining users of the function are dead constants, remove
425     // them.
426     F->removeDeadConstantUsers();
427
428     if (DNR && DNR->count(F))
429       continue;
430     if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
431         !F->hasAvailableExternallyLinkage())
432       continue;
433     if (!F->use_empty())
434       continue;
435     
436     // Remove any call graph edges from the function to its callees.
437     CGN->removeAllCalledFunctions();
438
439     // Remove any edges from the external node to the function's call graph
440     // node.  These edges might have been made irrelegant due to
441     // optimization of the program.
442     CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
443
444     // Removing the node for callee from the call graph and delete it.
445     FunctionsToRemove.insert(CGN);
446   }
447
448   // Now that we know which functions to delete, do so.  We didn't want to do
449   // this inline, because that would invalidate our CallGraph::iterator
450   // objects. :(
451   //
452   // Note that it doesn't matter that we are iterating over a non-stable set
453   // here to do this, it doesn't matter which order the functions are deleted
454   // in.
455   bool Changed = false;
456   for (SmallPtrSet<CallGraphNode*, 16>::iterator I = FunctionsToRemove.begin(),
457        E = FunctionsToRemove.end(); I != E; ++I) {
458     resetCachedCostInfo((*I)->getFunction());
459     delete CG.removeFunctionFromModule(*I);
460     ++NumDeleted;
461     Changed = true;
462   }
463
464   return Changed;
465 }