second patch to fix PR992/993.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "Inliner.h"
17 #include "llvm/Module.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Support/CallSite.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/Statistic.h"
25 #include <iostream>
26 #include <set>
27 using namespace llvm;
28
29 namespace {
30   Statistic<> NumInlined("inline", "Number of functions inlined");
31   Statistic<> NumDeleted("inline",
32                        "Number of functions deleted because all callers found");
33   cl::opt<unsigned>             // FIXME: 200 is VERY conservative
34   InlineLimit("inline-threshold", cl::Hidden, cl::init(200),
35         cl::desc("Control the amount of inlining to perform (default = 200)"));
36 }
37
38 Inliner::Inliner() : InlineThreshold(InlineLimit) {}
39
40 // InlineCallIfPossible - If it is possible to inline the specified call site,
41 // do so and update the CallGraph for this operation.
42 static bool InlineCallIfPossible(CallSite CS, CallGraph &CG,
43                                  const std::set<Function*> &SCCFunctions) {
44   Function *Callee = CS.getCalledFunction();
45   if (!InlineFunction(CS, &CG)) return false;
46
47   // If we inlined the last possible call site to the function, delete the
48   // function body now.
49   if (Callee->use_empty() && Callee->hasInternalLinkage() &&
50       !SCCFunctions.count(Callee)) {
51     DEBUG(std::cerr << "    -> Deleting dead function: "
52                     << Callee->getName() << "\n");
53
54     // Remove any call graph edges from the callee to its callees.
55     CallGraphNode *CalleeNode = CG[Callee];
56     while (CalleeNode->begin() != CalleeNode->end())
57       CalleeNode->removeCallEdgeTo((CalleeNode->end()-1)->second);
58
59     // Removing the node for callee from the call graph and delete it.
60     delete CG.removeFunctionFromModule(CalleeNode);
61     ++NumDeleted;
62   }
63   return true;
64 }
65
66 bool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {
67   CallGraph &CG = getAnalysis<CallGraph>();
68
69   std::set<Function*> SCCFunctions;
70   DEBUG(std::cerr << "Inliner visiting SCC:");
71   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
72     Function *F = SCC[i]->getFunction();
73     if (F) SCCFunctions.insert(F);
74     DEBUG(std::cerr << " " << (F ? F->getName() : "INDIRECTNODE"));
75   }
76
77   // Scan through and identify all call sites ahead of time so that we only
78   // inline call sites in the original functions, not call sites that result
79   // from inlining other functions.
80   std::vector<CallSite> CallSites;
81
82   for (unsigned i = 0, e = SCC.size(); i != e; ++i)
83     if (Function *F = SCC[i]->getFunction())
84       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
85         for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
86           CallSite CS = CallSite::get(I);
87           if (CS.getInstruction() && (!CS.getCalledFunction() ||
88                                       !CS.getCalledFunction()->isExternal()))
89             CallSites.push_back(CS);
90         }
91
92   DEBUG(std::cerr << ": " << CallSites.size() << " call sites.\n");
93
94   // Now that we have all of the call sites, move the ones to functions in the
95   // current SCC to the end of the list.
96   unsigned FirstCallInSCC = CallSites.size();
97   for (unsigned i = 0; i < FirstCallInSCC; ++i)
98     if (Function *F = CallSites[i].getCalledFunction())
99       if (SCCFunctions.count(F))
100         std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
101
102   // Now that we have all of the call sites, loop over them and inline them if
103   // it looks profitable to do so.
104   bool Changed = false;
105   bool LocalChange;
106   do {
107     LocalChange = false;
108     // Iterate over the outer loop because inlining functions can cause indirect
109     // calls to become direct calls.
110     for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)
111       if (Function *Callee = CallSites[CSi].getCalledFunction()) {
112         // Calls to external functions are never inlinable.
113         if (Callee->isExternal() ||
114             CallSites[CSi].getInstruction()->getParent()->getParent() ==Callee){
115           if (SCC.size() == 1) {
116             std::swap(CallSites[CSi], CallSites.back());
117             CallSites.pop_back();
118           } else {
119             // Keep the 'in SCC / not in SCC' boundary correct.
120             CallSites.erase(CallSites.begin()+CSi);
121           }
122           --CSi;
123           continue;
124         }
125
126         // If the policy determines that we should inline this function,
127         // try to do so.
128         CallSite CS = CallSites[CSi];
129         int InlineCost = getInlineCost(CS);
130         if (InlineCost >= (int)InlineThreshold) {
131           DEBUG(std::cerr << "    NOT Inlining: cost=" << InlineCost
132                 << ", Call: " << *CS.getInstruction());
133         } else {
134           DEBUG(std::cerr << "    Inlining: cost=" << InlineCost
135                 << ", Call: " << *CS.getInstruction());
136
137           // Attempt to inline the function...
138           if (InlineCallIfPossible(CS, CG, SCCFunctions)) {
139             // Remove this call site from the list.  If possible, use 
140             // swap/pop_back for efficiency, but do not use it if doing so would
141             // move a call site to a function in this SCC before the
142             // 'FirstCallInSCC' barrier.
143             if (SCC.size() == 1) {
144               std::swap(CallSites[CSi], CallSites.back());
145               CallSites.pop_back();
146             } else {
147               CallSites.erase(CallSites.begin()+CSi);
148             }
149             --CSi;
150
151             ++NumInlined;
152             Changed = true;
153             LocalChange = true;
154           }
155         }
156       }
157   } while (LocalChange);
158
159   return Changed;
160 }
161
162 // doFinalization - Remove now-dead linkonce functions at the end of
163 // processing to avoid breaking the SCC traversal.
164 bool Inliner::doFinalization(CallGraph &CG) {
165   std::set<CallGraphNode*> FunctionsToRemove;
166
167   // Scan for all of the functions, looking for ones that should now be removed
168   // from the program.  Insert the dead ones in the FunctionsToRemove set.
169   for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
170     CallGraphNode *CGN = I->second;
171     if (Function *F = CGN ? CGN->getFunction() : 0) {
172       // If the only remaining users of the function are dead constants, remove
173       // them.
174       F->removeDeadConstantUsers();
175
176       if ((F->hasLinkOnceLinkage() || F->hasInternalLinkage()) &&
177           F->use_empty()) {
178
179         // Remove any call graph edges from the function to its callees.
180         while (CGN->begin() != CGN->end())
181           CGN->removeCallEdgeTo((CGN->end()-1)->second);
182
183         // Remove any edges from the external node to the function's call graph
184         // node.  These edges might have been made irrelegant due to
185         // optimization of the program.
186         CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
187
188         // Removing the node for callee from the call graph and delete it.
189         FunctionsToRemove.insert(CGN);
190       }
191     }
192   }
193
194   // Now that we know which functions to delete, do so.  We didn't want to do
195   // this inline, because that would invalidate our CallGraph::iterator
196   // objects. :(
197   bool Changed = false;
198   for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),
199          E = FunctionsToRemove.end(); I != E; ++I) {
200     delete CG.removeFunctionFromModule(*I);
201     ++NumDeleted;
202     Changed = true;
203   }
204
205   return Changed;
206 }