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 "DSCallSiteIterator.h"
16 Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
17 Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
19 RegisterAnalysis<BUDataStructures>
20 X("budatastructure", "Bottom-up Data Structure Analysis");
25 // run - Calculate the bottom up data structure graphs for each function in the
28 bool BUDataStructures::run(Module &M) {
29 LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
30 GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph());
31 GlobalsGraph->setPrintAuxCalls();
33 Function *MainFunc = M.getMainFunction();
35 calculateReachableGraphs(MainFunc);
37 // Calculate the graphs for any functions that are unreachable from main...
38 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
39 if (!I->isExternal() && !DSInfo.count(I)) {
42 std::cerr << "*** Function unreachable from main: "
43 << I->getName() << "\n";
45 calculateReachableGraphs(I); // Calculate all graphs...
50 void BUDataStructures::calculateReachableGraphs(Function *F) {
51 std::vector<Function*> Stack;
52 hash_map<Function*, unsigned> ValMap;
54 calculateGraphs(F, Stack, NextID, ValMap);
57 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
58 // Has the graph already been created?
59 DSGraph *&Graph = DSInfo[F];
60 if (Graph) return *Graph;
62 // Copy the local version into DSInfo...
63 Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(*F));
65 Graph->setGlobalsGraph(GlobalsGraph);
66 Graph->setPrintAuxCalls();
68 // Start with a copy of the original call sites...
69 Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
73 unsigned BUDataStructures::calculateGraphs(Function *F,
74 std::vector<Function*> &Stack,
76 hash_map<Function*, unsigned> &ValMap) {
77 assert(ValMap.find(F) == ValMap.end() && "Shouldn't revisit functions!");
78 unsigned Min = NextID++, MyID = Min;
82 if (F->isExternal()) { // sprintf, fprintf, sscanf, etc...
89 DSGraph &Graph = getOrCreateGraph(F);
91 // The edges out of the current node are the call site targets...
92 for (DSCallSiteIterator I = DSCallSiteIterator::begin_aux(Graph),
93 E = DSCallSiteIterator::end_aux(Graph); I != E; ++I) {
94 Function *Callee = *I;
96 // Have we visited the destination function yet?
97 hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
98 if (It == ValMap.end()) // No, visit it now.
99 M = calculateGraphs(Callee, Stack, NextID, ValMap);
100 else // Yes, get it's number.
102 if (M < Min) Min = M;
105 assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
107 return Min; // This is part of a larger SCC!
109 // If this is a new SCC, process it now.
110 if (Stack.back() == F) { // Special case the single "SCC" case here.
111 DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
112 << F->getName() << "\n");
114 DSGraph &G = getDSGraph(*F);
115 DEBUG(std::cerr << " [BU] Calculating graph for: " << F->getName()<< "\n");
117 DEBUG(std::cerr << " [BU] Done inlining: " << F->getName() << " ["
118 << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
121 if (MaxSCC < 1) MaxSCC = 1;
123 // Should we revisit the graph?
124 if (DSCallSiteIterator::begin_aux(G) != DSCallSiteIterator::end_aux(G)) {
126 return calculateGraphs(F, Stack, NextID, ValMap);
133 // SCCFunctions - Keep track of the functions in the current SCC
135 hash_set<Function*> SCCFunctions;
138 std::vector<Function*>::iterator FirstInSCC = Stack.end();
139 DSGraph *SCCGraph = 0;
143 SCCFunctions.insert(NF);
145 // Figure out which graph is the largest one, in order to speed things up
146 // a bit in situations where functions in the SCC have widely different
148 DSGraph &NFGraph = getDSGraph(*NF);
149 if (!SCCGraph || SCCGraph->getGraphSize() < NFGraph.getGraphSize())
153 std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
154 << SCCFunctions.size() << "\n";
156 // Compute the Max SCC Size...
157 if (MaxSCC < SCCFunctions.size())
158 MaxSCC = SCCFunctions.size();
160 // First thing first, collapse all of the DSGraphs into a single graph for
161 // the entire SCC. We computed the largest graph, so clone all of the other
162 // (smaller) graphs into it. Discard all of the old graphs.
164 for (hash_set<Function*>::iterator I = SCCFunctions.begin(),
165 E = SCCFunctions.end(); I != E; ++I) {
166 DSGraph &G = getDSGraph(**I);
167 if (&G != SCCGraph) {
168 DSGraph::NodeMapTy NodeMap;
169 SCCGraph->cloneInto(G, SCCGraph->getScalarMap(),
170 SCCGraph->getReturnNodes(), NodeMap, 0);
171 // Update the DSInfo map and delete the old graph...
172 DSInfo[*I] = SCCGraph;
177 // Clean up the graph before we start inlining a bunch again...
178 SCCGraph->removeTriviallyDeadNodes();
180 // Now that we have one big happy family, resolve all of the call sites in
182 calculateGraph(*SCCGraph);
183 DEBUG(std::cerr << " [BU] Done inlining SCC [" << SCCGraph->getGraphSize()
184 << "+" << SCCGraph->getAuxFunctionCalls().size() << "]\n");
186 std::cerr << "DONE with SCC #: " << MyID << "\n";
188 // We never have to revisit "SCC" processed functions...
190 // Drop the stuff we don't need from the end of the stack
191 Stack.erase(FirstInSCC, Stack.end());
195 return MyID; // == Min
199 // releaseMemory - If the pass pipeline is done with this pass, we can release
200 // our memory... here...
202 void BUDataStructures::releaseMemory() {
203 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
204 E = DSInfo.end(); I != E; ++I) {
205 I->second->getReturnNodes().erase(I->first);
206 if (I->second->getReturnNodes().empty())
210 // Empty map so next time memory is released, data structures are not
217 void BUDataStructures::calculateGraph(DSGraph &Graph) {
218 // Move our call site list into TempFCs so that inline call sites go into the
219 // new call site list and doesn't invalidate our iterators!
220 std::vector<DSCallSite> TempFCs;
221 std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
222 TempFCs.swap(AuxCallsList);
224 DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
226 // Loop over all of the resolvable call sites
227 unsigned LastCallSiteIdx = ~0U;
228 for (DSCallSiteIterator I = DSCallSiteIterator::begin(TempFCs),
229 E = DSCallSiteIterator::end(TempFCs); I != E; ++I) {
230 // If we skipped over any call sites, they must be unresolvable, copy them
231 // to the real call site list.
233 for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
234 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
235 LastCallSiteIdx = I.getCallSiteIdx();
237 // Resolve the current call...
238 Function *Callee = *I;
239 DSCallSite CS = I.getCallSite();
241 if (Callee->isExternal()) {
242 // Ignore this case, simple varargs functions we cannot stub out!
243 } else if (ReturnNodes.find(Callee) != ReturnNodes.end()) {
244 // Self recursion... simply link up the formal arguments with the
245 // actual arguments...
246 DEBUG(std::cerr << " Self Inlining: " << Callee->getName() << "\n");
248 // Handle self recursion by resolving the arguments and return value
249 Graph.mergeInGraph(CS, *Callee, Graph, 0);
252 ActualCallees.insert(std::make_pair(&CS.getCallInst(), Callee));
254 // Get the data structure graph for the called function.
256 DSGraph &GI = getDSGraph(*Callee); // Graph to inline
258 DEBUG(std::cerr << " Inlining graph for " << Callee->getName()
259 << "[" << GI.getGraphSize() << "+"
260 << GI.getAuxFunctionCalls().size() << "] into '"
261 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() << "+"
262 << Graph.getAuxFunctionCalls().size() << "]\n");
264 // Handle self recursion by resolving the arguments and return value
265 Graph.mergeInGraph(CS, *Callee, GI,
266 DSGraph::KeepModRefBits |
267 DSGraph::StripAllocaBit | DSGraph::DontCloneCallNodes);
271 Graph.writeGraphToFile(std::cerr, "bu_" + F.getName() + "_after_" +
277 // Make sure to catch any leftover unresolvable calls...
278 for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
279 AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
283 // Recompute the Incomplete markers. If there are any function calls left
284 // now that are complete, we must loop!
285 Graph.maskIncompleteMarkers();
286 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
287 // FIXME: materialize nodes from the globals graph as neccesary...
288 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
290 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());