1 //===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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"
27 RegisterAnalysis<TDDataStructures> // Register the pass
28 Y("tddatastructure", "Top-down Data Structure Analysis");
30 Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
33 void TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,
34 hash_set<DSNode*> &Visited) {
35 if (!N || Visited.count(N)) return;
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);
46 markReachableFunctionsExternallyAccessible(NN, Visited);
52 // run - Calculate the top down data structure graphs for each function in the
55 bool TDDataStructures::run(Module &M) {
56 BUDataStructures &BU = getAnalysis<BUDataStructures>();
57 GlobalsGraph = new DSGraph(BU.getGlobalsGraph());
58 GlobalsGraph->setPrintAuxCalls();
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
64 const DSGraph::ScalarMapTy &GGSM = GlobalsGraph->getScalarMap();
65 hash_set<DSNode*> Visited;
66 for (DSGraph::ScalarMapTy::const_iterator I = GGSM.begin(), E = GGSM.end();
68 if (isa<GlobalValue>(I->first))
69 markReachableFunctionsExternallyAccessible(I->second.getNode(), Visited);
71 // Loop over unresolved call nodes. Any functions passed into (but not
72 // returned!?) from unresolvable call nodes may be invoked outside of the
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(),
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);
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();
95 // Calculate top-down from main...
96 if (Function *F = M.getMainFunction())
97 ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
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);
103 VisitedGraph.clear(); // Release memory!
105 // Visit each of the graphs in reverse post-order now!
106 while (!PostOrder.empty()) {
107 inlineGraphIntoCallees(*PostOrder.back());
108 PostOrder.pop_back();
111 ArgsRemainIncomplete.clear();
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);
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;
136 // Recursively traverse all of the callee graphs.
137 const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls();
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);
145 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
147 ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
150 PostOrder.push_back(&G);
157 // releaseMemory - If the pass pipeline is done with this pass, we can release
158 // our memory... here...
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.
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())
171 // Empty map so next time memory is released, data structures are not
178 void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
179 // Recompute the Incomplete markers and eliminate unreachable nodes.
180 Graph.removeTriviallyDeadNodes();
181 Graph.maskIncompleteMarkers();
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;
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.
201 Graph.updateFromGlobalGraph();
203 // Recompute the Incomplete markers. Depends on whether args are complete
205 = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
206 Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
208 // Delete dead nodes. Treat globals that are unreachable as dead also.
209 Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
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.
214 const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();
215 if (FunctionCalls.empty()) {
216 DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames()
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).
226 DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
227 << FunctionCalls.size() << " call nodes.\n");
229 const BUDataStructures::ActualCalleesTy &ActualCallees =
230 getAnalysis<BUDataStructures>().getActualCallees();
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.
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);
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;
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!");
253 // if this callee graph is already done at this site, skip this callee
254 if (GraphsSeen.find(&CalleeGraph) != GraphsSeen.end())
256 GraphsSeen.insert(&CalleeGraph);
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());
275 if (const DSNode* RetNode = FunctionCalls[i].getRetVal().getNode())
276 RootNodeSet.insert(RetNode);
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);
282 if (FunctionCalls[i].isIndirectCall())
283 RootNodeSet.insert(FunctionCalls[i].getCalleeNode());
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");
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);
298 // Transform our call site info into the cloned version for CalleeGraph
299 DSCallSite CS(FunctionCalls[i], NodeMapInCallee);
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);
310 DEBUG(std::cerr << " [TD] Done inlining into callees for: "
311 << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
312 << Graph.getFunctionCalls().size() << "]\n");
315 } // End llvm namespace