Silence a spurious warning
[oota-llvm.git] / lib / Analysis / DataStructure / TopDownClosure.cpp
1 //===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
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 TDDataStructures class, which represents the
11 // Top-down Interprocedural closure of the data structure graph over the
12 // program.  This is useful (but not strictly necessary?) for applications
13 // like pointer analysis.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/DataStructure.h"
18 #include "llvm/Module.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Analysis/DSGraph.h"
21 #include "Support/Debug.h"
22 #include "Support/Statistic.h"
23 using namespace llvm;
24
25 namespace {
26   RegisterAnalysis<TDDataStructures>   // Register the pass
27   Y("tddatastructure", "Top-down Data Structure Analysis");
28
29   Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
30 }
31
32 void TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,
33                                                    hash_set<DSNode*> &Visited) {
34   if (!N || Visited.count(N)) return;
35   Visited.insert(N);
36
37   for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i) {
38     DSNodeHandle &NH = N->getLink(i*N->getPointerSize());
39     if (DSNode *NN = NH.getNode()) {
40       const std::vector<GlobalValue*> &Globals = NN->getGlobals();
41       for (unsigned G = 0, e = Globals.size(); G != e; ++G)
42         if (Function *F = dyn_cast<Function>(Globals[G]))
43           ArgsRemainIncomplete.insert(F);
44
45       markReachableFunctionsExternallyAccessible(NN, Visited);
46     }
47   }
48 }
49
50
51 // run - Calculate the top down data structure graphs for each function in the
52 // program.
53 //
54 bool TDDataStructures::run(Module &M) {
55   BUDataStructures &BU = getAnalysis<BUDataStructures>();
56   GlobalsGraph = new DSGraph(BU.getGlobalsGraph());
57   GlobalsGraph->setPrintAuxCalls();
58
59   // Figure out which functions must not mark their arguments complete because
60   // they are accessible outside this compilation unit.  Currently, these
61   // arguments are functions which are reachable by global variables in the
62   // globals graph.
63   const DSScalarMap &GGSM = GlobalsGraph->getScalarMap();
64   hash_set<DSNode*> Visited;
65   for (DSScalarMap::global_iterator I = GGSM.global_begin(), E = GGSM.global_end();
66        I != E; ++I)
67     markReachableFunctionsExternallyAccessible(GGSM.find(*I)->second.getNode(), Visited);
68
69   // Loop over unresolved call nodes.  Any functions passed into (but not
70   // returned!) from unresolvable call nodes may be invoked outside of the
71   // current module.
72   const std::vector<DSCallSite> &Calls = GlobalsGraph->getAuxFunctionCalls();
73   for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
74     const DSCallSite &CS = Calls[i];
75     for (unsigned arg = 0, e = CS.getNumPtrArgs(); arg != e; ++arg)
76       markReachableFunctionsExternallyAccessible(CS.getPtrArg(arg).getNode(),
77                                                  Visited);
78   }
79   Visited.clear();
80
81   // Functions without internal linkage also have unknown incoming arguments!
82   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
83     if (!I->isExternal() && !I->hasInternalLinkage())
84       ArgsRemainIncomplete.insert(I);
85
86   // We want to traverse the call graph in reverse post-order.  To do this, we
87   // calculate a post-order traversal, then reverse it.
88   hash_set<DSGraph*> VisitedGraph;
89   std::vector<DSGraph*> PostOrder;
90   const BUDataStructures::ActualCalleesTy &ActualCallees = 
91     getAnalysis<BUDataStructures>().getActualCallees();
92
93   // Calculate top-down from main...
94   if (Function *F = M.getMainFunction())
95     ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
96
97   // Next calculate the graphs for each unreachable function...
98   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
99     ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);
100
101   VisitedGraph.clear();   // Release memory!
102
103   // Visit each of the graphs in reverse post-order now!
104   while (!PostOrder.empty()) {
105     inlineGraphIntoCallees(*PostOrder.back());
106     PostOrder.pop_back();
107   }
108
109   ArgsRemainIncomplete.clear();
110   GlobalsGraph->removeTriviallyDeadNodes();
111
112   return false;
113 }
114
115
116 DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {
117   DSGraph *&G = DSInfo[&F];
118   if (G == 0) { // Not created yet?  Clone BU graph...
119     G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F));
120     G->getAuxFunctionCalls().clear();
121     G->setPrintAuxCalls();
122     G->setGlobalsGraph(GlobalsGraph);
123   }
124   return *G;
125 }
126
127
128 void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,
129                                         std::vector<DSGraph*> &PostOrder,
130                       const BUDataStructures::ActualCalleesTy &ActualCallees) {
131   if (F.isExternal()) return;
132   DSGraph &G = getOrCreateDSGraph(F);
133   if (Visited.count(&G)) return;
134   Visited.insert(&G);
135   
136   // Recursively traverse all of the callee graphs.
137   const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls();
138
139   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
140     Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
141     std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
142       BUDataStructures::ActualCalleesTy::const_iterator>
143          IP = ActualCallees.equal_range(CallI);
144
145     for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
146          I != IP.second; ++I)
147       ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
148   }
149
150   PostOrder.push_back(&G);
151 }
152
153
154
155
156
157 // releaseMemory - If the pass pipeline is done with this pass, we can release
158 // our memory... here...
159 //
160 // FIXME: This should be releaseMemory and will work fine, except that LoadVN
161 // has no way to extend the lifetime of the pass, which screws up ds-aa.
162 //
163 void TDDataStructures::releaseMyMemory() {
164   for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
165          E = DSInfo.end(); I != E; ++I) {
166     I->second->getReturnNodes().erase(I->first);
167     if (I->second->getReturnNodes().empty())
168       delete I->second;
169   }
170
171   // Empty map so next time memory is released, data structures are not
172   // re-deleted.
173   DSInfo.clear();
174   delete GlobalsGraph;
175   GlobalsGraph = 0;
176 }
177
178 void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
179   // Recompute the Incomplete markers and eliminate unreachable nodes.
180   Graph.maskIncompleteMarkers();
181
182   // If any of the functions has incomplete incoming arguments, don't mark any
183   // of them as complete.
184   bool HasIncompleteArgs = false;
185   const DSGraph::ReturnNodesTy &GraphReturnNodes = Graph.getReturnNodes();
186   for (DSGraph::ReturnNodesTy::const_iterator I = GraphReturnNodes.begin(),
187          E = GraphReturnNodes.end(); I != E; ++I)
188     if (ArgsRemainIncomplete.count(I->first)) {
189       HasIncompleteArgs = true;
190       break;
191     }
192
193   // Now fold in the necessary globals from the GlobalsGraph.  A global G
194   // must be folded in if it exists in the current graph (i.e., is not dead)
195   // and it was not inlined from any of my callers.  If it was inlined from
196   // a caller, it would have been fully consistent with the GlobalsGraph
197   // in the caller so folding in is not necessary.  Otherwise, this node came
198   // solely from this function's BU graph and so has to be made consistent.
199   // 
200   Graph.updateFromGlobalGraph();
201
202   // Recompute the Incomplete markers.  Depends on whether args are complete
203   unsigned Flags
204     = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
205   Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
206
207   // Delete dead nodes.  Treat globals that are unreachable as dead also.
208   Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
209
210   // We are done with computing the current TD Graph! Now move on to
211   // inlining the current graph into the graphs for its callees, if any.
212   // 
213   const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();
214   if (FunctionCalls.empty()) {
215     DEBUG(std::cerr << "  [TD] No callees for: " << Graph.getFunctionNames()
216                     << "\n");
217     return;
218   }
219
220   // Now that we have information about all of the callees, propagate the
221   // current graph into the callees.  Clone only the reachable subgraph at
222   // each call-site, not the entire graph (even though the entire graph
223   // would be cloned only once, this should still be better on average).
224   //
225   DEBUG(std::cerr << "  [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
226                   << FunctionCalls.size() << " call nodes.\n");
227
228   const BUDataStructures::ActualCalleesTy &ActualCallees =
229     getAnalysis<BUDataStructures>().getActualCallees();
230
231   // Loop over all the call sites and all the callees at each call site.  Build
232   // a mapping from called DSGraph's to the call sites in this function that
233   // invoke them.  This is useful because we can be more efficient if there are
234   // multiple call sites to the callees in the graph from this caller.
235   std::multimap<DSGraph*, std::pair<Function*, const DSCallSite*> > CallSites;
236
237   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
238     Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
239     // For each function in the invoked function list at this call site...
240     std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
241       BUDataStructures::ActualCalleesTy::const_iterator>
242           IP = ActualCallees.equal_range(CallI);
243     // Loop over each actual callee at this call site
244     for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
245          I != IP.second; ++I) {
246       DSGraph& CalleeGraph = getDSGraph(*I->second);
247       assert(&CalleeGraph != &Graph && "TD need not inline graph into self!");
248
249       CallSites.insert(std::make_pair(&CalleeGraph,
250                            std::make_pair(I->second, &FunctionCalls[i])));
251     }
252   }
253
254   // Now that we built the mapping, actually perform the inlining a callee graph
255   // at a time.
256   std::multimap<DSGraph*,std::pair<Function*,const DSCallSite*> >::iterator CSI;
257   for (CSI = CallSites.begin(); CSI != CallSites.end(); ) {
258     DSGraph &CalleeGraph = *CSI->first;
259     // Iterate through all of the call sites of this graph, cloning and merging
260     // any nodes required by the call.
261     ReachabilityCloner RC(CalleeGraph, Graph, DSGraph::StripModRefBits);
262
263     // Clone over any global nodes that appear in both graphs.
264     for (DSScalarMap::global_iterator
265            SI = CalleeGraph.getScalarMap().global_begin(),
266            SE = CalleeGraph.getScalarMap().global_end(); SI != SE; ++SI) {
267       DSScalarMap::const_iterator GI = Graph.getScalarMap().find(*SI);
268       if (GI != Graph.getScalarMap().end())
269         RC.merge(CalleeGraph.getNodeForValue(*SI), GI->second);
270     }
271
272     // Loop over all of the distinct call sites in the caller of the callee.
273     for (; CSI != CallSites.end() && CSI->first == &CalleeGraph; ++CSI) {
274       Function &CF = *CSI->second.first;
275       const DSCallSite &CS = *CSI->second.second;
276       DEBUG(std::cerr << "     [TD] Resolving arguments for callee graph '"
277             << CalleeGraph.getFunctionNames()
278             << "': " << CF.getFunctionType()->getNumParams()
279             << " args\n          at call site (DSCallSite*) 0x" << &CS << "\n");
280       
281       // Get the formal argument and return nodes for the called function and
282       // merge them with the cloned subgraph.
283       RC.mergeCallSite(CalleeGraph.getCallSiteForArguments(CF), CS);
284       ++NumTDInlines;
285     }
286   }
287
288   DEBUG(std::cerr << "  [TD] Done inlining into callees for: "
289         << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
290         << Graph.getFunctionCalls().size() << "]\n");
291 }