1 //===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
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.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Analysis/DataStructure.h"
11 #include "llvm/Module.h"
12 #include "llvm/DerivedTypes.h"
13 #include "Support/Debug.h"
14 #include "Support/Statistic.h"
15 #include "DSCallSiteIterator.h"
18 RegisterAnalysis<TDDataStructures> // Register the pass
19 Y("tddatastructure", "Top-down Data Structure Analysis");
21 Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
24 /// FunctionHasCompleteArguments - This function returns true if it is safe not
25 /// to mark arguments to the function complete.
27 /// FIXME: Need to check if all callers have been found, or rather if a
28 /// funcpointer escapes!
30 static bool FunctionHasCompleteArguments(Function &F) {
31 return F.hasInternalLinkage();
34 // run - Calculate the top down data structure graphs for each function in the
37 bool TDDataStructures::run(Module &M) {
38 BUDataStructures &BU = getAnalysis<BUDataStructures>();
39 GlobalsGraph = new DSGraph(BU.getGlobalsGraph());
41 // 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);
47 // 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();
54 // Calculate top-down from main...
55 if (Function *F = M.getMainFunction())
56 ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
58 // Next calculate the graphs for each unreachable function...
59 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
60 ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);
62 VisitedGraph.clear(); // Release memory!
64 // Visit each of the graphs in reverse post-order now!
65 while (!PostOrder.empty()) {
66 inlineGraphIntoCallees(*PostOrder.back());
70 ArgsRemainIncomplete.clear();
75 DSGraph &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();
80 G->setPrintAuxCalls();
81 G->setGlobalsGraph(GlobalsGraph);
87 void 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;
95 // Recursively traverse all of the callee graphs.
96 const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls();
98 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
99 Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
100 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
101 BUDataStructures::ActualCalleesTy::const_iterator>
102 IP = ActualCallees.equal_range(CallI);
104 for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
106 ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
109 PostOrder.push_back(&G);
116 // releaseMemory - If the pass pipeline is done with this pass, we can release
117 // our memory... here...
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.
122 void 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())
130 // Empty map so next time memory is released, data structures are not
137 void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
138 // Recompute the Incomplete markers and eliminate unreachable nodes.
139 Graph.removeTriviallyDeadNodes();
140 Graph.maskIncompleteMarkers();
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;
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.
160 Graph.updateFromGlobalGraph();
162 // Recompute the Incomplete markers. Depends on whether args are complete
164 = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
165 Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
167 // Delete dead nodes. Treat globals that are unreachable as dead also.
168 Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
170 // 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.
173 const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();
174 if (FunctionCalls.empty()) {
175 DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames()
180 // Now that we have information about all of the callees, propagate the
181 // 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).
185 DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
186 << FunctionCalls.size() << " call nodes.\n");
188 const BUDataStructures::ActualCalleesTy &ActualCallees =
189 getAnalysis<BUDataStructures>().getActualCallees();
191 // 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.
194 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
195 Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
196 // For each function in the invoked function list at this call site...
197 std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
198 BUDataStructures::ActualCalleesTy::const_iterator>
199 IP = ActualCallees.equal_range(CallI);
201 // 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;
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!");
212 // if this callee graph is already done at this site, skip this callee
213 if (GraphsSeen.find(&CalleeGraph) != GraphsSeen.end())
215 GraphsSeen.insert(&CalleeGraph);
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());
234 if (const DSNode* RetNode = FunctionCalls[i].getRetVal().getNode())
235 RootNodeSet.insert(RetNode);
237 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);
241 if (FunctionCalls[i].isIndirectCall())
242 RootNodeSet.insert(FunctionCalls[i].getCalleeNode());
244 DEBUG(std::cerr << " [TD] Resolving arguments for callee graph '"
245 << CalleeGraph.getFunctionNames()
246 << "': " << I->second->getFunctionType()->getNumParams()
247 << " args\n at call site (DSCallSite*) 0x"
248 << &FunctionCalls[i] << "\n");
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);
257 // Transform our call site info into the cloned version for CalleeGraph
258 DSCallSite CS(FunctionCalls[i], NodeMapInCallee);
260 // 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);
269 DEBUG(std::cerr << " [TD] Done inlining into callees for: "
270 << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
271 << Graph.getFunctionCalls().size() << "]\n");