Put all LLVM code into the llvm namespace, as per bug 109.
[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
24 namespace llvm {
25
26 namespace {
27   RegisterAnalysis<TDDataStructures>   // Register the pass
28   Y("tddatastructure", "Top-down Data Structure Analysis");
29
30   Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
31 }
32
33 void TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,
34                                                    hash_set<DSNode*> &Visited) {
35   if (!N || Visited.count(N)) return;
36   Visited.insert(N);
37
38   for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i) {
39     DSNodeHandle &NH = N->getLink(i*N->getPointerSize());
40     if (DSNode *NN = NH.getNode()) {
41       const std::vector<GlobalValue*> &Globals = NN->getGlobals();
42       for (unsigned G = 0, e = Globals.size(); G != e; ++G)
43         if (Function *F = dyn_cast<Function>(Globals[G]))
44           ArgsRemainIncomplete.insert(F);
45
46       markReachableFunctionsExternallyAccessible(NN, Visited);
47     }
48   }
49 }
50
51
52 // run - Calculate the top down data structure graphs for each function in the
53 // program.
54 //
55 bool TDDataStructures::run(Module &M) {
56   BUDataStructures &BU = getAnalysis<BUDataStructures>();
57   GlobalsGraph = new DSGraph(BU.getGlobalsGraph());
58   GlobalsGraph->setPrintAuxCalls();
59
60   // Figure out which functions must not mark their arguments complete because
61   // they are accessible outside this compilation unit.  Currently, these
62   // arguments are functions which are reachable by global variables in the
63   // globals graph.
64   const DSGraph::ScalarMapTy &GGSM = GlobalsGraph->getScalarMap();
65   hash_set<DSNode*> Visited;
66   for (DSGraph::ScalarMapTy::const_iterator I = GGSM.begin(), E = GGSM.end();
67        I != E; ++I)
68     if (isa<GlobalValue>(I->first))
69       markReachableFunctionsExternallyAccessible(I->second.getNode(), Visited);
70
71   // Loop over unresolved call nodes.  Any functions passed into (but not
72   // returned!?) from unresolvable call nodes may be invoked outside of the
73   // current module.
74   const std::vector<DSCallSite> &Calls = GlobalsGraph->getAuxFunctionCalls();
75   for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
76     const DSCallSite &CS = Calls[i];
77     for (unsigned arg = 0, e = CS.getNumPtrArgs(); arg != e; ++arg)
78       markReachableFunctionsExternallyAccessible(CS.getPtrArg(arg).getNode(),
79                                                  Visited);
80   }
81   Visited.clear();
82
83   // Functions without internal linkage also have unknown incoming arguments!
84   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
85     if (!I->isExternal() && !I->hasInternalLinkage())
86       ArgsRemainIncomplete.insert(I);
87
88   // We want to traverse the call graph in reverse post-order.  To do this, we
89   // calculate a post-order traversal, then reverse it.
90   hash_set<DSGraph*> VisitedGraph;
91   std::vector<DSGraph*> PostOrder;
92   const BUDataStructures::ActualCalleesTy &ActualCallees = 
93     getAnalysis<BUDataStructures>().getActualCallees();
94
95   // Calculate top-down from main...
96   if (Function *F = M.getMainFunction())
97     ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
98
99   // Next calculate the graphs for each unreachable function...
100   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
101     ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);
102
103   VisitedGraph.clear();   // Release memory!
104
105   // Visit each of the graphs in reverse post-order now!
106   while (!PostOrder.empty()) {
107     inlineGraphIntoCallees(*PostOrder.back());
108     PostOrder.pop_back();
109   }
110
111   ArgsRemainIncomplete.clear();
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.removeTriviallyDeadNodes();
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.
233   // Clone and merge the reachable subgraph from the call into callee's graph.
234   // 
235   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
236     Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
237     // For each function in the invoked function list at this call site...
238     std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
239       BUDataStructures::ActualCalleesTy::const_iterator>
240           IP = ActualCallees.equal_range(CallI);
241
242     // Multiple callees may have the same graph, so try to inline and merge
243     // only once for each <callSite,calleeGraph> pair, not once for each
244     // <callSite,calleeFunction> pair; the latter will be correct but slower.
245     hash_set<DSGraph*> GraphsSeen;
246
247     // Loop over each actual callee at this call site
248     for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
249          I != IP.second; ++I) {
250       DSGraph& CalleeGraph = getDSGraph(*I->second);
251       assert(&CalleeGraph != &Graph && "TD need not inline graph into self!");
252
253       // if this callee graph is already done at this site, skip this callee
254       if (GraphsSeen.find(&CalleeGraph) != GraphsSeen.end())
255         continue;
256       GraphsSeen.insert(&CalleeGraph);
257
258       // Get the root nodes for cloning the reachable subgraph into each callee:
259       // -- all global nodes that appear in both the caller and the callee
260       // -- return value at this call site, if any
261       // -- actual arguments passed at this call site
262       // -- callee node at this call site, if this is an indirect call (this may
263       //    not be needed for merging, but allows us to create CS and therefore
264       //    simplify the merging below).
265       hash_set<const DSNode*> RootNodeSet;
266       for (DSGraph::ScalarMapTy::const_iterator
267              SI = CalleeGraph.getScalarMap().begin(),
268              SE = CalleeGraph.getScalarMap().end(); SI != SE; ++SI)
269         if (GlobalValue* GV = dyn_cast<GlobalValue>(SI->first)) {
270           DSGraph::ScalarMapTy::const_iterator GI=Graph.getScalarMap().find(GV);
271           if (GI != Graph.getScalarMap().end())
272             RootNodeSet.insert(GI->second.getNode());
273         }
274
275       if (const DSNode* RetNode = FunctionCalls[i].getRetVal().getNode())
276         RootNodeSet.insert(RetNode);
277
278       for (unsigned j=0, N=FunctionCalls[i].getNumPtrArgs(); j < N; ++j)
279         if (const DSNode* ArgTarget = FunctionCalls[i].getPtrArg(j).getNode())
280           RootNodeSet.insert(ArgTarget);
281
282       if (FunctionCalls[i].isIndirectCall())
283         RootNodeSet.insert(FunctionCalls[i].getCalleeNode());
284
285       DEBUG(std::cerr << "     [TD] Resolving arguments for callee graph '"
286             << CalleeGraph.getFunctionNames()
287             << "': " << I->second->getFunctionType()->getNumParams()
288             << " args\n          at call site (DSCallSite*) 0x"
289             << &FunctionCalls[i] << "\n");
290       
291       DSGraph::NodeMapTy NodeMapInCallee; // map from nodes to clones in callee
292       DSGraph::NodeMapTy CompletedMap;    // unused map for nodes not to do
293       CalleeGraph.cloneReachableSubgraph(Graph, RootNodeSet,
294                                          NodeMapInCallee, CompletedMap,
295                                          DSGraph::StripModRefBits |
296                                          DSGraph::KeepAllocaBit);
297
298       // Transform our call site info into the cloned version for CalleeGraph
299       DSCallSite CS(FunctionCalls[i], NodeMapInCallee);
300
301       // Get the formal argument and return nodes for the called function
302       // and merge them with the cloned subgraph.  Global nodes were merged  
303       // already by cloneReachableSubgraph() above.
304       CalleeGraph.getCallSiteForArguments(*I->second).mergeWith(CS);
305
306       ++NumTDInlines;
307     }
308   }
309
310   DEBUG(std::cerr << "  [TD] Done inlining into callees for: "
311         << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
312         << Graph.getFunctionCalls().size() << "]\n");
313 }
314
315 } // End llvm namespace