1 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural 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 BUDataStructures class, which represents the
11 // Bottom-Up Interprocedural closure of the data structure graph over the
12 // program. This is useful for applications like pool allocation, but **not**
13 // applications like alias analysis.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Analysis/DataStructure.h"
18 #include "llvm/Module.h"
19 #include "Support/Statistic.h"
20 #include "Support/Debug.h"
21 #include "DSCallSiteIterator.h"
25 Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
26 Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
27 Statistic<> NumCallEdges("budatastructures", "Number of 'actual' call edges");
29 RegisterAnalysis<BUDataStructures>
30 X("budatastructure", "Bottom-up Data Structure Analysis");
35 // run - Calculate the bottom up data structure graphs for each function in the
38 bool BUDataStructures::run(Module &M) {
39 LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
40 GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph());
41 GlobalsGraph->setPrintAuxCalls();
43 Function *MainFunc = M.getMainFunction();
45 calculateReachableGraphs(MainFunc);
47 // Calculate the graphs for any functions that are unreachable from main...
48 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
49 if (!I->isExternal() && !DSInfo.count(I)) {
52 std::cerr << "*** Function unreachable from main: "
53 << I->getName() << "\n";
55 calculateReachableGraphs(I); // Calculate all graphs...
58 NumCallEdges += ActualCallees.size();
60 // At the end of the bottom-up pass, the globals graph becomes complete.
61 // FIXME: This is not the right way to do this, but it is sorta better than
62 // nothing! In particular, externally visible globals and unresolvable call
63 // nodes at the end of the BU phase should make things that they point to
64 // incomplete in the globals graph.
66 GlobalsGraph->removeTriviallyDeadNodes();
67 GlobalsGraph->maskIncompleteMarkers();
71 void BUDataStructures::calculateReachableGraphs(Function *F) {
72 std::vector<Function*> Stack;
73 hash_map<Function*, unsigned> ValMap;
75 calculateGraphs(F, Stack, NextID, ValMap);
78 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
79 // Has the graph already been created?
80 DSGraph *&Graph = DSInfo[F];
81 if (Graph) return *Graph;
83 // Copy the local version into DSInfo...
84 Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(*F));
86 Graph->setGlobalsGraph(GlobalsGraph);
87 Graph->setPrintAuxCalls();
89 // Start with a copy of the original call sites...
90 Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
94 unsigned BUDataStructures::calculateGraphs(Function *F,
95 std::vector<Function*> &Stack,
97 hash_map<Function*, unsigned> &ValMap) {
98 assert(!ValMap.count(F) && "Shouldn't revisit functions!");
99 unsigned Min = NextID++, MyID = Min;
103 if (F->isExternal()) { // sprintf, fprintf, sscanf, etc...
110 DSGraph &Graph = getOrCreateGraph(F);
112 // The edges out of the current node are the call site targets...
113 for (DSCallSiteIterator I = DSCallSiteIterator::begin_aux(Graph),
114 E = DSCallSiteIterator::end_aux(Graph); I != E; ++I) {
115 Function *Callee = *I;
117 // Have we visited the destination function yet?
118 hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
119 if (It == ValMap.end()) // No, visit it now.
120 M = calculateGraphs(Callee, Stack, NextID, ValMap);
121 else // Yes, get it's number.
123 if (M < Min) Min = M;
126 assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
128 return Min; // This is part of a larger SCC!
130 // If this is a new SCC, process it now.
131 if (Stack.back() == F) { // Special case the single "SCC" case here.
132 DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
133 << F->getName() << "\n");
135 DSGraph &G = getDSGraph(*F);
136 DEBUG(std::cerr << " [BU] Calculating graph for: " << F->getName()<< "\n");
138 DEBUG(std::cerr << " [BU] Done inlining: " << F->getName() << " ["
139 << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
142 if (MaxSCC < 1) MaxSCC = 1;
144 // Should we revisit the graph?
145 if (DSCallSiteIterator::begin_aux(G) != DSCallSiteIterator::end_aux(G)) {
147 return calculateGraphs(F, Stack, NextID, ValMap);
154 // SCCFunctions - Keep track of the functions in the current SCC
156 hash_set<DSGraph*> SCCGraphs;
159 std::vector<Function*>::iterator FirstInSCC = Stack.end();
160 DSGraph *SCCGraph = 0;
165 // Figure out which graph is the largest one, in order to speed things up
166 // a bit in situations where functions in the SCC have widely different
168 DSGraph &NFGraph = getDSGraph(*NF);
169 SCCGraphs.insert(&NFGraph);
170 if (!SCCGraph || SCCGraph->getGraphSize() < NFGraph.getGraphSize())
174 std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
175 << SCCGraphs.size() << "\n";
177 // Compute the Max SCC Size...
178 if (MaxSCC < SCCGraphs.size())
179 MaxSCC = SCCGraphs.size();
181 // First thing first, collapse all of the DSGraphs into a single graph for
182 // the entire SCC. We computed the largest graph, so clone all of the other
183 // (smaller) graphs into it. Discard all of the old graphs.
185 for (hash_set<DSGraph*>::iterator I = SCCGraphs.begin(),
186 E = SCCGraphs.end(); I != E; ++I) {
188 if (&G != SCCGraph) {
189 DSGraph::NodeMapTy NodeMap;
190 SCCGraph->cloneInto(G, SCCGraph->getScalarMap(),
191 SCCGraph->getReturnNodes(), NodeMap);
192 // Update the DSInfo map and delete the old graph...
193 for (DSGraph::ReturnNodesTy::iterator I = G.getReturnNodes().begin(),
194 E = G.getReturnNodes().end(); I != E; ++I)
195 DSInfo[I->first] = SCCGraph;
200 // Clean up the graph before we start inlining a bunch again...
201 SCCGraph->removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
203 // Now that we have one big happy family, resolve all of the call sites in
205 calculateGraph(*SCCGraph);
206 DEBUG(std::cerr << " [BU] Done inlining SCC [" << SCCGraph->getGraphSize()
207 << "+" << SCCGraph->getAuxFunctionCalls().size() << "]\n");
209 std::cerr << "DONE with SCC #: " << MyID << "\n";
211 // We never have to revisit "SCC" processed functions...
213 // Drop the stuff we don't need from the end of the stack
214 Stack.erase(FirstInSCC, Stack.end());
218 return MyID; // == Min
222 // releaseMemory - If the pass pipeline is done with this pass, we can release
223 // our memory... here...
225 void BUDataStructures::releaseMemory() {
226 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
227 E = DSInfo.end(); I != E; ++I) {
228 I->second->getReturnNodes().erase(I->first);
229 if (I->second->getReturnNodes().empty())
233 // Empty map so next time memory is released, data structures are not
240 void BUDataStructures::calculateGraph(DSGraph &Graph) {
241 // Move our call site list into TempFCs so that inline call sites go into the
242 // new call site list and doesn't invalidate our iterators!
243 std::vector<DSCallSite> TempFCs;
244 std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
245 TempFCs.swap(AuxCallsList);
247 DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
249 // Loop over all of the resolvable call sites
250 unsigned LastCallSiteIdx = ~0U;
251 for (DSCallSiteIterator I = DSCallSiteIterator::begin(TempFCs),
252 E = DSCallSiteIterator::end(TempFCs); I != E; ++I) {
253 // If we skipped over any call sites, they must be unresolvable, copy them
254 // to the real call site list.
256 for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
257 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
258 LastCallSiteIdx = I.getCallSiteIdx();
260 // Resolve the current call...
261 Function *Callee = *I;
262 DSCallSite CS = I.getCallSite();
264 if (Callee->isExternal()) {
265 // Ignore this case, simple varargs functions we cannot stub out!
266 } else if (ReturnNodes.count(Callee)) {
267 // Self recursion... simply link up the formal arguments with the
268 // actual arguments...
269 DEBUG(std::cerr << " Self Inlining: " << Callee->getName() << "\n");
271 // Handle self recursion by resolving the arguments and return value
272 Graph.mergeInGraph(CS, *Callee, Graph, 0);
275 ActualCallees.insert(std::make_pair(CS.getCallSite().getInstruction(),
278 // Get the data structure graph for the called function.
280 DSGraph &GI = getDSGraph(*Callee); // Graph to inline
282 if (Callee->getName() == "bc_raise")
283 std::cerr << "HERE!\n";
285 DEBUG(std::cerr << " Inlining graph for " << Callee->getName()
286 << "[" << GI.getGraphSize() << "+"
287 << GI.getAuxFunctionCalls().size() << "] into '"
288 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() << "+"
289 << Graph.getAuxFunctionCalls().size() << "]\n");
291 Graph.mergeInGraph(CS, *Callee, GI,
292 DSGraph::KeepModRefBits |
293 DSGraph::StripAllocaBit | DSGraph::DontCloneCallNodes);
297 Graph.writeGraphToFile(std::cerr, "bu_" + F.getName() + "_after_" +
303 // Make sure to catch any leftover unresolvable calls...
304 for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
305 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
309 // Recompute the Incomplete markers
310 assert(Graph.getInlinedGlobals().empty());
311 Graph.maskIncompleteMarkers();
312 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
314 // Delete dead nodes. Treat globals that are unreachable but that can
315 // reach live nodes as live.
316 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
318 // When this graph is finalized, clone the globals in the graph into the
319 // globals graph to make sure it has everything, from all graphs.
320 DSScalarMap &MainSM = Graph.getScalarMap();
321 ReachabilityCloner RC(*GlobalsGraph, Graph, DSGraph::StripAllocaBit);
323 // Clone everything reachable from globals in the "main" graph into the
325 for (DSScalarMap::global_iterator I = MainSM.global_begin(),
326 E = MainSM.global_end(); I != E; ++I)
327 RC.getClonedNH(MainSM[*I]);
329 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());