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