blob: 696368a866e84ed2a545895828ab29c381350f42 [file] [log] [blame]
Vikram S. Adveaaeee752002-07-30 22:06:40 +00001//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
John Criswellb576c942003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Vikram S. Adveaaeee752002-07-30 22:06:40 +00009//
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"
Chris Lattner492dda92003-11-08 21:17:37 +000020#include "llvm/Analysis/DSGraph.h"
Chris Lattner6806f562003-08-01 22:15:03 +000021#include "Support/Debug.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000022#include "Support/Statistic.h"
Vikram S. Adveaaeee752002-07-30 22:06:40 +000023
Brian Gaeked0fde302003-11-11 22:41:34 +000024namespace llvm {
25
Chris Lattner4923d1b2003-02-03 22:51:28 +000026namespace {
27 RegisterAnalysis<TDDataStructures> // Register the pass
Chris Lattner312edd32003-06-28 22:14:55 +000028 Y("tddatastructure", "Top-down Data Structure Analysis");
Chris Lattnera8da51b2003-07-02 04:39:44 +000029
30 Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
31}
32
Chris Lattner3b0a9be2003-09-20 22:24:04 +000033void TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,
34 hash_set<DSNode*> &Visited) {
Chris Lattner11fc9302003-09-20 23:58:33 +000035 if (!N || Visited.count(N)) return;
Chris Lattner3b0a9be2003-09-20 22:24:04 +000036 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 }
Chris Lattner4923d1b2003-02-03 22:51:28 +000049}
Vikram S. Adveaaeee752002-07-30 22:06:40 +000050
Chris Lattner3b0a9be2003-09-20 22:24:04 +000051
Chris Lattneraa0b4682002-11-09 21:12:07 +000052// run - Calculate the top down data structure graphs for each function in the
53// program.
54//
55bool TDDataStructures::run(Module &M) {
56 BUDataStructures &BU = getAnalysis<BUDataStructures>();
Chris Lattner312edd32003-06-28 22:14:55 +000057 GlobalsGraph = new DSGraph(BU.getGlobalsGraph());
Chris Lattner11fc9302003-09-20 23:58:33 +000058 GlobalsGraph->setPrintAuxCalls();
Chris Lattneraa0b4682002-11-09 21:12:07 +000059
Chris Lattnera8da51b2003-07-02 04:39:44 +000060 // Figure out which functions must not mark their arguments complete because
Chris Lattner3b0a9be2003-09-20 22:24:04 +000061 // 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);
Chris Lattner11fc9302003-09-20 23:58:33 +000070
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 }
Chris Lattner3b0a9be2003-09-20 22:24:04 +000081 Visited.clear();
82
83 // Functions without internal linkage also have unknown incoming arguments!
Chris Lattnera8da51b2003-07-02 04:39:44 +000084 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner3b0a9be2003-09-20 22:24:04 +000085 if (!I->isExternal() && !I->hasInternalLinkage())
Chris Lattnera8da51b2003-07-02 04:39:44 +000086 ArgsRemainIncomplete.insert(I);
87
Chris Lattner6c874612003-07-02 23:42:48 +000088 // 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
Chris Lattneraa0b4682002-11-09 21:12:07 +000095 // Calculate top-down from main...
96 if (Function *F = M.getMainFunction())
Chris Lattner61691c52003-07-02 23:44:15 +000097 ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
Chris Lattneraa0b4682002-11-09 21:12:07 +000098
Vikram S. Adve03e19dd2003-07-16 21:40:28 +000099 // Next calculate the graphs for each unreachable function...
Chris Lattnera8da51b2003-07-02 04:39:44 +0000100 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner6c874612003-07-02 23:42:48 +0000101 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 }
Chris Lattneraa0b4682002-11-09 21:12:07 +0000110
Chris Lattnera8da51b2003-07-02 04:39:44 +0000111 ArgsRemainIncomplete.clear();
Chris Lattneraa0b4682002-11-09 21:12:07 +0000112 return false;
113}
114
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000115
Chris Lattner7a211632002-11-08 21:28:37 +0000116DSGraph &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();
Chris Lattner24d80072003-02-04 00:59:32 +0000121 G->setPrintAuxCalls();
Chris Lattneraa0b4682002-11-09 21:12:07 +0000122 G->setGlobalsGraph(GlobalsGraph);
Chris Lattner7a211632002-11-08 21:28:37 +0000123 }
124 return *G;
125}
Vikram S. Adve26b98262002-10-20 21:41:02 +0000126
Chris Lattnerdea81462003-06-29 22:37:07 +0000127
Chris Lattner18f07a12003-07-01 16:28:11 +0000128void 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();
Chris Lattnerdea81462003-06-29 22:37:07 +0000138
Chris Lattner18f07a12003-07-01 16:28:11 +0000139 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000140 Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
Chris Lattner18f07a12003-07-01 16:28:11 +0000141 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
142 BUDataStructures::ActualCalleesTy::const_iterator>
Chris Lattner808a7ae2003-09-20 16:34:13 +0000143 IP = ActualCallees.equal_range(CallI);
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000144
Chris Lattner18f07a12003-07-01 16:28:11 +0000145 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
146 I != IP.second; ++I)
147 ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
148 }
Chris Lattner198be222002-10-21 19:47:18 +0000149
Chris Lattner18f07a12003-07-01 16:28:11 +0000150 PostOrder.push_back(&G);
151}
152
153
154
Chris Lattner18f07a12003-07-01 16:28:11 +0000155
Chris Lattner6c874612003-07-02 23:42:48 +0000156
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//
163void 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;
Chris Lattner18f07a12003-07-01 16:28:11 +0000169 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000170
Chris Lattner6c874612003-07-02 23:42:48 +0000171 // 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}
Chris Lattner18f07a12003-07-01 16:28:11 +0000177
178void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000179 // Recompute the Incomplete markers and eliminate unreachable nodes.
Chris Lattner47030f82003-07-02 19:49:11 +0000180 Graph.removeTriviallyDeadNodes();
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000181 Graph.maskIncompleteMarkers();
Chris Lattnera8da51b2003-07-02 04:39:44 +0000182
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 }
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000193
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
Chris Lattnera8da51b2003-07-02 04:39:44 +0000204 unsigned Flags
205 = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000206 Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000207
208 // Delete dead nodes. Treat globals that are unreachable as dead also.
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000209 Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
210
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000211 // 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 //
Chris Lattnera8da51b2003-07-02 04:39:44 +0000214 const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();
215 if (FunctionCalls.empty()) {
Chris Lattner18f07a12003-07-01 16:28:11 +0000216 DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames()
217 << "\n");
218 return;
219 }
220
Chris Lattner18f07a12003-07-01 16:28:11 +0000221 // Now that we have information about all of the callees, propagate the
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000222 // 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).
Chris Lattner18f07a12003-07-01 16:28:11 +0000225 //
226 DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
Chris Lattnera8da51b2003-07-02 04:39:44 +0000227 << FunctionCalls.size() << " call nodes.\n");
Chris Lattner18f07a12003-07-01 16:28:11 +0000228
Chris Lattnera8da51b2003-07-02 04:39:44 +0000229 const BUDataStructures::ActualCalleesTy &ActualCallees =
230 getAnalysis<BUDataStructures>().getActualCallees();
Chris Lattner18f07a12003-07-01 16:28:11 +0000231
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000232 // 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 //
Chris Lattnera8da51b2003-07-02 04:39:44 +0000235 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000236 Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000237 // For each function in the invoked function list at this call site...
Chris Lattnera8da51b2003-07-02 04:39:44 +0000238 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
239 BUDataStructures::ActualCalleesTy::const_iterator>
Chris Lattner808a7ae2003-09-20 16:34:13 +0000240 IP = ActualCallees.equal_range(CallI);
Chris Lattnera8da51b2003-07-02 04:39:44 +0000241
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000242 // 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());
Chris Lattnera8da51b2003-07-02 04:39:44 +0000273 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000274
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000275 if (const DSNode* RetNode = FunctionCalls[i].getRetVal().getNode())
276 RootNodeSet.insert(RetNode);
Chris Lattner0e744122002-10-17 04:26:54 +0000277
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000278 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
Chris Lattnera8da51b2003-07-02 04:39:44 +0000285 DEBUG(std::cerr << " [TD] Resolving arguments for callee graph '"
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000286 << 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);
Chris Lattner7a211632002-11-08 21:28:37 +0000297
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000298 // Transform our call site info into the cloned version for CalleeGraph
299 DSCallSite CS(FunctionCalls[i], NodeMapInCallee);
Chris Lattnera8da51b2003-07-02 04:39:44 +0000300
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000301 // 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;
Chris Lattnera8da51b2003-07-02 04:39:44 +0000307 }
Chris Lattnere0fbd482003-02-09 18:42:43 +0000308 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000309
310 DEBUG(std::cerr << " [TD] Done inlining into callees for: "
311 << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
312 << Graph.getFunctionCalls().size() << "]\n");
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000313}
Chris Lattner4923d1b2003-02-03 22:51:28 +0000314
Brian Gaeked0fde302003-11-11 22:41:34 +0000315} // End llvm namespace