blob: 92a03ee2f40e31a437406a4328b09a7e8d4f3a7f [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
24/// FunctionHasCompleteArguments - This function returns true if it is safe not
25/// to mark arguments to the function complete.
26///
27/// FIXME: Need to check if all callers have been found, or rather if a
28/// funcpointer escapes!
29///
30static bool FunctionHasCompleteArguments(Function &F) {
31 return F.hasInternalLinkage();
Chris Lattner4923d1b2003-02-03 22:51:28 +000032}
Vikram S. Adveaaeee752002-07-30 22:06:40 +000033
Chris Lattneraa0b4682002-11-09 21:12:07 +000034// run - Calculate the top down data structure graphs for each function in the
35// program.
36//
37bool TDDataStructures::run(Module &M) {
38 BUDataStructures &BU = getAnalysis<BUDataStructures>();
Chris Lattner312edd32003-06-28 22:14:55 +000039 GlobalsGraph = new DSGraph(BU.getGlobalsGraph());
Chris Lattneraa0b4682002-11-09 21:12:07 +000040
Chris Lattnera8da51b2003-07-02 04:39:44 +000041 // Figure out which functions must not mark their arguments complete because
42 // they are accessible outside this compilation unit.
43 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
44 if (!FunctionHasCompleteArguments(*I))
45 ArgsRemainIncomplete.insert(I);
46
Chris Lattner6c874612003-07-02 23:42:48 +000047 // We want to traverse the call graph in reverse post-order. To do this, we
48 // calculate a post-order traversal, then reverse it.
49 hash_set<DSGraph*> VisitedGraph;
50 std::vector<DSGraph*> PostOrder;
51 const BUDataStructures::ActualCalleesTy &ActualCallees =
52 getAnalysis<BUDataStructures>().getActualCallees();
53
Chris Lattneraa0b4682002-11-09 21:12:07 +000054 // Calculate top-down from main...
55 if (Function *F = M.getMainFunction())
Chris Lattner61691c52003-07-02 23:44:15 +000056 ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
Chris Lattneraa0b4682002-11-09 21:12:07 +000057
Vikram S. Adve03e19dd2003-07-16 21:40:28 +000058 // Next calculate the graphs for each unreachable function...
Chris Lattnera8da51b2003-07-02 04:39:44 +000059 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner6c874612003-07-02 23:42:48 +000060 ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);
61
62 VisitedGraph.clear(); // Release memory!
63
64 // Visit each of the graphs in reverse post-order now!
65 while (!PostOrder.empty()) {
66 inlineGraphIntoCallees(*PostOrder.back());
67 PostOrder.pop_back();
68 }
Chris Lattneraa0b4682002-11-09 21:12:07 +000069
Chris Lattnera8da51b2003-07-02 04:39:44 +000070 ArgsRemainIncomplete.clear();
Chris Lattneraa0b4682002-11-09 21:12:07 +000071 return false;
72}
73
Vikram S. Adveaaeee752002-07-30 22:06:40 +000074
Chris Lattner7a211632002-11-08 21:28:37 +000075DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {
76 DSGraph *&G = DSInfo[&F];
77 if (G == 0) { // Not created yet? Clone BU graph...
78 G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F));
79 G->getAuxFunctionCalls().clear();
Chris Lattner24d80072003-02-04 00:59:32 +000080 G->setPrintAuxCalls();
Chris Lattneraa0b4682002-11-09 21:12:07 +000081 G->setGlobalsGraph(GlobalsGraph);
Chris Lattner7a211632002-11-08 21:28:37 +000082 }
83 return *G;
84}
Vikram S. Adve26b98262002-10-20 21:41:02 +000085
Chris Lattnerdea81462003-06-29 22:37:07 +000086
Chris Lattner18f07a12003-07-01 16:28:11 +000087void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,
88 std::vector<DSGraph*> &PostOrder,
89 const BUDataStructures::ActualCalleesTy &ActualCallees) {
90 if (F.isExternal()) return;
91 DSGraph &G = getOrCreateDSGraph(F);
92 if (Visited.count(&G)) return;
93 Visited.insert(&G);
94
95 // Recursively traverse all of the callee graphs.
96 const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls();
Chris Lattnerdea81462003-06-29 22:37:07 +000097
Chris Lattner18f07a12003-07-01 16:28:11 +000098 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
99 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
100 BUDataStructures::ActualCalleesTy::const_iterator>
Chris Lattnera8da51b2003-07-02 04:39:44 +0000101 IP = ActualCallees.equal_range(&FunctionCalls[i].getCallInst());
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000102
Chris Lattner18f07a12003-07-01 16:28:11 +0000103 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
104 I != IP.second; ++I)
105 ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
106 }
Chris Lattner198be222002-10-21 19:47:18 +0000107
Chris Lattner18f07a12003-07-01 16:28:11 +0000108 PostOrder.push_back(&G);
109}
110
111
112
Chris Lattner18f07a12003-07-01 16:28:11 +0000113
Chris Lattner6c874612003-07-02 23:42:48 +0000114
115// releaseMemory - If the pass pipeline is done with this pass, we can release
116// our memory... here...
117//
118// FIXME: This should be releaseMemory and will work fine, except that LoadVN
119// has no way to extend the lifetime of the pass, which screws up ds-aa.
120//
121void TDDataStructures::releaseMyMemory() {
122 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
123 E = DSInfo.end(); I != E; ++I) {
124 I->second->getReturnNodes().erase(I->first);
125 if (I->second->getReturnNodes().empty())
126 delete I->second;
Chris Lattner18f07a12003-07-01 16:28:11 +0000127 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000128
Chris Lattner6c874612003-07-02 23:42:48 +0000129 // Empty map so next time memory is released, data structures are not
130 // re-deleted.
131 DSInfo.clear();
132 delete GlobalsGraph;
133 GlobalsGraph = 0;
134}
Chris Lattner18f07a12003-07-01 16:28:11 +0000135
136void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000137 // Recompute the Incomplete markers and eliminate unreachable nodes.
Chris Lattner47030f82003-07-02 19:49:11 +0000138 Graph.removeTriviallyDeadNodes();
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000139 Graph.maskIncompleteMarkers();
Chris Lattnera8da51b2003-07-02 04:39:44 +0000140
141 // If any of the functions has incomplete incoming arguments, don't mark any
142 // of them as complete.
143 bool HasIncompleteArgs = false;
144 const DSGraph::ReturnNodesTy &GraphReturnNodes = Graph.getReturnNodes();
145 for (DSGraph::ReturnNodesTy::const_iterator I = GraphReturnNodes.begin(),
146 E = GraphReturnNodes.end(); I != E; ++I)
147 if (ArgsRemainIncomplete.count(I->first)) {
148 HasIncompleteArgs = true;
149 break;
150 }
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000151
152 // Now fold in the necessary globals from the GlobalsGraph. A global G
153 // must be folded in if it exists in the current graph (i.e., is not dead)
154 // and it was not inlined from any of my callers. If it was inlined from
155 // a caller, it would have been fully consistent with the GlobalsGraph
156 // in the caller so folding in is not necessary. Otherwise, this node came
157 // solely from this function's BU graph and so has to be made consistent.
158 //
159 Graph.updateFromGlobalGraph();
160
161 // Recompute the Incomplete markers. Depends on whether args are complete
Chris Lattnera8da51b2003-07-02 04:39:44 +0000162 unsigned Flags
163 = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000164 Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000165
166 // Delete dead nodes. Treat globals that are unreachable as dead also.
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000167 Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
168
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000169 // We are done with computing the current TD Graph! Now move on to
170 // inlining the current graph into the graphs for its callees, if any.
171 //
Chris Lattnera8da51b2003-07-02 04:39:44 +0000172 const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();
173 if (FunctionCalls.empty()) {
Chris Lattner18f07a12003-07-01 16:28:11 +0000174 DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames()
175 << "\n");
176 return;
177 }
178
Chris Lattner18f07a12003-07-01 16:28:11 +0000179 // Now that we have information about all of the callees, propagate the
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000180 // current graph into the callees. Clone only the reachable subgraph at
181 // each call-site, not the entire graph (even though the entire graph
182 // would be cloned only once, this should still be better on average).
Chris Lattner18f07a12003-07-01 16:28:11 +0000183 //
184 DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
Chris Lattnera8da51b2003-07-02 04:39:44 +0000185 << FunctionCalls.size() << " call nodes.\n");
Chris Lattner18f07a12003-07-01 16:28:11 +0000186
Chris Lattnera8da51b2003-07-02 04:39:44 +0000187 const BUDataStructures::ActualCalleesTy &ActualCallees =
188 getAnalysis<BUDataStructures>().getActualCallees();
Chris Lattner18f07a12003-07-01 16:28:11 +0000189
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000190 // Loop over all the call sites and all the callees at each call site.
191 // Clone and merge the reachable subgraph from the call into callee's graph.
192 //
Chris Lattnera8da51b2003-07-02 04:39:44 +0000193 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000194 // For each function in the invoked function list at this call site...
Chris Lattnera8da51b2003-07-02 04:39:44 +0000195 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
196 BUDataStructures::ActualCalleesTy::const_iterator>
197 IP = ActualCallees.equal_range(&FunctionCalls[i].getCallInst());
198
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000199 // Multiple callees may have the same graph, so try to inline and merge
200 // only once for each <callSite,calleeGraph> pair, not once for each
201 // <callSite,calleeFunction> pair; the latter will be correct but slower.
202 hash_set<DSGraph*> GraphsSeen;
203
204 // Loop over each actual callee at this call site
205 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
206 I != IP.second; ++I) {
207 DSGraph& CalleeGraph = getDSGraph(*I->second);
208 assert(&CalleeGraph != &Graph && "TD need not inline graph into self!");
209
210 // if this callee graph is already done at this site, skip this callee
211 if (GraphsSeen.find(&CalleeGraph) != GraphsSeen.end())
212 continue;
213 GraphsSeen.insert(&CalleeGraph);
214
215 // Get the root nodes for cloning the reachable subgraph into each callee:
216 // -- all global nodes that appear in both the caller and the callee
217 // -- return value at this call site, if any
218 // -- actual arguments passed at this call site
219 // -- callee node at this call site, if this is an indirect call (this may
220 // not be needed for merging, but allows us to create CS and therefore
221 // simplify the merging below).
222 hash_set<const DSNode*> RootNodeSet;
223 for (DSGraph::ScalarMapTy::const_iterator
224 SI = CalleeGraph.getScalarMap().begin(),
225 SE = CalleeGraph.getScalarMap().end(); SI != SE; ++SI)
226 if (GlobalValue* GV = dyn_cast<GlobalValue>(SI->first)) {
227 DSGraph::ScalarMapTy::const_iterator GI=Graph.getScalarMap().find(GV);
228 if (GI != Graph.getScalarMap().end())
229 RootNodeSet.insert(GI->second.getNode());
Chris Lattnera8da51b2003-07-02 04:39:44 +0000230 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000231
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000232 if (const DSNode* RetNode = FunctionCalls[i].getRetVal().getNode())
233 RootNodeSet.insert(RetNode);
Chris Lattner0e744122002-10-17 04:26:54 +0000234
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000235 for (unsigned j=0, N=FunctionCalls[i].getNumPtrArgs(); j < N; ++j)
236 if (const DSNode* ArgTarget = FunctionCalls[i].getPtrArg(j).getNode())
237 RootNodeSet.insert(ArgTarget);
238
239 if (FunctionCalls[i].isIndirectCall())
240 RootNodeSet.insert(FunctionCalls[i].getCalleeNode());
241
Chris Lattnera8da51b2003-07-02 04:39:44 +0000242 DEBUG(std::cerr << " [TD] Resolving arguments for callee graph '"
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000243 << CalleeGraph.getFunctionNames()
244 << "': " << I->second->getFunctionType()->getNumParams()
245 << " args\n at call site (DSCallSite*) 0x"
246 << &FunctionCalls[i] << "\n");
247
248 DSGraph::NodeMapTy NodeMapInCallee; // map from nodes to clones in callee
249 DSGraph::NodeMapTy CompletedMap; // unused map for nodes not to do
250 CalleeGraph.cloneReachableSubgraph(Graph, RootNodeSet,
251 NodeMapInCallee, CompletedMap,
252 DSGraph::StripModRefBits |
253 DSGraph::KeepAllocaBit);
Chris Lattner7a211632002-11-08 21:28:37 +0000254
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000255 // Transform our call site info into the cloned version for CalleeGraph
256 DSCallSite CS(FunctionCalls[i], NodeMapInCallee);
Chris Lattnera8da51b2003-07-02 04:39:44 +0000257
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000258 // Get the formal argument and return nodes for the called function
259 // and merge them with the cloned subgraph. Global nodes were merged
260 // already by cloneReachableSubgraph() above.
261 CalleeGraph.getCallSiteForArguments(*I->second).mergeWith(CS);
262
263 ++NumTDInlines;
Chris Lattnera8da51b2003-07-02 04:39:44 +0000264 }
Chris Lattnere0fbd482003-02-09 18:42:43 +0000265 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000266
267 DEBUG(std::cerr << " [TD] Done inlining into callees for: "
268 << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
269 << Graph.getFunctionCalls().size() << "]\n");
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000270}
Chris Lattner4923d1b2003-02-03 22:51:28 +0000271