1 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
3 // This file implements the BUDataStructures class, which represents the
4 // Bottom-Up Interprocedural closure of the data structure graph over the
5 // program. This is useful for applications like pool allocation, but **not**
6 // applications like alias analysis.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Analysis/DataStructure.h"
11 #include "llvm/Module.h"
12 #include "Support/Statistic.h"
13 #include "Support/Debug.h"
14 #include "DSCallSiteIterator.h"
17 Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
18 Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
19 Statistic<> NumCallEdges("budatastructures", "Number of 'actual' call edges");
21 RegisterAnalysis<BUDataStructures>
22 X("budatastructure", "Bottom-up Data Structure Analysis");
27 // run - Calculate the bottom up data structure graphs for each function in the
30 bool BUDataStructures::run(Module &M) {
31 LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
32 GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph());
33 GlobalsGraph->setPrintAuxCalls();
35 Function *MainFunc = M.getMainFunction();
37 calculateReachableGraphs(MainFunc);
39 // Calculate the graphs for any functions that are unreachable from main...
40 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
41 if (!I->isExternal() && !DSInfo.count(I)) {
44 std::cerr << "*** Function unreachable from main: "
45 << I->getName() << "\n";
47 calculateReachableGraphs(I); // Calculate all graphs...
50 NumCallEdges += ActualCallees.size();
54 void BUDataStructures::calculateReachableGraphs(Function *F) {
55 std::vector<Function*> Stack;
56 hash_map<Function*, unsigned> ValMap;
58 calculateGraphs(F, Stack, NextID, ValMap);
61 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
62 // Has the graph already been created?
63 DSGraph *&Graph = DSInfo[F];
64 if (Graph) return *Graph;
66 // Copy the local version into DSInfo...
67 Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(*F));
69 Graph->setGlobalsGraph(GlobalsGraph);
70 Graph->setPrintAuxCalls();
72 // Start with a copy of the original call sites...
73 Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
77 unsigned BUDataStructures::calculateGraphs(Function *F,
78 std::vector<Function*> &Stack,
80 hash_map<Function*, unsigned> &ValMap) {
81 assert(ValMap.find(F) == ValMap.end() && "Shouldn't revisit functions!");
82 unsigned Min = NextID++, MyID = Min;
86 if (F->isExternal()) { // sprintf, fprintf, sscanf, etc...
93 DSGraph &Graph = getOrCreateGraph(F);
95 // The edges out of the current node are the call site targets...
96 for (DSCallSiteIterator I = DSCallSiteIterator::begin_aux(Graph),
97 E = DSCallSiteIterator::end_aux(Graph); I != E; ++I) {
98 Function *Callee = *I;
100 // Have we visited the destination function yet?
101 hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
102 if (It == ValMap.end()) // No, visit it now.
103 M = calculateGraphs(Callee, Stack, NextID, ValMap);
104 else // Yes, get it's number.
106 if (M < Min) Min = M;
109 assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
111 return Min; // This is part of a larger SCC!
113 // If this is a new SCC, process it now.
114 if (Stack.back() == F) { // Special case the single "SCC" case here.
115 DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
116 << F->getName() << "\n");
118 DSGraph &G = getDSGraph(*F);
119 DEBUG(std::cerr << " [BU] Calculating graph for: " << F->getName()<< "\n");
121 DEBUG(std::cerr << " [BU] Done inlining: " << F->getName() << " ["
122 << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
125 if (MaxSCC < 1) MaxSCC = 1;
127 // Should we revisit the graph?
128 if (DSCallSiteIterator::begin_aux(G) != DSCallSiteIterator::end_aux(G)) {
130 return calculateGraphs(F, Stack, NextID, ValMap);
137 // SCCFunctions - Keep track of the functions in the current SCC
139 hash_set<Function*> SCCFunctions;
142 std::vector<Function*>::iterator FirstInSCC = Stack.end();
143 DSGraph *SCCGraph = 0;
147 SCCFunctions.insert(NF);
149 // Figure out which graph is the largest one, in order to speed things up
150 // a bit in situations where functions in the SCC have widely different
152 DSGraph &NFGraph = getDSGraph(*NF);
153 if (!SCCGraph || SCCGraph->getGraphSize() < NFGraph.getGraphSize())
157 std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
158 << SCCFunctions.size() << "\n";
160 // Compute the Max SCC Size...
161 if (MaxSCC < SCCFunctions.size())
162 MaxSCC = SCCFunctions.size();
164 // First thing first, collapse all of the DSGraphs into a single graph for
165 // the entire SCC. We computed the largest graph, so clone all of the other
166 // (smaller) graphs into it. Discard all of the old graphs.
168 for (hash_set<Function*>::iterator I = SCCFunctions.begin(),
169 E = SCCFunctions.end(); I != E; ++I) {
170 DSGraph &G = getDSGraph(**I);
171 if (&G != SCCGraph) {
172 DSGraph::NodeMapTy NodeMap;
173 SCCGraph->cloneInto(G, SCCGraph->getScalarMap(),
174 SCCGraph->getReturnNodes(), NodeMap, 0);
175 // Update the DSInfo map and delete the old graph...
176 DSInfo[*I] = SCCGraph;
181 // Clean up the graph before we start inlining a bunch again...
182 SCCGraph->removeTriviallyDeadNodes();
184 // Now that we have one big happy family, resolve all of the call sites in
186 calculateGraph(*SCCGraph);
187 DEBUG(std::cerr << " [BU] Done inlining SCC [" << SCCGraph->getGraphSize()
188 << "+" << SCCGraph->getAuxFunctionCalls().size() << "]\n");
190 std::cerr << "DONE with SCC #: " << MyID << "\n";
192 // We never have to revisit "SCC" processed functions...
194 // Drop the stuff we don't need from the end of the stack
195 Stack.erase(FirstInSCC, Stack.end());
199 return MyID; // == Min
203 // releaseMemory - If the pass pipeline is done with this pass, we can release
204 // our memory... here...
206 void BUDataStructures::releaseMemory() {
207 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
208 E = DSInfo.end(); I != E; ++I) {
209 I->second->getReturnNodes().erase(I->first);
210 if (I->second->getReturnNodes().empty())
214 // Empty map so next time memory is released, data structures are not
221 void BUDataStructures::calculateGraph(DSGraph &Graph) {
222 // Move our call site list into TempFCs so that inline call sites go into the
223 // new call site list and doesn't invalidate our iterators!
224 std::vector<DSCallSite> TempFCs;
225 std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
226 TempFCs.swap(AuxCallsList);
228 DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
230 // Loop over all of the resolvable call sites
231 unsigned LastCallSiteIdx = ~0U;
232 for (DSCallSiteIterator I = DSCallSiteIterator::begin(TempFCs),
233 E = DSCallSiteIterator::end(TempFCs); I != E; ++I) {
234 // If we skipped over any call sites, they must be unresolvable, copy them
235 // to the real call site list.
237 for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
238 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
239 LastCallSiteIdx = I.getCallSiteIdx();
241 // Resolve the current call...
242 Function *Callee = *I;
243 DSCallSite CS = I.getCallSite();
245 if (Callee->isExternal()) {
246 // Ignore this case, simple varargs functions we cannot stub out!
247 } else if (ReturnNodes.find(Callee) != ReturnNodes.end()) {
248 // Self recursion... simply link up the formal arguments with the
249 // actual arguments...
250 DEBUG(std::cerr << " Self Inlining: " << Callee->getName() << "\n");
252 // Handle self recursion by resolving the arguments and return value
253 Graph.mergeInGraph(CS, *Callee, Graph, 0);
256 ActualCallees.insert(std::make_pair(&CS.getCallInst(), Callee));
258 // Get the data structure graph for the called function.
260 DSGraph &GI = getDSGraph(*Callee); // Graph to inline
262 DEBUG(std::cerr << " Inlining graph for " << Callee->getName()
263 << "[" << GI.getGraphSize() << "+"
264 << GI.getAuxFunctionCalls().size() << "] into '"
265 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() << "+"
266 << Graph.getAuxFunctionCalls().size() << "]\n");
268 // Handle self recursion by resolving the arguments and return value
269 Graph.mergeInGraph(CS, *Callee, GI,
270 DSGraph::KeepModRefBits |
271 DSGraph::StripAllocaBit | DSGraph::DontCloneCallNodes);
275 Graph.writeGraphToFile(std::cerr, "bu_" + F.getName() + "_after_" +
281 // Make sure to catch any leftover unresolvable calls...
282 for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
283 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
287 // Re-materialize nodes from the globals graph.
288 // Do not ignore globals inlined from callees -- they are not up-to-date!
289 Graph.getInlinedGlobals().clear();
290 Graph.updateFromGlobalGraph();
292 // Recompute the Incomplete markers
293 Graph.maskIncompleteMarkers();
294 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
296 // Delete dead nodes. Treat globals that are unreachable but that can
297 // reach live nodes as live.
298 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
300 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());