57a8924ae4775605e2e2ffa737f344a8ec584647
[oota-llvm.git] / lib / Analysis / DataStructure / TopDownClosure.cpp
1 //===- TopDownClosure.cpp - Compute the top-down interprocedure 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 TDDataStructures class, which represents the
11 // Top-down Interprocedural closure of the data structure graph over the
12 // program.  This is useful (but not strictly necessary?) for applications
13 // like pointer analysis.
14 //
15 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "td_dsa"
17 #include "llvm/Analysis/DataStructure/DataStructure.h"
18 #include "llvm/Module.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Analysis/DataStructure/DSGraph.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Timer.h"
23 #include "llvm/ADT/Statistic.h"
24 using namespace llvm;
25
26 #if 0
27 #define TIME_REGION(VARNAME, DESC) \
28    NamedRegionTimer VARNAME(DESC)
29 #else
30 #define TIME_REGION(VARNAME, DESC)
31 #endif
32
33 namespace {
34   RegisterPass<TDDataStructures>   // Register the pass
35   Y("tddatastructure", "Top-down Data Structure Analysis");
36
37   Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
38 }
39
40 void TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,
41                                                    hash_set<DSNode*> &Visited) {
42   if (!N || Visited.count(N)) return;
43   Visited.insert(N);
44
45   for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i) {
46     DSNodeHandle &NH = N->getLink(i*N->getPointerSize());
47     if (DSNode *NN = NH.getNode()) {
48       std::vector<Function*> Functions;
49       NN->addFullFunctionList(Functions);
50       ArgsRemainIncomplete.insert(Functions.begin(), Functions.end());
51       markReachableFunctionsExternallyAccessible(NN, Visited);
52     }
53   }
54 }
55
56
57 // run - Calculate the top down data structure graphs for each function in the
58 // program.
59 //
60 bool TDDataStructures::runOnModule(Module &M) {
61   BUInfo = &getAnalysis<BUDataStructures>();
62   GlobalECs = BUInfo->getGlobalECs();
63   GlobalsGraph = new DSGraph(BUInfo->getGlobalsGraph(), GlobalECs);
64   GlobalsGraph->setPrintAuxCalls();
65
66   // Figure out which functions must not mark their arguments complete because
67   // they are accessible outside this compilation unit.  Currently, these
68   // arguments are functions which are reachable by global variables in the
69   // globals graph.
70   const DSScalarMap &GGSM = GlobalsGraph->getScalarMap();
71   hash_set<DSNode*> Visited;
72   for (DSScalarMap::global_iterator I=GGSM.global_begin(), E=GGSM.global_end();
73        I != E; ++I) {
74     DSNode *N = GGSM.find(*I)->second.getNode();
75     if (N->isIncomplete())
76       markReachableFunctionsExternallyAccessible(N, Visited);
77   }
78
79   // Loop over unresolved call nodes.  Any functions passed into (but not
80   // returned!) from unresolvable call nodes may be invoked outside of the
81   // current module.
82   for (DSGraph::afc_iterator I = GlobalsGraph->afc_begin(),
83          E = GlobalsGraph->afc_end(); I != E; ++I)
84     for (unsigned arg = 0, e = I->getNumPtrArgs(); arg != e; ++arg)
85       markReachableFunctionsExternallyAccessible(I->getPtrArg(arg).getNode(),
86                                                  Visited);
87   Visited.clear();
88
89   // Functions without internal linkage also have unknown incoming arguments!
90   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
91     if (!I->isExternal() && !I->hasInternalLinkage())
92       ArgsRemainIncomplete.insert(I);
93
94   // We want to traverse the call graph in reverse post-order.  To do this, we
95   // calculate a post-order traversal, then reverse it.
96   hash_set<DSGraph*> VisitedGraph;
97   std::vector<DSGraph*> PostOrder;
98
99 #if 0
100 {TIME_REGION(XXX, "td:Copy graphs");
101
102   // Visit each of the graphs in reverse post-order now!
103   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
104     if (!I->isExternal())
105       getOrCreateDSGraph(*I);
106   return false;
107 }
108 #endif
109
110
111 {TIME_REGION(XXX, "td:Compute postorder");
112
113   // Calculate top-down from main...
114   if (Function *F = M.getMainFunction())
115     ComputePostOrder(*F, VisitedGraph, PostOrder);
116
117   // Next calculate the graphs for each unreachable function...
118   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
119     ComputePostOrder(*I, VisitedGraph, PostOrder);
120
121   VisitedGraph.clear();   // Release memory!
122 }
123
124 {TIME_REGION(XXX, "td:Inline stuff");
125
126   // Visit each of the graphs in reverse post-order now!
127   while (!PostOrder.empty()) {
128     InlineCallersIntoGraph(*PostOrder.back());
129     PostOrder.pop_back();
130   }
131 }
132
133   // Free the IndCallMap.
134   while (!IndCallMap.empty()) {
135     delete IndCallMap.begin()->second;
136     IndCallMap.erase(IndCallMap.begin());
137   }
138
139
140   ArgsRemainIncomplete.clear();
141   GlobalsGraph->removeTriviallyDeadNodes();
142
143   return false;
144 }
145
146
147 DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {
148   DSGraph *&G = DSInfo[&F];
149   if (G == 0) { // Not created yet?  Clone BU graph...
150     G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F), GlobalECs,
151                     DSGraph::DontCloneAuxCallNodes);
152     assert(G->getAuxFunctionCalls().empty() && "Cloned aux calls?");
153     G->setPrintAuxCalls();
154     G->setGlobalsGraph(GlobalsGraph);
155
156     // Note that this graph is the graph for ALL of the function in the SCC, not
157     // just F.
158     for (DSGraph::retnodes_iterator RI = G->retnodes_begin(),
159            E = G->retnodes_end(); RI != E; ++RI)
160       if (RI->first != &F)
161         DSInfo[RI->first] = G;
162   }
163   return *G;
164 }
165
166
167 void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,
168                                         std::vector<DSGraph*> &PostOrder) {
169   if (F.isExternal()) return;
170   DSGraph &G = getOrCreateDSGraph(F);
171   if (Visited.count(&G)) return;
172   Visited.insert(&G);
173
174   // Recursively traverse all of the callee graphs.
175   for (DSGraph::fc_iterator CI = G.fc_begin(), CE = G.fc_end(); CI != CE; ++CI){
176     Instruction *CallI = CI->getCallSite().getInstruction();
177     for (BUDataStructures::callee_iterator I = BUInfo->callee_begin(CallI),
178            E = BUInfo->callee_end(CallI); I != E; ++I)
179       ComputePostOrder(*I->second, Visited, PostOrder);
180   }
181
182   PostOrder.push_back(&G);
183 }
184
185
186
187
188
189 // releaseMemory - If the pass pipeline is done with this pass, we can release
190 // our memory... here...
191 //
192 // FIXME: This should be releaseMemory and will work fine, except that LoadVN
193 // has no way to extend the lifetime of the pass, which screws up ds-aa.
194 //
195 void TDDataStructures::releaseMyMemory() {
196   for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
197          E = DSInfo.end(); I != E; ++I) {
198     I->second->getReturnNodes().erase(I->first);
199     if (I->second->getReturnNodes().empty())
200       delete I->second;
201   }
202
203   // Empty map so next time memory is released, data structures are not
204   // re-deleted.
205   DSInfo.clear();
206   delete GlobalsGraph;
207   GlobalsGraph = 0;
208 }
209
210 /// InlineCallersIntoGraph - Inline all of the callers of the specified DS graph
211 /// into it, then recompute completeness of nodes in the resultant graph.
212 void TDDataStructures::InlineCallersIntoGraph(DSGraph &DSG) {
213   // Inline caller graphs into this graph.  First step, get the list of call
214   // sites that call into this graph.
215   std::vector<CallerCallEdge> EdgesFromCaller;
216   std::map<DSGraph*, std::vector<CallerCallEdge> >::iterator
217     CEI = CallerEdges.find(&DSG);
218   if (CEI != CallerEdges.end()) {
219     std::swap(CEI->second, EdgesFromCaller);
220     CallerEdges.erase(CEI);
221   }
222
223   // Sort the caller sites to provide a by-caller-graph ordering.
224   std::sort(EdgesFromCaller.begin(), EdgesFromCaller.end());
225
226
227   // Merge information from the globals graph into this graph.  FIXME: This is
228   // stupid.  Instead of us cloning information from the GG into this graph,
229   // then having RemoveDeadNodes clone it back, we should do all of this as a
230   // post-pass over all of the graphs.  We need to take cloning out of
231   // removeDeadNodes and gut removeDeadNodes at the same time first though. :(
232   {
233     DSGraph &GG = *DSG.getGlobalsGraph();
234     ReachabilityCloner RC(DSG, GG,
235                           DSGraph::DontCloneCallNodes |
236                           DSGraph::DontCloneAuxCallNodes);
237     for (DSScalarMap::global_iterator
238            GI = DSG.getScalarMap().global_begin(),
239            E = DSG.getScalarMap().global_end(); GI != E; ++GI)
240       RC.getClonedNH(GG.getNodeForValue(*GI));
241   }
242
243   DOUT << "[TD] Inlining callers into '" << DSG.getFunctionNames() << "'\n";
244
245   // Iteratively inline caller graphs into this graph.
246   while (!EdgesFromCaller.empty()) {
247     DSGraph &CallerGraph = *EdgesFromCaller.back().CallerGraph;
248
249     // Iterate through all of the call sites of this graph, cloning and merging
250     // any nodes required by the call.
251     ReachabilityCloner RC(DSG, CallerGraph,
252                           DSGraph::DontCloneCallNodes |
253                           DSGraph::DontCloneAuxCallNodes);
254
255     // Inline all call sites from this caller graph.
256     do {
257       const DSCallSite &CS = *EdgesFromCaller.back().CS;
258       Function &CF = *EdgesFromCaller.back().CalledFunction;
259       DOUT << "   [TD] Inlining graph into Fn '" << CF.getName() << "' from ";
260       if (CallerGraph.getReturnNodes().empty())
261         DOUT << "SYNTHESIZED INDIRECT GRAPH";
262       else
263         DOUT << "Fn '" << CS.getCallSite().getInstruction()->
264                             getParent()->getParent()->getName() << "'";
265       DOUT << ": " << CF.getFunctionType()->getNumParams() << " args\n";
266
267       // Get the formal argument and return nodes for the called function and
268       // merge them with the cloned subgraph.
269       DSCallSite T1 = DSG.getCallSiteForArguments(CF);
270       RC.mergeCallSite(T1, CS);
271       ++NumTDInlines;
272
273       EdgesFromCaller.pop_back();
274     } while (!EdgesFromCaller.empty() &&
275              EdgesFromCaller.back().CallerGraph == &CallerGraph);
276   }
277
278
279   // Next, now that this graph is finalized, we need to recompute the
280   // incompleteness markers for this graph and remove unreachable nodes.
281   DSG.maskIncompleteMarkers();
282
283   // If any of the functions has incomplete incoming arguments, don't mark any
284   // of them as complete.
285   bool HasIncompleteArgs = false;
286   for (DSGraph::retnodes_iterator I = DSG.retnodes_begin(),
287          E = DSG.retnodes_end(); I != E; ++I)
288     if (ArgsRemainIncomplete.count(I->first)) {
289       HasIncompleteArgs = true;
290       break;
291     }
292
293   // Recompute the Incomplete markers.  Depends on whether args are complete
294   unsigned Flags
295     = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
296   DSG.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
297
298   // Delete dead nodes.  Treat globals that are unreachable as dead also.
299   DSG.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
300
301   // We are done with computing the current TD Graph!  Finally, before we can
302   // finish processing this function, we figure out which functions it calls and
303   // records these call graph edges, so that we have them when we process the
304   // callee graphs.
305   if (DSG.fc_begin() == DSG.fc_end()) return;
306
307   // Loop over all the call sites and all the callees at each call site, and add
308   // edges to the CallerEdges structure for each callee.
309   for (DSGraph::fc_iterator CI = DSG.fc_begin(), E = DSG.fc_end();
310        CI != E; ++CI) {
311
312     // Handle direct calls efficiently.
313     if (CI->isDirectCall()) {
314       if (!CI->getCalleeFunc()->isExternal() &&
315           !DSG.getReturnNodes().count(CI->getCalleeFunc()))
316         CallerEdges[&getDSGraph(*CI->getCalleeFunc())]
317           .push_back(CallerCallEdge(&DSG, &*CI, CI->getCalleeFunc()));
318       continue;
319     }
320
321     Instruction *CallI = CI->getCallSite().getInstruction();
322     // For each function in the invoked function list at this call site...
323     BUDataStructures::callee_iterator IPI =
324       BUInfo->callee_begin(CallI), IPE = BUInfo->callee_end(CallI);
325
326     // Skip over all calls to this graph (SCC calls).
327     while (IPI != IPE && &getDSGraph(*IPI->second) == &DSG)
328       ++IPI;
329
330     // All SCC calls?
331     if (IPI == IPE) continue;
332
333     Function *FirstCallee = IPI->second;
334     ++IPI;
335
336     // Skip over more SCC calls.
337     while (IPI != IPE && &getDSGraph(*IPI->second) == &DSG)
338       ++IPI;
339
340     // If there is exactly one callee from this call site, remember the edge in
341     // CallerEdges.
342     if (IPI == IPE) {
343       if (!FirstCallee->isExternal())
344         CallerEdges[&getDSGraph(*FirstCallee)]
345           .push_back(CallerCallEdge(&DSG, &*CI, FirstCallee));
346       continue;
347     }
348
349     // Otherwise, there are multiple callees from this call site, so it must be
350     // an indirect call.  Chances are that there will be other call sites with
351     // this set of targets.  If so, we don't want to do M*N inlining operations,
352     // so we build up a new, private, graph that represents the calls of all
353     // calls to this set of functions.
354     std::vector<Function*> Callees;
355     for (BUDataStructures::ActualCalleesTy::const_iterator I =
356            BUInfo->callee_begin(CallI), E = BUInfo->callee_end(CallI);
357          I != E; ++I)
358       if (!I->second->isExternal())
359         Callees.push_back(I->second);
360     std::sort(Callees.begin(), Callees.end());
361
362     std::map<std::vector<Function*>, DSGraph*>::iterator IndCallRecI =
363       IndCallMap.lower_bound(Callees);
364
365     DSGraph *IndCallGraph;
366
367     // If we already have this graph, recycle it.
368     if (IndCallRecI != IndCallMap.end() && IndCallRecI->first == Callees) {
369       DOUT << "  [TD] *** Reuse of indcall graph for " << Callees.size()
370            << " callees!\n";
371       IndCallGraph = IndCallRecI->second;
372     } else {
373       // Otherwise, create a new DSGraph to represent this.
374       IndCallGraph = new DSGraph(DSG.getGlobalECs(), DSG.getTargetData());
375
376       // Make a nullary dummy call site, which will eventually get some content
377       // merged into it.  The actual callee function doesn't matter here, so we
378       // just pass it something to keep the ctor happy.
379       std::vector<DSNodeHandle> ArgDummyVec;
380       DSCallSite DummyCS(CI->getCallSite(), DSNodeHandle(), Callees[0]/*dummy*/,
381                          ArgDummyVec);
382       IndCallGraph->getFunctionCalls().push_back(DummyCS);
383
384       IndCallRecI = IndCallMap.insert(IndCallRecI,
385                                       std::make_pair(Callees, IndCallGraph));
386
387       // Additionally, make sure that each of the callees inlines this graph
388       // exactly once.
389       DSCallSite *NCS = &IndCallGraph->getFunctionCalls().front();
390       for (unsigned i = 0, e = Callees.size(); i != e; ++i) {
391         DSGraph& CalleeGraph = getDSGraph(*Callees[i]);
392         if (&CalleeGraph != &DSG)
393           CallerEdges[&CalleeGraph].push_back(CallerCallEdge(IndCallGraph, NCS,
394                                                              Callees[i]));
395       }
396     }
397
398     // Now that we know which graph to use for this, merge the caller
399     // information into the graph, based on information from the call site.
400     ReachabilityCloner RC(*IndCallGraph, DSG, 0);
401     RC.mergeCallSite(IndCallGraph->getFunctionCalls().front(), *CI);
402   }
403 }
404
405
406 static const Function *getFnForValue(const Value *V) {
407   if (const Instruction *I = dyn_cast<Instruction>(V))
408     return I->getParent()->getParent();
409   else if (const Argument *A = dyn_cast<Argument>(V))
410     return A->getParent();
411   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
412     return BB->getParent();
413   return 0;
414 }
415
416 void TDDataStructures::deleteValue(Value *V) {
417   if (const Function *F = getFnForValue(V)) {  // Function local value?
418     // If this is a function local value, just delete it from the scalar map!
419     getDSGraph(*F).getScalarMap().eraseIfExists(V);
420     return;
421   }
422
423   if (Function *F = dyn_cast<Function>(V)) {
424     assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
425            "cannot handle scc's");
426     delete DSInfo[F];
427     DSInfo.erase(F);
428     return;
429   }
430
431   assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
432 }
433
434 void TDDataStructures::copyValue(Value *From, Value *To) {
435   if (From == To) return;
436   if (const Function *F = getFnForValue(From)) {  // Function local value?
437     // If this is a function local value, just delete it from the scalar map!
438     getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
439     return;
440   }
441
442   if (Function *FromF = dyn_cast<Function>(From)) {
443     Function *ToF = cast<Function>(To);
444     assert(!DSInfo.count(ToF) && "New Function already exists!");
445     DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
446     DSInfo[ToF] = NG;
447     assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
448
449     // Change the Function* is the returnnodes map to the ToF.
450     DSNodeHandle Ret = NG->retnodes_begin()->second;
451     NG->getReturnNodes().clear();
452     NG->getReturnNodes()[ToF] = Ret;
453     return;
454   }
455
456   if (const Function *F = getFnForValue(To)) {
457     DSGraph &G = getDSGraph(*F);
458     G.getScalarMap().copyScalarIfExists(From, To);
459     return;
460   }
461
462   DOUT << *From;
463   DOUT << *To;
464   assert(0 && "Do not know how to copy this yet!");
465   abort();
466 }