This replaces the correct but slow code with a more aggressive scc-finder
[oota-llvm.git] / lib / Analysis / DataStructure / BottomUpClosure.cpp
1 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/DataStructure/DataStructure.h"
18 #include "llvm/Analysis/DataStructure/DSGraph.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Support/Debug.h"
22 using namespace llvm;
23
24 namespace {
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");
28   
29   RegisterAnalysis<BUDataStructures>
30   X("budatastructure", "Bottom-up Data Structure Analysis");
31 }
32
33 // run - Calculate the bottom up data structure graphs for each function in the
34 // program.
35 //
36 bool BUDataStructures::runOnModule(Module &M) {
37   LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
38   GlobalECs = LocalDSA.getGlobalECs();
39
40   GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph(), GlobalECs);
41   GlobalsGraph->setPrintAuxCalls();
42
43   IndCallGraphMap = new std::map<std::vector<Function*>,
44                            std::pair<DSGraph*, std::vector<DSNodeHandle> > >();
45
46   std::vector<Function*> Stack;
47   hash_map<Function*, unsigned> ValMap;
48   unsigned NextID = 1;
49
50   Function *MainFunc = M.getMainFunction();
51   if (MainFunc)
52     calculateGraphs(MainFunc, Stack, NextID, ValMap);
53
54   // Calculate the graphs for any functions that are unreachable from main...
55   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
56     if (!I->isExternal() && !DSInfo.count(I)) {
57 #ifndef NDEBUG
58       if (MainFunc)
59         std::cerr << "*** Function unreachable from main: "
60                   << I->getName() << "\n";
61 #endif
62       calculateGraphs(I, Stack, NextID, ValMap);     // Calculate all graphs.
63     }
64
65   NumCallEdges += ActualCallees.size();
66
67   // If we computed any temporary indcallgraphs, free them now.
68   for (std::map<std::vector<Function*>,
69          std::pair<DSGraph*, std::vector<DSNodeHandle> > >::iterator I =
70          IndCallGraphMap->begin(), E = IndCallGraphMap->end(); I != E; ++I) {
71     I->second.second.clear();  // Drop arg refs into the graph.
72     delete I->second.first;
73   }
74   delete IndCallGraphMap;
75
76   // At the end of the bottom-up pass, the globals graph becomes complete.
77   // FIXME: This is not the right way to do this, but it is sorta better than
78   // nothing!  In particular, externally visible globals and unresolvable call
79   // nodes at the end of the BU phase should make things that they point to
80   // incomplete in the globals graph.
81   // 
82   GlobalsGraph->removeTriviallyDeadNodes();
83   GlobalsGraph->maskIncompleteMarkers();
84
85   // Mark external globals incomplete.
86   GlobalsGraph->markIncompleteNodes(DSGraph::IgnoreGlobals);
87
88   // Merge the globals variables (not the calls) from the globals graph back
89   // into the main function's graph so that the main function contains all of
90   // the information about global pools and GV usage in the program.
91   if (MainFunc && !MainFunc->isExternal()) {
92     DSGraph &MainGraph = getOrCreateGraph(MainFunc);
93     const DSGraph &GG = *MainGraph.getGlobalsGraph();
94     ReachabilityCloner RC(MainGraph, GG, 
95                           DSGraph::DontCloneCallNodes |
96                           DSGraph::DontCloneAuxCallNodes);
97
98     // Clone the global nodes into this graph.
99     for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
100            E = GG.getScalarMap().global_end(); I != E; ++I)
101       if (isa<GlobalVariable>(*I))
102         RC.getClonedNH(GG.getNodeForValue(*I));
103
104     MainGraph.maskIncompleteMarkers();
105     MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs | 
106                                   DSGraph::IgnoreGlobals);
107   }
108
109   return false;
110 }
111
112 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
113   // Has the graph already been created?
114   DSGraph *&Graph = DSInfo[F];
115   if (Graph) return *Graph;
116
117   // Copy the local version into DSInfo...
118   Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(*F),
119                       GlobalECs);
120
121   Graph->setGlobalsGraph(GlobalsGraph);
122   Graph->setPrintAuxCalls();
123
124   // Start with a copy of the original call sites...
125   Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
126   return *Graph;
127 }
128
129 static bool isVAHackFn(const Function *F) {
130   return F->getName() == "printf"  || F->getName() == "sscanf" ||
131     F->getName() == "fprintf" || F->getName() == "open" ||
132     F->getName() == "sprintf" || F->getName() == "fputs" ||
133     F->getName() == "fscanf";
134 }
135
136 static bool isResolvableFunc(const Function* callee) {
137   return !callee->isExternal() || isVAHackFn(callee);
138 }
139
140 static void GetAllCallees(const DSCallSite &CS, 
141                           std::vector<Function*> &Callees) {
142   if (CS.isDirectCall()) {
143     if (isResolvableFunc(CS.getCalleeFunc()))
144       Callees.push_back(CS.getCalleeFunc());
145   } else if (!CS.getCalleeNode()->isIncomplete()) {
146     // Get all callees.
147     unsigned OldSize = Callees.size();
148     CS.getCalleeNode()->addFullFunctionList(Callees);
149     
150     // If any of the callees are unresolvable, remove the whole batch!
151     for (unsigned i = OldSize, e = Callees.size(); i != e; ++i)
152       if (!isResolvableFunc(Callees[i])) {
153         Callees.erase(Callees.begin()+OldSize, Callees.end());
154         return;
155       }
156   }
157 }
158
159
160 /// GetAllAuxCallees - Return a list containing all of the resolvable callees in
161 /// the aux list for the specified graph in the Callees vector.
162 static void GetAllAuxCallees(DSGraph &G, std::vector<Function*> &Callees) {
163   Callees.clear();
164   for (DSGraph::afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
165     GetAllCallees(*I, Callees);
166 }
167
168 unsigned BUDataStructures::calculateGraphs(Function *F,
169                                            std::vector<Function*> &Stack,
170                                            unsigned &NextID, 
171                                      hash_map<Function*, unsigned> &ValMap) {
172   assert(!ValMap.count(F) && "Shouldn't revisit functions!");
173   unsigned Min = NextID++, MyID = Min;
174   ValMap[F] = Min;
175   Stack.push_back(F);
176
177   // FIXME!  This test should be generalized to be any function that we have
178   // already processed, in the case when there isn't a main or there are
179   // unreachable functions!
180   if (F->isExternal()) {   // sprintf, fprintf, sscanf, etc...
181     // No callees!
182     Stack.pop_back();
183     ValMap[F] = ~0;
184     return Min;
185   }
186
187   DSGraph &Graph = getOrCreateGraph(F);
188
189   // Find all callee functions.
190   std::vector<Function*> CalleeFunctions;
191   GetAllAuxCallees(Graph, CalleeFunctions);
192
193   // The edges out of the current node are the call site targets...
194   for (unsigned i = 0, e = CalleeFunctions.size(); i != e; ++i) {
195     Function *Callee = CalleeFunctions[i];
196     unsigned M;
197     // Have we visited the destination function yet?
198     hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
199     if (It == ValMap.end())  // No, visit it now.
200       M = calculateGraphs(Callee, Stack, NextID, ValMap);
201     else                    // Yes, get it's number.
202       M = It->second;
203     if (M < Min) Min = M;
204   }
205
206   assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
207   if (Min != MyID)
208     return Min;         // This is part of a larger SCC!
209
210   // If this is a new SCC, process it now.
211   if (Stack.back() == F) {           // Special case the single "SCC" case here.
212     DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
213                     << F->getName() << "\n");
214     Stack.pop_back();
215     DSGraph &G = getDSGraph(*F);
216     DEBUG(std::cerr << "  [BU] Calculating graph for: " << F->getName()<< "\n");
217     calculateGraph(G);
218     DEBUG(std::cerr << "  [BU] Done inlining: " << F->getName() << " ["
219                     << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
220                     << "]\n");
221
222     if (MaxSCC < 1) MaxSCC = 1;
223
224     // Should we revisit the graph?  Only do it if there are now new resolvable
225     // callees.
226     GetAllAuxCallees(Graph, CalleeFunctions);
227     if (!CalleeFunctions.empty()) {
228       ValMap.erase(F);
229       return calculateGraphs(F, Stack, NextID, ValMap);
230     } else {
231       ValMap[F] = ~0U;
232     }
233     return MyID;
234
235   } else {
236     // SCCFunctions - Keep track of the functions in the current SCC
237     //
238     hash_set<DSGraph*> SCCGraphs;
239
240     Function *NF;
241     std::vector<Function*>::iterator FirstInSCC = Stack.end();
242     DSGraph *SCCGraph = 0;
243     do {
244       NF = *--FirstInSCC;
245       ValMap[NF] = ~0U;
246
247       // Figure out which graph is the largest one, in order to speed things up
248       // a bit in situations where functions in the SCC have widely different
249       // graph sizes.
250       DSGraph &NFGraph = getDSGraph(*NF);
251       SCCGraphs.insert(&NFGraph);
252       // FIXME: If we used a better way of cloning graphs (ie, just splice all
253       // of the nodes into the new graph), this would be completely unneeded!
254       if (!SCCGraph || SCCGraph->getGraphSize() < NFGraph.getGraphSize())
255         SCCGraph = &NFGraph;
256     } while (NF != F);
257
258     std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
259               << SCCGraphs.size() << "\n";
260
261     // Compute the Max SCC Size...
262     if (MaxSCC < SCCGraphs.size())
263       MaxSCC = SCCGraphs.size();
264
265     // First thing first, collapse all of the DSGraphs into a single graph for
266     // the entire SCC.  We computed the largest graph, so clone all of the other
267     // (smaller) graphs into it.  Discard all of the old graphs.
268     //
269     for (hash_set<DSGraph*>::iterator I = SCCGraphs.begin(),
270            E = SCCGraphs.end(); I != E; ++I) {
271       DSGraph &G = **I;
272       if (&G != SCCGraph) {
273         SCCGraph->cloneInto(G);
274
275         // Update the DSInfo map and delete the old graph...
276         for (DSGraph::retnodes_iterator I = G.retnodes_begin(),
277                E = G.retnodes_end(); I != E; ++I)
278           DSInfo[I->first] = SCCGraph;
279         delete &G;
280       }
281     }
282
283     // Clean up the graph before we start inlining a bunch again...
284     SCCGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
285
286     // Now that we have one big happy family, resolve all of the call sites in
287     // the graph...
288     calculateGraph(*SCCGraph);
289     DEBUG(std::cerr << "  [BU] Done inlining SCC  [" << SCCGraph->getGraphSize()
290                     << "+" << SCCGraph->getAuxFunctionCalls().size() << "]\n");
291
292     std::cerr << "DONE with SCC #: " << MyID << "\n";
293
294     // We never have to revisit "SCC" processed functions...
295     
296     // Drop the stuff we don't need from the end of the stack
297     Stack.erase(FirstInSCC, Stack.end());
298     return MyID;
299   }
300
301   return MyID;  // == Min
302 }
303
304
305 // releaseMemory - If the pass pipeline is done with this pass, we can release
306 // our memory... here...
307 //
308 void BUDataStructures::releaseMyMemory() {
309   for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
310          E = DSInfo.end(); I != E; ++I) {
311     I->second->getReturnNodes().erase(I->first);
312     if (I->second->getReturnNodes().empty())
313       delete I->second;
314   }
315
316   // Empty map so next time memory is released, data structures are not
317   // re-deleted.
318   DSInfo.clear();
319   delete GlobalsGraph;
320   GlobalsGraph = 0;
321 }
322
323 void BUDataStructures::calculateGraph(DSGraph &Graph) {
324   // Move our call site list into TempFCs so that inline call sites go into the
325   // new call site list and doesn't invalidate our iterators!
326   std::list<DSCallSite> TempFCs;
327   std::list<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
328   TempFCs.swap(AuxCallsList);
329
330   DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
331
332   bool Printed = false;
333   std::vector<Function*> CalledFuncs;
334   while (!TempFCs.empty()) {
335     DSCallSite &CS = *TempFCs.begin();
336
337     CalledFuncs.clear();
338
339     // Fast path for noop calls.  Note that we don't care about merging globals
340     // in the callee with nodes in the caller here.
341     if (CS.getRetVal().isNull() && CS.getNumPtrArgs() == 0) {
342       TempFCs.erase(TempFCs.begin());
343       continue;
344     } else if (CS.isDirectCall() && isVAHackFn(CS.getCalleeFunc())) {
345       TempFCs.erase(TempFCs.begin());
346       continue;
347     }
348
349     GetAllCallees(CS, CalledFuncs);
350
351     if (CalledFuncs.empty()) {
352       // Remember that we could not resolve this yet!
353       AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
354       continue;
355     } else {
356       DSGraph *GI;
357       Instruction *TheCall = CS.getCallSite().getInstruction();
358
359       if (CalledFuncs.size() == 1) {
360         Function *Callee = CalledFuncs[0];
361         ActualCallees.insert(std::make_pair(TheCall, Callee));
362
363         // Get the data structure graph for the called function.
364         GI = &getDSGraph(*Callee);  // Graph to inline
365         DEBUG(std::cerr << "    Inlining graph for " << Callee->getName());
366
367         DEBUG(std::cerr << "[" << GI->getGraphSize() << "+"
368               << GI->getAuxFunctionCalls().size() << "] into '"
369               << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
370               << Graph.getAuxFunctionCalls().size() << "]\n");
371         Graph.mergeInGraph(CS, *Callee, *GI,
372                            DSGraph::StripAllocaBit|DSGraph::DontCloneCallNodes);
373         ++NumBUInlines;
374       } else {
375         if (!Printed)
376           std::cerr << "In Fns: " << Graph.getFunctionNames() << "\n";
377         std::cerr << "  calls " << CalledFuncs.size()
378                   << " fns from site: " << CS.getCallSite().getInstruction() 
379                   << "  " << *CS.getCallSite().getInstruction();
380         std::cerr << "   Fns =";
381         unsigned NumPrinted = 0;
382
383         for (std::vector<Function*>::iterator I = CalledFuncs.begin(),
384                E = CalledFuncs.end(); I != E; ++I) {
385           if (NumPrinted++ < 8) std::cerr << " " << (*I)->getName();
386
387           // Add the call edges to the call graph.
388           ActualCallees.insert(std::make_pair(TheCall, *I));
389         }
390         std::cerr << "\n";
391
392         // See if we already computed a graph for this set of callees.
393         std::sort(CalledFuncs.begin(), CalledFuncs.end());
394         std::pair<DSGraph*, std::vector<DSNodeHandle> > &IndCallGraph =
395           (*IndCallGraphMap)[CalledFuncs];
396
397         if (IndCallGraph.first == 0) {
398           std::vector<Function*>::iterator I = CalledFuncs.begin(),
399             E = CalledFuncs.end();
400           
401           // Start with a copy of the first graph.
402           GI = IndCallGraph.first = new DSGraph(getDSGraph(**I), GlobalECs);
403           GI->setGlobalsGraph(Graph.getGlobalsGraph());
404           std::vector<DSNodeHandle> &Args = IndCallGraph.second;
405
406           // Get the argument nodes for the first callee.  The return value is
407           // the 0th index in the vector.
408           GI->getFunctionArgumentsForCall(*I, Args);
409
410           // Merge all of the other callees into this graph.
411           for (++I; I != E; ++I) {
412             // If the graph already contains the nodes for the function, don't
413             // bother merging it in again.
414             if (!GI->containsFunction(*I)) {
415               GI->cloneInto(getDSGraph(**I));
416               ++NumBUInlines;
417             }
418
419             std::vector<DSNodeHandle> NextArgs;
420             GI->getFunctionArgumentsForCall(*I, NextArgs);
421             unsigned i = 0, e = Args.size();
422             for (; i != e; ++i) {
423               if (i == NextArgs.size()) break;
424               Args[i].mergeWith(NextArgs[i]);
425             }
426             for (e = NextArgs.size(); i != e; ++i)
427               Args.push_back(NextArgs[i]);
428           }
429           
430           // Clean up the final graph!
431           GI->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
432         } else {
433           std::cerr << "***\n*** RECYCLED GRAPH ***\n***\n";
434         }
435
436         GI = IndCallGraph.first;
437
438         // Merge the unified graph into this graph now.
439         DEBUG(std::cerr << "    Inlining multi callee graph "
440               << "[" << GI->getGraphSize() << "+"
441               << GI->getAuxFunctionCalls().size() << "] into '"
442               << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
443               << Graph.getAuxFunctionCalls().size() << "]\n");
444
445         Graph.mergeInGraph(CS, IndCallGraph.second, *GI,
446                            DSGraph::StripAllocaBit |
447                            DSGraph::DontCloneCallNodes);
448         ++NumBUInlines;
449       }
450     }
451     TempFCs.erase(TempFCs.begin());
452   }
453
454   // Recompute the Incomplete markers
455   Graph.maskIncompleteMarkers();
456   Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
457
458   // Delete dead nodes.  Treat globals that are unreachable but that can
459   // reach live nodes as live.
460   Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
461
462   // When this graph is finalized, clone the globals in the graph into the
463   // globals graph to make sure it has everything, from all graphs.
464   DSScalarMap &MainSM = Graph.getScalarMap();
465   ReachabilityCloner RC(*GlobalsGraph, Graph, DSGraph::StripAllocaBit);
466
467   // Clone everything reachable from globals in the function graph into the
468   // globals graph.
469   for (DSScalarMap::global_iterator I = MainSM.global_begin(),
470          E = MainSM.global_end(); I != E; ++I) 
471     RC.getClonedNH(MainSM[*I]);
472
473   //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
474 }
475
476 static const Function *getFnForValue(const Value *V) {
477   if (const Instruction *I = dyn_cast<Instruction>(V))
478     return I->getParent()->getParent();
479   else if (const Argument *A = dyn_cast<Argument>(V))
480     return A->getParent();
481   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
482     return BB->getParent();
483   return 0;
484 }
485
486 /// deleteValue/copyValue - Interfaces to update the DSGraphs in the program.
487 /// These correspond to the interfaces defined in the AliasAnalysis class.
488 void BUDataStructures::deleteValue(Value *V) {
489   if (const Function *F = getFnForValue(V)) {  // Function local value?
490     // If this is a function local value, just delete it from the scalar map!
491     getDSGraph(*F).getScalarMap().eraseIfExists(V);
492     return;
493   }
494
495   if (Function *F = dyn_cast<Function>(V)) {
496     assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
497            "cannot handle scc's");
498     delete DSInfo[F];
499     DSInfo.erase(F);
500     return;
501   }
502
503   assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
504 }
505
506 void BUDataStructures::copyValue(Value *From, Value *To) {
507   if (From == To) return;
508   if (const Function *F = getFnForValue(From)) {  // Function local value?
509     // If this is a function local value, just delete it from the scalar map!
510     getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
511     return;
512   }
513
514   if (Function *FromF = dyn_cast<Function>(From)) {
515     Function *ToF = cast<Function>(To);
516     assert(!DSInfo.count(ToF) && "New Function already exists!");
517     DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
518     DSInfo[ToF] = NG;
519     assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
520
521     // Change the Function* is the returnnodes map to the ToF.
522     DSNodeHandle Ret = NG->retnodes_begin()->second;
523     NG->getReturnNodes().clear();
524     NG->getReturnNodes()[ToF] = Ret;
525     return;
526   }
527
528   if (const Function *F = getFnForValue(To)) {
529     DSGraph &G = getDSGraph(*F);
530     G.getScalarMap().copyScalarIfExists(From, To);
531     return;
532   }
533
534   std::cerr << *From;
535   std::cerr << *To;
536   assert(0 && "Do not know how to copy this yet!");
537   abort();
538 }