blob: 13535e3f8014bcc84a107794c255d5dedac8e09e [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) {
Chris Lattner808a7ae2003-09-20 16:34:13 +000099 Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
Chris Lattner18f07a12003-07-01 16:28:11 +0000100 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
101 BUDataStructures::ActualCalleesTy::const_iterator>
Chris Lattner808a7ae2003-09-20 16:34:13 +0000102 IP = ActualCallees.equal_range(CallI);
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000103
Chris Lattner18f07a12003-07-01 16:28:11 +0000104 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
105 I != IP.second; ++I)
106 ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
107 }
Chris Lattner198be222002-10-21 19:47:18 +0000108
Chris Lattner18f07a12003-07-01 16:28:11 +0000109 PostOrder.push_back(&G);
110}
111
112
113
Chris Lattner18f07a12003-07-01 16:28:11 +0000114
Chris Lattner6c874612003-07-02 23:42:48 +0000115
116// releaseMemory - If the pass pipeline is done with this pass, we can release
117// our memory... here...
118//
119// FIXME: This should be releaseMemory and will work fine, except that LoadVN
120// has no way to extend the lifetime of the pass, which screws up ds-aa.
121//
122void TDDataStructures::releaseMyMemory() {
123 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
124 E = DSInfo.end(); I != E; ++I) {
125 I->second->getReturnNodes().erase(I->first);
126 if (I->second->getReturnNodes().empty())
127 delete I->second;
Chris Lattner18f07a12003-07-01 16:28:11 +0000128 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000129
Chris Lattner6c874612003-07-02 23:42:48 +0000130 // Empty map so next time memory is released, data structures are not
131 // re-deleted.
132 DSInfo.clear();
133 delete GlobalsGraph;
134 GlobalsGraph = 0;
135}
Chris Lattner18f07a12003-07-01 16:28:11 +0000136
137void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000138 // Recompute the Incomplete markers and eliminate unreachable nodes.
Chris Lattner47030f82003-07-02 19:49:11 +0000139 Graph.removeTriviallyDeadNodes();
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000140 Graph.maskIncompleteMarkers();
Chris Lattnera8da51b2003-07-02 04:39:44 +0000141
142 // If any of the functions has incomplete incoming arguments, don't mark any
143 // of them as complete.
144 bool HasIncompleteArgs = false;
145 const DSGraph::ReturnNodesTy &GraphReturnNodes = Graph.getReturnNodes();
146 for (DSGraph::ReturnNodesTy::const_iterator I = GraphReturnNodes.begin(),
147 E = GraphReturnNodes.end(); I != E; ++I)
148 if (ArgsRemainIncomplete.count(I->first)) {
149 HasIncompleteArgs = true;
150 break;
151 }
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000152
153 // Now fold in the necessary globals from the GlobalsGraph. A global G
154 // must be folded in if it exists in the current graph (i.e., is not dead)
155 // and it was not inlined from any of my callers. If it was inlined from
156 // a caller, it would have been fully consistent with the GlobalsGraph
157 // in the caller so folding in is not necessary. Otherwise, this node came
158 // solely from this function's BU graph and so has to be made consistent.
159 //
160 Graph.updateFromGlobalGraph();
161
162 // Recompute the Incomplete markers. Depends on whether args are complete
Chris Lattnera8da51b2003-07-02 04:39:44 +0000163 unsigned Flags
164 = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000165 Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000166
167 // Delete dead nodes. Treat globals that are unreachable as dead also.
Chris Lattner4f2cfc02003-02-10 18:16:36 +0000168 Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
169
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000170 // We are done with computing the current TD Graph! Now move on to
171 // inlining the current graph into the graphs for its callees, if any.
172 //
Chris Lattnera8da51b2003-07-02 04:39:44 +0000173 const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();
174 if (FunctionCalls.empty()) {
Chris Lattner18f07a12003-07-01 16:28:11 +0000175 DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames()
176 << "\n");
177 return;
178 }
179
Chris Lattner18f07a12003-07-01 16:28:11 +0000180 // Now that we have information about all of the callees, propagate the
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000181 // current graph into the callees. Clone only the reachable subgraph at
182 // each call-site, not the entire graph (even though the entire graph
183 // would be cloned only once, this should still be better on average).
Chris Lattner18f07a12003-07-01 16:28:11 +0000184 //
185 DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
Chris Lattnera8da51b2003-07-02 04:39:44 +0000186 << FunctionCalls.size() << " call nodes.\n");
Chris Lattner18f07a12003-07-01 16:28:11 +0000187
Chris Lattnera8da51b2003-07-02 04:39:44 +0000188 const BUDataStructures::ActualCalleesTy &ActualCallees =
189 getAnalysis<BUDataStructures>().getActualCallees();
Chris Lattner18f07a12003-07-01 16:28:11 +0000190
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000191 // Loop over all the call sites and all the callees at each call site.
192 // Clone and merge the reachable subgraph from the call into callee's graph.
193 //
Chris Lattnera8da51b2003-07-02 04:39:44 +0000194 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000195 Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000196 // For each function in the invoked function list at this call site...
Chris Lattnera8da51b2003-07-02 04:39:44 +0000197 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
198 BUDataStructures::ActualCalleesTy::const_iterator>
Chris Lattner808a7ae2003-09-20 16:34:13 +0000199 IP = ActualCallees.equal_range(CallI);
Chris Lattnera8da51b2003-07-02 04:39:44 +0000200
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000201 // Multiple callees may have the same graph, so try to inline and merge
202 // only once for each <callSite,calleeGraph> pair, not once for each
203 // <callSite,calleeFunction> pair; the latter will be correct but slower.
204 hash_set<DSGraph*> GraphsSeen;
205
206 // Loop over each actual callee at this call site
207 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
208 I != IP.second; ++I) {
209 DSGraph& CalleeGraph = getDSGraph(*I->second);
210 assert(&CalleeGraph != &Graph && "TD need not inline graph into self!");
211
212 // if this callee graph is already done at this site, skip this callee
213 if (GraphsSeen.find(&CalleeGraph) != GraphsSeen.end())
214 continue;
215 GraphsSeen.insert(&CalleeGraph);
216
217 // Get the root nodes for cloning the reachable subgraph into each callee:
218 // -- all global nodes that appear in both the caller and the callee
219 // -- return value at this call site, if any
220 // -- actual arguments passed at this call site
221 // -- callee node at this call site, if this is an indirect call (this may
222 // not be needed for merging, but allows us to create CS and therefore
223 // simplify the merging below).
224 hash_set<const DSNode*> RootNodeSet;
225 for (DSGraph::ScalarMapTy::const_iterator
226 SI = CalleeGraph.getScalarMap().begin(),
227 SE = CalleeGraph.getScalarMap().end(); SI != SE; ++SI)
228 if (GlobalValue* GV = dyn_cast<GlobalValue>(SI->first)) {
229 DSGraph::ScalarMapTy::const_iterator GI=Graph.getScalarMap().find(GV);
230 if (GI != Graph.getScalarMap().end())
231 RootNodeSet.insert(GI->second.getNode());
Chris Lattnera8da51b2003-07-02 04:39:44 +0000232 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000233
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000234 if (const DSNode* RetNode = FunctionCalls[i].getRetVal().getNode())
235 RootNodeSet.insert(RetNode);
Chris Lattner0e744122002-10-17 04:26:54 +0000236
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000237 for (unsigned j=0, N=FunctionCalls[i].getNumPtrArgs(); j < N; ++j)
238 if (const DSNode* ArgTarget = FunctionCalls[i].getPtrArg(j).getNode())
239 RootNodeSet.insert(ArgTarget);
240
241 if (FunctionCalls[i].isIndirectCall())
242 RootNodeSet.insert(FunctionCalls[i].getCalleeNode());
243
Chris Lattnera8da51b2003-07-02 04:39:44 +0000244 DEBUG(std::cerr << " [TD] Resolving arguments for callee graph '"
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000245 << CalleeGraph.getFunctionNames()
246 << "': " << I->second->getFunctionType()->getNumParams()
247 << " args\n at call site (DSCallSite*) 0x"
248 << &FunctionCalls[i] << "\n");
249
250 DSGraph::NodeMapTy NodeMapInCallee; // map from nodes to clones in callee
251 DSGraph::NodeMapTy CompletedMap; // unused map for nodes not to do
252 CalleeGraph.cloneReachableSubgraph(Graph, RootNodeSet,
253 NodeMapInCallee, CompletedMap,
254 DSGraph::StripModRefBits |
255 DSGraph::KeepAllocaBit);
Chris Lattner7a211632002-11-08 21:28:37 +0000256
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000257 // Transform our call site info into the cloned version for CalleeGraph
258 DSCallSite CS(FunctionCalls[i], NodeMapInCallee);
Chris Lattnera8da51b2003-07-02 04:39:44 +0000259
Vikram S. Adve03e19dd2003-07-16 21:40:28 +0000260 // Get the formal argument and return nodes for the called function
261 // and merge them with the cloned subgraph. Global nodes were merged
262 // already by cloneReachableSubgraph() above.
263 CalleeGraph.getCallSiteForArguments(*I->second).mergeWith(CS);
264
265 ++NumTDInlines;
Chris Lattnera8da51b2003-07-02 04:39:44 +0000266 }
Chris Lattnere0fbd482003-02-09 18:42:43 +0000267 }
Chris Lattner18f07a12003-07-01 16:28:11 +0000268
269 DEBUG(std::cerr << " [TD] Done inlining into callees for: "
270 << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
271 << Graph.getFunctionCalls().size() << "]\n");
Vikram S. Adveaaeee752002-07-30 22:06:40 +0000272}
Chris Lattner4923d1b2003-02-03 22:51:28 +0000273