blob: 1266e5ee0973541294224d1fca3084e268374b70 [file] [log] [blame]
Vikram S. Adveaaeee752002-07-30 22:06:40 +00001//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
2//
3// This file implements the TDDataStructures class, which represents the
4// Top-down Interprocedural closure of the data structure graph over the
5// program. This is useful (but not strictly necessary?) for applications
6// like pointer analysis.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Analysis/DataStructure.h"
11#include "llvm/Module.h"
12#include "llvm/DerivedTypes.h"
Chris Lattner6806f562003-08-01 22:15:03 +000013#include "Support/Debug.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include "Support/Statistic.h"
Chris Lattner18f07a12003-07-01 16:28:11 +000015#include "DSCallSiteIterator.h"
Vikram S. Adveaaeee752002-07-30 22:06:40 +000016
Chris Lattner4923d1b2003-02-03 22:51:28 +000017namespace {
18 RegisterAnalysis<TDDataStructures> // Register the pass
Chris Lattner312edd32003-06-28 22:14:55 +000019 Y("tddatastructure", "Top-down Data Structure Analysis");
Chris Lattnera8da51b2003-07-02 04:39:44 +000020
21 Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
22}
23
Chris Lattner3b0a9be2003-09-20 22:24:04 +000024void TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,
25 hash_set<DSNode*> &Visited) {
26 if (Visited.count(N)) return;
27 Visited.insert(N);
28
29 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i) {
30 DSNodeHandle &NH = N->getLink(i*N->getPointerSize());
31 if (DSNode *NN = NH.getNode()) {
32 const std::vector<GlobalValue*> &Globals = NN->getGlobals();
33 for (unsigned G = 0, e = Globals.size(); G != e; ++G)
34 if (Function *F = dyn_cast<Function>(Globals[G]))
35 ArgsRemainIncomplete.insert(F);
36
37 markReachableFunctionsExternallyAccessible(NN, Visited);
38 }
39 }
Chris Lattner4923d1b2003-02-03 22:51:28 +000040}
Vikram S. Adveaaeee752002-07-30 22:06:40 +000041
Chris Lattner3b0a9be2003-09-20 22:24:04 +000042
Chris Lattneraa0b4682002-11-09 21:12:07 +000043// run - Calculate the top down data structure graphs for each function in the
44// program.
45//
46bool TDDataStructures::run(Module &M) {
47 BUDataStructures &BU = getAnalysis<BUDataStructures>();
Chris Lattner312edd32003-06-28 22:14:55 +000048 GlobalsGraph = new DSGraph(BU.getGlobalsGraph());
Chris Lattneraa0b4682002-11-09 21:12:07 +000049
Chris Lattnera8da51b2003-07-02 04:39:44 +000050 // Figure out which functions must not mark their arguments complete because
Chris Lattner3b0a9be2003-09-20 22:24:04 +000051 // they are accessible outside this compilation unit. Currently, these
52 // arguments are functions which are reachable by global variables in the
53 // globals graph.
54 const DSGraph::ScalarMapTy &GGSM = GlobalsGraph->getScalarMap();
55 hash_set<DSNode*> Visited;
56 for (DSGraph::ScalarMapTy::const_iterator I = GGSM.begin(), E = GGSM.end();
57 I != E; ++I)
58 if (isa<GlobalValue>(I->first))
59 markReachableFunctionsExternallyAccessible(I->second.getNode(), Visited);
60 Visited.clear();
61
62 // Functions without internal linkage also have unknown incoming arguments!
Chris Lattnera8da51b2003-07-02 04:39:44 +000063 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner3b0a9be2003-09-20 22:24:04 +000064 if (!I->isExternal() && !I->hasInternalLinkage())
Chris Lattnera8da51b2003-07-02 04:39:44 +000065 ArgsRemainIncomplete.insert(I);
66
Chris Lattner6c874612003-07-02 23:42:48 +000067 // We want to traverse the call graph in reverse post-order. To do this, we
68 // calculate a post-order traversal, then reverse it.
69 hash_set<DSGraph*> VisitedGraph;
70 std::vector<DSGraph*> PostOrder;
71 const BUDataStructures::ActualCalleesTy &ActualCallees =
72 getAnalysis<BUDataStructures>().getActualCallees();
73
Chris Lattneraa0b4682002-11-09 21:12:07 +000074 // Calculate top-down from main...
75 if (Function *F = M.getMainFunction())
Chris Lattner61691c52003-07-02 23:44:15 +000076 ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
Chris Lattneraa0b4682002-11-09 21:12:07 +000077
Vikram S. Adve03e19dd2003-07-16 21:40:28 +000078 // Next calculate the graphs for each unreachable function...
Chris Lattnera8da51b2003-07-02 04:39:44 +000079 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner6c874612003-07-02 23:42:48 +000080 ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);
81
82 VisitedGraph.clear(); // Release memory!
83
84 // Visit each of the graphs in reverse post-order now!
85 while (!PostOrder.empty()) {
86 inlineGraphIntoCallees(*PostOrder.back());
87 PostOrder.pop_back();
88 }
Chris Lattneraa0b4682002-11-09 21:12:07 +000089
Chris Lattnera8da51b2003-07-02 04:39:44 +000090 ArgsRemainIncomplete.clear();
Chris Lattneraa0b4682002-11-09 21:12:07 +000091 return false;
92}
93
Vikram S. Adveaaeee752002-07-30 22:06:40 +000094
Chris Lattner7a211632002-11-08 21:28:37 +000095DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {
96 DSGraph *&G = DSInfo[&F];
97 if (G == 0) { // Not created yet? Clone BU graph...
98 G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F));
99 G->getAuxFunctionCalls().clear();
Chris Lattner24d80072003-02-04 00:59:32 +0000100 G->setPrintAuxCalls();
Chris Lattneraa0b4682002-11-09 21:12:07 +0000101 G->setGlobalsGraph(GlobalsGraph);
Chris Lattner7a211632002-11-08 21:28:37 +0000102 }
103 return *G;
104}
Vikram S. Adve26b98262002-10-20 21:41:02 +0000105
Chris Lattnerdea81462003-06-29 22:37:07 +0000106
Chris Lattner18f07a12003-07-01 16:28:11 +0000107void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,
108 std::vector<DSGraph*> &PostOrder,
109 const BUDataStructures::ActualCalleesTy &ActualCallees) {
110 if (F.isExternal()) return;
111 DSGraph &G = getOrCreateDSGraph(F);
112 if (Visited.count(&G)) return;
113 Visited.insert(&G);
114
115 // Recursively traverse all of the callee graphs.
116 const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls();
Chris Lattnerdea81462003-06-29 22:37:07 +0000117
Chris Lattner18f07a12003-07-01 16:28:11 +0000118 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000119 Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
Chris Lattner18f07a12003-07-01 16:28:11 +0000120 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
121 BUDataStructures::ActualCalleesTy::const_iterator>
Chris Lattner808a7ae2003-09-20 16:34:13 +0000122 IP = ActualCallees.equal_range(CallI);
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000123
Chris Lattner18f07a12003-07-01 16:28:11 +0000124 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
125 I != IP.second; ++I)
126 ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
127 }
Chris Lattner198be222002-10-21 19:47:18 +0000128
Chris Lattner18f07a12003-07-01 16:28:11 +0000129 PostOrder.push_back(&G);
130}
131
132
133
Chris Lattner18f07a12003-07-01 16:28:11 +0000134
Chris Lattner6c874612003-07-02 23:42:48 +0000135
136// releaseMemory - If the pass pipeline is done with this pass, we can release
137// our memory... here...
138//
139// FIXME: This should be releaseMemory and will work fine, except that LoadVN
140// has no way to extend the lifetime of the pass, which screws up ds-aa.
141//
142void TDDataStructures::releaseMyMemory() {
143 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
144 E = DSInfo.end(); I != E; ++I) {
145 I->second->getReturnNodes().erase(I->first);
146 if (I->second->getReturnNodes().empty())
147 delete I->second;
Chris Lattner18f07a12003-07-01 16:28:11 +0000148 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000149
Chris Lattner6c874612003-07-02 23:42:48 +0000150 // Empty map so next time memory is released, data structures are not
151 // re-deleted.
152 DSInfo.clear();
153 delete GlobalsGraph;
154 GlobalsGraph = 0;
155}
Chris Lattner18f07a12003-07-01 16:28:11 +0000156
157void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000158 // Recompute the Incomplete markers and eliminate unreachable nodes.
Chris Lattner47030f82003-07-02 19:49:11 +0000159 Graph.removeTriviallyDeadNodes();
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000160 Graph.maskIncompleteMarkers();
Chris Lattnera8da51b2003-07-02 04:39:44 +0000161
162 // If any of the functions has incomplete incoming arguments, don't mark any
163 // of them as complete.
164 bool HasIncompleteArgs = false;
165 const DSGraph::ReturnNodesTy &GraphReturnNodes = Graph.getReturnNodes();
166 for (DSGraph::ReturnNodesTy::const_iterator I = GraphReturnNodes.begin(),
167 E = GraphReturnNodes.end(); I != E; ++I)
168 if (ArgsRemainIncomplete.count(I->first)) {
169 HasIncompleteArgs = true;
170 break;
171 }
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000172
173 // Now fold in the necessary globals from the GlobalsGraph. A global G
174 // must be folded in if it exists in the current graph (i.e., is not dead)
175 // and it was not inlined from any of my callers. If it was inlined from
176 // a caller, it would have been fully consistent with the GlobalsGraph
177 // in the caller so folding in is not necessary. Otherwise, this node came
178 // solely from this function's BU graph and so has to be made consistent.
179 //
180 Graph.updateFromGlobalGraph();
181
182 // Recompute the Incomplete markers. Depends on whether args are complete
Chris Lattnera8da51b2003-07-02 04:39:44 +0000183 unsigned Flags
184 = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000185 Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000186
187 // Delete dead nodes. Treat globals that are unreachable as dead also.
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000188 Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
189
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000190 // We are done with computing the current TD Graph! Now move on to
191 // inlining the current graph into the graphs for its callees, if any.
192 //
Chris Lattnera8da51b2003-07-02 04:39:44 +0000193 const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();
194 if (FunctionCalls.empty()) {
Chris Lattner18f07a12003-07-01 16:28:11 +0000195 DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames()
196 << "\n");
197 return;
198 }
199
Chris Lattner18f07a12003-07-01 16:28:11 +0000200 // Now that we have information about all of the callees, propagate the
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000201 // current graph into the callees. Clone only the reachable subgraph at
202 // each call-site, not the entire graph (even though the entire graph
203 // would be cloned only once, this should still be better on average).
Chris Lattner18f07a12003-07-01 16:28:11 +0000204 //
205 DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
Chris Lattnera8da51b2003-07-02 04:39:44 +0000206 << FunctionCalls.size() << " call nodes.\n");
Chris Lattner18f07a12003-07-01 16:28:11 +0000207
Chris Lattnera8da51b2003-07-02 04:39:44 +0000208 const BUDataStructures::ActualCalleesTy &ActualCallees =
209 getAnalysis<BUDataStructures>().getActualCallees();
Chris Lattner18f07a12003-07-01 16:28:11 +0000210
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000211 // Loop over all the call sites and all the callees at each call site.
212 // Clone and merge the reachable subgraph from the call into callee's graph.
213 //
Chris Lattnera8da51b2003-07-02 04:39:44 +0000214 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000215 Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000216 // For each function in the invoked function list at this call site...
Chris Lattnera8da51b2003-07-02 04:39:44 +0000217 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
218 BUDataStructures::ActualCalleesTy::const_iterator>
Chris Lattner808a7ae2003-09-20 16:34:13 +0000219 IP = ActualCallees.equal_range(CallI);
Chris Lattnera8da51b2003-07-02 04:39:44 +0000220
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000221 // Multiple callees may have the same graph, so try to inline and merge
222 // only once for each <callSite,calleeGraph> pair, not once for each
223 // <callSite,calleeFunction> pair; the latter will be correct but slower.
224 hash_set<DSGraph*> GraphsSeen;
225
226 // Loop over each actual callee at this call site
227 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
228 I != IP.second; ++I) {
229 DSGraph& CalleeGraph = getDSGraph(*I->second);
230 assert(&CalleeGraph != &Graph && "TD need not inline graph into self!");
231
232 // if this callee graph is already done at this site, skip this callee
233 if (GraphsSeen.find(&CalleeGraph) != GraphsSeen.end())
234 continue;
235 GraphsSeen.insert(&CalleeGraph);
236
237 // Get the root nodes for cloning the reachable subgraph into each callee:
238 // -- all global nodes that appear in both the caller and the callee
239 // -- return value at this call site, if any
240 // -- actual arguments passed at this call site
241 // -- callee node at this call site, if this is an indirect call (this may
242 // not be needed for merging, but allows us to create CS and therefore
243 // simplify the merging below).
244 hash_set<const DSNode*> RootNodeSet;
245 for (DSGraph::ScalarMapTy::const_iterator
246 SI = CalleeGraph.getScalarMap().begin(),
247 SE = CalleeGraph.getScalarMap().end(); SI != SE; ++SI)
248 if (GlobalValue* GV = dyn_cast<GlobalValue>(SI->first)) {
249 DSGraph::ScalarMapTy::const_iterator GI=Graph.getScalarMap().find(GV);
250 if (GI != Graph.getScalarMap().end())
251 RootNodeSet.insert(GI->second.getNode());
Chris Lattnera8da51b2003-07-02 04:39:44 +0000252 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000253
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000254 if (const DSNode* RetNode = FunctionCalls[i].getRetVal().getNode())
255 RootNodeSet.insert(RetNode);
Chris Lattner0e744122002-10-17 04:26:54 +0000256
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000257 for (unsigned j=0, N=FunctionCalls[i].getNumPtrArgs(); j < N; ++j)
258 if (const DSNode* ArgTarget = FunctionCalls[i].getPtrArg(j).getNode())
259 RootNodeSet.insert(ArgTarget);
260
261 if (FunctionCalls[i].isIndirectCall())
262 RootNodeSet.insert(FunctionCalls[i].getCalleeNode());
263
Chris Lattnera8da51b2003-07-02 04:39:44 +0000264 DEBUG(std::cerr << " [TD] Resolving arguments for callee graph '"
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000265 << CalleeGraph.getFunctionNames()
266 << "': " << I->second->getFunctionType()->getNumParams()
267 << " args\n at call site (DSCallSite*) 0x"
268 << &FunctionCalls[i] << "\n");
269
270 DSGraph::NodeMapTy NodeMapInCallee; // map from nodes to clones in callee
271 DSGraph::NodeMapTy CompletedMap; // unused map for nodes not to do
272 CalleeGraph.cloneReachableSubgraph(Graph, RootNodeSet,
273 NodeMapInCallee, CompletedMap,
274 DSGraph::StripModRefBits |
275 DSGraph::KeepAllocaBit);
Chris Lattner7a211632002-11-08 21:28:37 +0000276
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000277 // Transform our call site info into the cloned version for CalleeGraph
278 DSCallSite CS(FunctionCalls[i], NodeMapInCallee);
Chris Lattnera8da51b2003-07-02 04:39:44 +0000279
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000280 // Get the formal argument and return nodes for the called function
281 // and merge them with the cloned subgraph. Global nodes were merged
282 // already by cloneReachableSubgraph() above.
283 CalleeGraph.getCallSiteForArguments(*I->second).mergeWith(CS);
284
285 ++NumTDInlines;
Chris Lattnera8da51b2003-07-02 04:39:44 +0000286 }
Chris Lattnere0fbd482003-02-09 18:42:43 +0000287 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000288
289 DEBUG(std::cerr << " [TD] Done inlining into callees for: "
290 << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
291 << Graph.getFunctionCalls().size() << "]\n");
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000292}
Chris Lattner4923d1b2003-02-03 22:51:28 +0000293