Replace DEBUG(std::cerr with DOUT. Removed some iostream #includes.
[oota-llvm.git] / lib / Analysis / DataStructure / EquivClassGraphs.cpp
1 //===- EquivClassGraphs.cpp - Merge equiv-class graphs & inline bottom-up -===//
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 pass is the same as the complete bottom-up graphs, but
11 // with functions partitioned into equivalence classes and a single merged
12 // DS graph for all functions in an equivalence class.  After this merging,
13 // graphs are inlined bottom-up on the SCCs of the final (CBU) call graph.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "ECGraphs"
18 #include "llvm/Analysis/DataStructure/DataStructure.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Analysis/DataStructure/DSGraph.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/ADT/SCCIterator.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/EquivalenceClasses.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include <iostream>
30 using namespace llvm;
31
32 namespace {
33   RegisterPass<EquivClassGraphs> X("eqdatastructure",
34                     "Equivalence-class Bottom-up Data Structure Analysis");
35   Statistic<> NumEquivBUInlines("equivdatastructures",
36                                 "Number of graphs inlined");
37   Statistic<> NumFoldGraphInlines("Inline equiv-class graphs bottom up",
38                                   "Number of graphs inlined");
39 }
40
41 #ifndef NDEBUG
42 template<typename GT>
43 static void CheckAllGraphs(Module *M, GT &ECGraphs) {
44   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
45     if (!I->isExternal()) {
46       DSGraph &G = ECGraphs.getDSGraph(*I);
47       if (G.retnodes_begin()->first != I)
48         continue;  // Only check a graph once.
49
50       DSGraph::NodeMapTy GlobalsGraphNodeMapping;
51       G.computeGToGGMapping(GlobalsGraphNodeMapping);
52     }
53 }
54 #endif
55
56 // getSomeCalleeForCallSite - Return any one callee function at a call site.
57 //
58 Function *EquivClassGraphs::getSomeCalleeForCallSite(const CallSite &CS) const{
59   Function *thisFunc = CS.getCaller();
60   assert(thisFunc && "getSomeCalleeForCallSite(): Not a valid call site?");
61   DSGraph &DSG = getDSGraph(*thisFunc);
62   DSNode *calleeNode = DSG.getNodeForValue(CS.getCalledValue()).getNode();
63   std::map<DSNode*, Function *>::const_iterator I =
64     OneCalledFunction.find(calleeNode);
65   return (I == OneCalledFunction.end())? NULL : I->second;
66 }
67
68 // runOnModule - Calculate the bottom up data structure graphs for each function
69 // in the program.
70 //
71 bool EquivClassGraphs::runOnModule(Module &M) {
72   CBU = &getAnalysis<CompleteBUDataStructures>();
73   GlobalECs = CBU->getGlobalECs();
74   DEBUG(CheckAllGraphs(&M, *CBU));
75
76   GlobalsGraph = new DSGraph(CBU->getGlobalsGraph(), GlobalECs);
77   GlobalsGraph->setPrintAuxCalls();
78
79   ActualCallees = CBU->getActualCallees();
80
81   // Find equivalence classes of functions called from common call sites.
82   // Fold the CBU graphs for all functions in an equivalence class.
83   buildIndirectFunctionSets(M);
84
85   // Stack of functions used for Tarjan's SCC-finding algorithm.
86   std::vector<DSGraph*> Stack;
87   std::map<DSGraph*, unsigned> ValMap;
88   unsigned NextID = 1;
89
90   Function *MainFunc = M.getMainFunction();
91   if (MainFunc && !MainFunc->isExternal()) {
92     processSCC(getOrCreateGraph(*MainFunc), Stack, NextID, ValMap);
93   } else {
94     std::cerr << "Fold Graphs: No 'main' function found!\n";
95   }
96
97   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
98     if (!I->isExternal())
99       processSCC(getOrCreateGraph(*I), Stack, NextID, ValMap);
100
101   DEBUG(CheckAllGraphs(&M, *this));
102
103   getGlobalsGraph().removeTriviallyDeadNodes();
104   getGlobalsGraph().markIncompleteNodes(DSGraph::IgnoreGlobals);
105
106   // Merge the globals variables (not the calls) from the globals graph back
107   // into the main function's graph so that the main function contains all of
108   // the information about global pools and GV usage in the program.
109   if (MainFunc && !MainFunc->isExternal()) {
110     DSGraph &MainGraph = getOrCreateGraph(*MainFunc);
111     const DSGraph &GG = *MainGraph.getGlobalsGraph();
112     ReachabilityCloner RC(MainGraph, GG,
113                           DSGraph::DontCloneCallNodes |
114                           DSGraph::DontCloneAuxCallNodes);
115
116     // Clone the global nodes into this graph.
117     for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
118            E = GG.getScalarMap().global_end(); I != E; ++I)
119       if (isa<GlobalVariable>(*I))
120         RC.getClonedNH(GG.getNodeForValue(*I));
121
122     MainGraph.maskIncompleteMarkers();
123     MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
124                                   DSGraph::IgnoreGlobals);
125   }
126
127   // Final processing.  Note that dead node elimination may actually remove
128   // globals from a function graph that are immediately used.  If there are no
129   // scalars pointing to the node (e.g. because the only use is a direct store
130   // to a scalar global) we have to make sure to rematerialize the globals back
131   // into the graphs here, or clients will break!
132   for (Module::global_iterator GI = M.global_begin(), E = M.global_end();
133        GI != E; ++GI)
134     // This only happens to first class typed globals.
135     if (GI->getType()->getElementType()->isFirstClassType())
136       for (Value::use_iterator UI = GI->use_begin(), E = GI->use_end();
137            UI != E; ++UI)
138         // This only happens to direct uses by instructions.
139         if (Instruction *User = dyn_cast<Instruction>(*UI)) {
140           DSGraph &DSG = getOrCreateGraph(*User->getParent()->getParent());
141           if (!DSG.getScalarMap().count(GI)) {
142             // If this global does not exist in the graph, but it is immediately
143             // used by an instruction in the graph, clone it over from the
144             // globals graph.
145             ReachabilityCloner RC(DSG, *GlobalsGraph, 0);
146             RC.getClonedNH(GlobalsGraph->getNodeForValue(GI));
147           }
148         }
149
150   return false;
151 }
152
153
154 // buildIndirectFunctionSets - Iterate over the module looking for indirect
155 // calls to functions.  If a call site can invoke any functions [F1, F2... FN],
156 // unify the N functions together in the FuncECs set.
157 //
158 void EquivClassGraphs::buildIndirectFunctionSets(Module &M) {
159   const ActualCalleesTy& AC = CBU->getActualCallees();
160
161   // Loop over all of the indirect calls in the program.  If a call site can
162   // call multiple different functions, we need to unify all of the callees into
163   // the same equivalence class.
164   Instruction *LastInst = 0;
165   Function *FirstFunc = 0;
166   for (ActualCalleesTy::const_iterator I=AC.begin(), E=AC.end(); I != E; ++I) {
167     if (I->second->isExternal())
168       continue;                         // Ignore functions we cannot modify
169
170     CallSite CS = CallSite::get(I->first);
171
172     if (CS.getCalledFunction()) {       // Direct call:
173       FuncECs.insert(I->second);        // -- Make sure function has equiv class
174       FirstFunc = I->second;            // -- First callee at this site
175     } else {                            // Else indirect call
176       // DEBUG(std::cerr << "CALLEE: " << I->second->getName()
177       //       << " from : " << I->first);
178       if (I->first != LastInst) {
179         // This is the first callee from this call site.
180         LastInst = I->first;
181         FirstFunc = I->second;
182         // Instead of storing the lastInst For Indirection call Sites we store
183         // the DSNode for the function ptr arguemnt
184         Function *thisFunc = LastInst->getParent()->getParent();
185         DSGraph &TFG = CBU->getDSGraph(*thisFunc);
186         DSNode *calleeNode = TFG.getNodeForValue(CS.getCalledValue()).getNode();
187         OneCalledFunction[calleeNode] = FirstFunc;
188         FuncECs.insert(I->second);
189       } else {
190         // This is not the first possible callee from a particular call site.
191         // Union the callee in with the other functions.
192         FuncECs.unionSets(FirstFunc, I->second);
193 #ifndef NDEBUG
194         Function *thisFunc = LastInst->getParent()->getParent();
195         DSGraph &TFG = CBU->getDSGraph(*thisFunc);
196         DSNode *calleeNode = TFG.getNodeForValue(CS.getCalledValue()).getNode();
197         assert(OneCalledFunction.count(calleeNode) > 0 && "Missed a call?");
198 #endif
199       }
200     }
201
202     // Now include all functions that share a graph with any function in the
203     // equivalence class.  More precisely, if F is in the class, and G(F) is
204     // its graph, then we include all other functions that are also in G(F).
205     // Currently, that is just the functions in the same call-graph-SCC as F.
206     //
207     DSGraph& funcDSGraph = CBU->getDSGraph(*I->second);
208     for (DSGraph::retnodes_iterator RI = funcDSGraph.retnodes_begin(),
209            RE = funcDSGraph.retnodes_end(); RI != RE; ++RI)
210       FuncECs.unionSets(FirstFunc, RI->first);
211   }
212
213   // Now that all of the equivalences have been built, merge the graphs for
214   // each equivalence class.
215   //
216   DOUT << "\nIndirect Function Equivalence Sets:\n";
217   for (EquivalenceClasses<Function*>::iterator EQSI = FuncECs.begin(), E =
218          FuncECs.end(); EQSI != E; ++EQSI) {
219     if (!EQSI->isLeader()) continue;
220
221     EquivalenceClasses<Function*>::member_iterator SI =
222       FuncECs.member_begin(EQSI);
223     assert(SI != FuncECs.member_end() && "Empty equiv set??");
224     EquivalenceClasses<Function*>::member_iterator SN = SI;
225     ++SN;
226     if (SN == FuncECs.member_end())
227       continue;   // Single function equivalence set, no merging to do.
228
229     Function* LF = *SI;
230
231 #ifndef NDEBUG
232     DOUT <<"  Equivalence set for leader " << LF->getName() <<" = ";
233     for (SN = SI; SN != FuncECs.member_end(); ++SN)
234       DOUT << " " << (*SN)->getName() << "," ;
235     DOUT << "\n";
236 #endif
237
238     // This equiv class has multiple functions: merge their graphs.  First,
239     // clone the CBU graph for the leader and make it the common graph for the
240     // equivalence graph.
241     DSGraph &MergedG = getOrCreateGraph(*LF);
242
243     // Record the argument nodes for use in merging later below.
244     std::vector<DSNodeHandle> ArgNodes;
245
246     for (Function::arg_iterator AI = LF->arg_begin(), E = LF->arg_end();
247          AI != E; ++AI)
248       if (DS::isPointerType(AI->getType()))
249         ArgNodes.push_back(MergedG.getNodeForValue(AI));
250
251     // Merge in the graphs of all other functions in this equiv. class.  Note
252     // that two or more functions may have the same graph, and it only needs
253     // to be merged in once.
254     std::set<DSGraph*> GraphsMerged;
255     GraphsMerged.insert(&CBU->getDSGraph(*LF));
256
257     for (++SI; SI != FuncECs.member_end(); ++SI) {
258       Function *F = *SI;
259       DSGraph &CBUGraph = CBU->getDSGraph(*F);
260       if (GraphsMerged.insert(&CBUGraph).second) {
261         // Record the "folded" graph for the function.
262         for (DSGraph::retnodes_iterator I = CBUGraph.retnodes_begin(),
263                E = CBUGraph.retnodes_end(); I != E; ++I) {
264           assert(DSInfo[I->first] == 0 && "Graph already exists for Fn!");
265           DSInfo[I->first] = &MergedG;
266         }
267
268         // Clone this member of the equivalence class into MergedG.
269         MergedG.cloneInto(CBUGraph);
270       }
271
272       // Merge the return nodes of all functions together.
273       MergedG.getReturnNodes()[LF].mergeWith(MergedG.getReturnNodes()[F]);
274
275       // Merge the function arguments with all argument nodes found so far.
276       // If there are extra function args, add them to the vector of argNodes
277       Function::arg_iterator AI2 = F->arg_begin(), AI2end = F->arg_end();
278       for (unsigned arg = 0, numArgs = ArgNodes.size();
279            arg != numArgs && AI2 != AI2end; ++AI2, ++arg)
280         if (DS::isPointerType(AI2->getType()))
281           ArgNodes[arg].mergeWith(MergedG.getNodeForValue(AI2));
282
283       for ( ; AI2 != AI2end; ++AI2)
284         if (DS::isPointerType(AI2->getType()))
285           ArgNodes.push_back(MergedG.getNodeForValue(AI2));
286       DEBUG(MergedG.AssertGraphOK());
287     }
288   }
289   DOUT << "\n";
290 }
291
292
293 DSGraph &EquivClassGraphs::getOrCreateGraph(Function &F) {
294   // Has the graph already been created?
295   DSGraph *&Graph = DSInfo[&F];
296   if (Graph) return *Graph;
297
298   DSGraph &CBUGraph = CBU->getDSGraph(F);
299
300   // Copy the CBU graph...
301   Graph = new DSGraph(CBUGraph, GlobalECs);   // updates the map via reference
302   Graph->setGlobalsGraph(&getGlobalsGraph());
303   Graph->setPrintAuxCalls();
304
305   // Make sure to update the DSInfo map for all functions in the graph!
306   for (DSGraph::retnodes_iterator I = Graph->retnodes_begin();
307        I != Graph->retnodes_end(); ++I)
308     if (I->first != &F) {
309       DSGraph *&FG = DSInfo[I->first];
310       assert(FG == 0 && "Merging function in SCC twice?");
311       FG = Graph;
312     }
313
314   return *Graph;
315 }
316
317
318 unsigned EquivClassGraphs::
319 processSCC(DSGraph &FG, std::vector<DSGraph*> &Stack, unsigned &NextID,
320            std::map<DSGraph*, unsigned> &ValMap) {
321   std::map<DSGraph*, unsigned>::iterator It = ValMap.lower_bound(&FG);
322   if (It != ValMap.end() && It->first == &FG)
323     return It->second;
324
325   DOUT << "    ProcessSCC for function " << FG.getFunctionNames() << "\n";
326
327   unsigned Min = NextID++, MyID = Min;
328   ValMap[&FG] = Min;
329   Stack.push_back(&FG);
330
331   // The edges out of the current node are the call site targets...
332   for (DSGraph::fc_iterator CI = FG.fc_begin(), CE = FG.fc_end();
333        CI != CE; ++CI) {
334     Instruction *Call = CI->getCallSite().getInstruction();
335
336     // Loop over all of the actually called functions...
337     for (callee_iterator I = callee_begin(Call), E = callee_end(Call);
338          I != E; ++I)
339       if (!I->second->isExternal()) {
340         // Process the callee as necessary.
341         unsigned M = processSCC(getOrCreateGraph(*I->second),
342                                 Stack, NextID, ValMap);
343         if (M < Min) Min = M;
344       }
345   }
346
347   assert(ValMap[&FG] == MyID && "SCC construction assumption wrong!");
348   if (Min != MyID)
349     return Min;         // This is part of a larger SCC!
350
351   // If this is a new SCC, process it now.
352   bool MergedGraphs = false;
353   while (Stack.back() != &FG) {
354     DSGraph *NG = Stack.back();
355     ValMap[NG] = ~0U;
356
357     // If the SCC found is not the same as those found in CBU, make sure to
358     // merge the graphs as appropriate.
359     FG.cloneInto(*NG);
360
361     // Update the DSInfo map and delete the old graph...
362     for (DSGraph::retnodes_iterator I = NG->retnodes_begin();
363          I != NG->retnodes_end(); ++I)
364       DSInfo[I->first] = &FG;
365
366     // Remove NG from the ValMap since the pointer may get recycled.
367     ValMap.erase(NG);
368     delete NG;
369     MergedGraphs = true;
370     Stack.pop_back();
371   }
372
373   // Clean up the graph before we start inlining a bunch again.
374   if (MergedGraphs)
375     FG.removeTriviallyDeadNodes();
376
377   Stack.pop_back();
378
379   processGraph(FG);
380   ValMap[&FG] = ~0U;
381   return MyID;
382 }
383
384
385 /// processGraph - Process the CBU graphs for the program in bottom-up order on
386 /// the SCC of the __ACTUAL__ call graph.  This builds final folded CBU graphs.
387 void EquivClassGraphs::processGraph(DSGraph &G) {
388   DOUT << "    ProcessGraph for function " << G.getFunctionNames() << "\n";
389
390   hash_set<Instruction*> calls;
391
392   // Else we need to inline some callee graph.  Visit all call sites.
393   // The edges out of the current node are the call site targets...
394   unsigned i = 0;
395   for (DSGraph::fc_iterator CI = G.fc_begin(), CE = G.fc_end(); CI != CE;
396        ++CI, ++i) {
397     const DSCallSite &CS = *CI;
398     Instruction *TheCall = CS.getCallSite().getInstruction();
399
400     assert(calls.insert(TheCall).second &&
401            "Call instruction occurs multiple times in graph??");
402
403     if (CS.getRetVal().isNull() && CS.getNumPtrArgs() == 0)
404       continue;
405
406     // Inline the common callee graph into the current graph, if the callee
407     // graph has not changed.  Note that all callees should have the same
408     // graph so we only need to do this once.
409     //
410     DSGraph* CalleeGraph = NULL;
411     callee_iterator I = callee_begin(TheCall), E = callee_end(TheCall);
412     unsigned TNum, Num;
413
414     // Loop over all potential callees to find the first non-external callee.
415     for (TNum = 0, Num = std::distance(I, E); I != E; ++I, ++TNum)
416       if (!I->second->isExternal())
417         break;
418
419     // Now check if the graph has changed and if so, clone and inline it.
420     if (I != E) {
421       Function *CalleeFunc = I->second;
422
423       // Merge the callee's graph into this graph, if not already the same.
424       // Callees in the same equivalence class (which subsumes those
425       // in the same SCCs) have the same graph.  Note that all recursion
426       // including self-recursion have been folded in the equiv classes.
427       //
428       CalleeGraph = &getOrCreateGraph(*CalleeFunc);
429       if (CalleeGraph != &G) {
430         ++NumFoldGraphInlines;
431         G.mergeInGraph(CS, *CalleeFunc, *CalleeGraph,
432                        DSGraph::StripAllocaBit |
433                        DSGraph::DontCloneCallNodes |
434                        DSGraph::DontCloneAuxCallNodes);
435         DOUT << "    Inlining graph [" << i << "/"
436              << G.getFunctionCalls().size()-1
437              << ":" << TNum << "/" << Num-1 << "] for "
438              << CalleeFunc->getName() << "["
439              << CalleeGraph->getGraphSize() << "+"
440              << CalleeGraph->getAuxFunctionCalls().size()
441              << "] into '" /*<< G.getFunctionNames()*/ << "' ["
442              << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
443              << "]\n";
444       }
445     }
446
447 #ifndef NDEBUG
448     // Now loop over the rest of the callees and make sure they have the
449     // same graph as the one inlined above.
450     if (CalleeGraph)
451       for (++I, ++TNum; I != E; ++I, ++TNum)
452         if (!I->second->isExternal())
453           assert(CalleeGraph == &getOrCreateGraph(*I->second) &&
454                  "Callees at a call site have different graphs?");
455 #endif
456   }
457
458   // Recompute the Incomplete markers.
459   G.maskIncompleteMarkers();
460   G.markIncompleteNodes(DSGraph::MarkFormalArgs);
461
462   // Delete dead nodes.  Treat globals that are unreachable but that can
463   // reach live nodes as live.
464   G.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
465
466   // When this graph is finalized, clone the globals in the graph into the
467   // globals graph to make sure it has everything, from all graphs.
468   ReachabilityCloner RC(*G.getGlobalsGraph(), G, DSGraph::StripAllocaBit);
469
470   // Clone everything reachable from globals in the function graph into the
471   // globals graph.
472   DSScalarMap &MainSM = G.getScalarMap();
473   for (DSScalarMap::global_iterator I = MainSM.global_begin(),
474          E = MainSM.global_end(); I != E; ++I)
475     RC.getClonedNH(MainSM[*I]);
476
477   DOUT << "  -- DONE ProcessGraph for function " << G.getFunctionNames() <<"\n";
478 }