remove ...
[oota-llvm.git] / lib / Analysis / DataStructure / Printer.cpp
1 //===- Printer.cpp - Code for printing data structure graphs nicely -------===//
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 'dot' graph printer.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/DataStructure/DataStructure.h"
15 #include "llvm/Analysis/DataStructure/EquivClassGraphs.h"
16 #include "llvm/Analysis/DataStructure/DSGraph.h"
17 #include "llvm/Analysis/DataStructure/DSGraphTraits.h"
18 #include "llvm/Module.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/GraphWriter.h"
23 #include "llvm/ADT/Statistic.h"
24 #include <fstream>
25 #include <sstream>
26 using namespace llvm;
27
28 // OnlyPrintMain - The DataStructure printer exposes this option to allow
29 // printing of only the graph for "main".
30 //
31 namespace {
32   cl::opt<bool> OnlyPrintMain("only-print-main-ds", cl::ReallyHidden);
33   cl::opt<bool> DontPrintAnything("dont-print-ds", cl::ReallyHidden);
34   Statistic<> MaxGraphSize   ("dsa", "Maximum graph size");
35   Statistic<> NumFoldedNodes ("dsa", "Number of folded nodes (in final graph)");
36 }
37
38 void DSNode::dump() const { print(std::cerr, 0); }
39
40 static std::string getCaption(const DSNode *N, const DSGraph *G) {
41   std::stringstream OS;
42   Module *M = 0;
43
44   if (!G) G = N->getParentGraph();
45
46   // Get the module from ONE of the functions in the graph it is available.
47   if (G && G->retnodes_begin() != G->retnodes_end())
48     M = G->retnodes_begin()->first->getParent();
49   if (M == 0 && G) {
50     // If there is a global in the graph, we can use it to find the module.
51     const DSScalarMap &SM = G->getScalarMap();
52     if (SM.global_begin() != SM.global_end())
53       M = (*SM.global_begin())->getParent();
54   }
55
56   if (N->isNodeCompletelyFolded())
57     OS << "COLLAPSED";
58   else {
59     WriteTypeSymbolic(OS, N->getType(), M);
60     if (N->isArray())
61       OS << " array";
62   }
63   if (unsigned NodeType = N->getNodeFlags()) {
64     OS << ": ";
65     if (NodeType & DSNode::AllocaNode ) OS << "S";
66     if (NodeType & DSNode::HeapNode   ) OS << "H";
67     if (NodeType & DSNode::GlobalNode ) OS << "G";
68     if (NodeType & DSNode::UnknownNode) OS << "U";
69     if (NodeType & DSNode::Incomplete ) OS << "I";
70     if (NodeType & DSNode::Modified   ) OS << "M";
71     if (NodeType & DSNode::Read       ) OS << "R";
72 #ifndef NDEBUG
73     if (NodeType & DSNode::DEAD       ) OS << "<dead>";
74 #endif
75     OS << "\n";
76   }
77
78   EquivalenceClasses<GlobalValue*> *GlobalECs = 0;
79   if (G) GlobalECs = &G->getGlobalECs();
80   
81   for (unsigned i = 0, e = N->getGlobalsList().size(); i != e; ++i) {
82     WriteAsOperand(OS, N->getGlobalsList()[i], false, true, M);
83
84     // Figure out how many globals are equivalent to this one.
85     if (GlobalECs) {
86       EquivalenceClasses<GlobalValue*>::iterator I =
87         GlobalECs->findValue(N->getGlobalsList()[i]);
88       if (I != GlobalECs->end()) {
89         unsigned NumMembers = 
90           std::distance(GlobalECs->member_begin(I), GlobalECs->member_end());
91         if (NumMembers != 1) OS << " + " << (NumMembers-1) << " EC";
92       }
93     }
94     OS << "\n";
95   }
96
97   return OS.str();
98 }
99
100 namespace llvm {
101 template<>
102 struct DOTGraphTraits<const DSGraph*> : public DefaultDOTGraphTraits {
103   static std::string getGraphName(const DSGraph *G) {
104     switch (G->getReturnNodes().size()) {
105     case 0: return G->getFunctionNames();
106     case 1: return "Function " + G->getFunctionNames();
107     default: return "Functions: " + G->getFunctionNames();
108     }
109   }
110
111   static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {
112     return getCaption(Node, Graph);
113   }
114
115   static std::string getNodeAttributes(const DSNode *N) {
116     return "shape=Mrecord";
117   }
118
119   static bool edgeTargetsEdgeSource(const void *Node,
120                                     DSNode::const_iterator I) {
121     unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
122     return (O >> DS::PointerShift) != 0;
123   }
124
125   static DSNode::const_iterator getEdgeTarget(const DSNode *Node,
126                                               DSNode::const_iterator I) {
127     unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
128     unsigned LinkNo = O >> DS::PointerShift;
129     const DSNode *N = *I;
130     DSNode::const_iterator R = N->begin();
131     for (; LinkNo; --LinkNo)
132       ++R;
133     return R;
134   }
135
136   
137   /// addCustomGraphFeatures - Use this graph writing hook to emit call nodes
138   /// and the return node.
139   ///
140   static void addCustomGraphFeatures(const DSGraph *G,
141                                      GraphWriter<const DSGraph*> &GW) {
142     Module *CurMod = 0;
143     if (G->retnodes_begin() != G->retnodes_end())
144       CurMod = G->retnodes_begin()->first->getParent();
145     else {
146       // If there is a global in the graph, we can use it to find the module.
147       const DSScalarMap &SM = G->getScalarMap();
148       if (SM.global_begin() != SM.global_end())
149         CurMod = (*SM.global_begin())->getParent();
150     }
151
152
153     // Add scalar nodes to the graph...
154     const DSGraph::ScalarMapTy &VM = G->getScalarMap();
155     for (DSGraph::ScalarMapTy::const_iterator I = VM.begin(); I != VM.end();++I)
156       if (!isa<GlobalValue>(I->first)) {
157         std::stringstream OS;
158         WriteAsOperand(OS, I->first, false, true, CurMod);
159         GW.emitSimpleNode(I->first, "", OS.str());
160         
161         // Add edge from return node to real destination
162         DSNode *DestNode = I->second.getNode();
163         int EdgeDest = I->second.getOffset() >> DS::PointerShift;
164         if (EdgeDest == 0) EdgeDest = -1;
165         GW.emitEdge(I->first, -1, DestNode,
166                     EdgeDest, "arrowtail=tee,color=gray63");
167       }
168
169
170     // Output the returned value pointer...
171     for (DSGraph::retnodes_iterator I = G->retnodes_begin(),
172            E = G->retnodes_end(); I != E; ++I)
173       if (I->second.getNode()) {
174         std::string Label;
175         if (G->getReturnNodes().size() == 1)
176           Label = "returning";
177         else
178           Label = I->first->getName() + " ret node";
179         // Output the return node...
180         GW.emitSimpleNode((void*)I->first, "plaintext=circle", Label);
181
182         // Add edge from return node to real destination
183         DSNode *RetNode = I->second.getNode();
184         int RetEdgeDest = I->second.getOffset() >> DS::PointerShift;;
185         if (RetEdgeDest == 0) RetEdgeDest = -1;
186         GW.emitEdge((void*)I->first, -1, RetNode,
187                     RetEdgeDest, "arrowtail=tee,color=gray63");
188       }
189
190     // Output all of the call nodes...
191     const std::list<DSCallSite> &FCs =
192       G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()
193       : G->getFunctionCalls();
194     for (std::list<DSCallSite>::const_iterator I = FCs.begin(), E = FCs.end();
195          I != E; ++I) {
196       const DSCallSite &Call = *I;
197       std::vector<std::string> EdgeSourceCaptions(Call.getNumPtrArgs()+2);
198       EdgeSourceCaptions[0] = "r";
199       if (Call.isDirectCall())
200         EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();
201       else
202         EdgeSourceCaptions[1] = "f";
203
204       GW.emitSimpleNode(&Call, "shape=record", "call", Call.getNumPtrArgs()+2,
205                         &EdgeSourceCaptions);
206
207       if (DSNode *N = Call.getRetVal().getNode()) {
208         int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;
209         if (EdgeDest == 0) EdgeDest = -1;
210         GW.emitEdge(&Call, 0, N, EdgeDest, "color=gray63,tailclip=false");
211       }
212
213       // Print out the callee...
214       if (Call.isIndirectCall()) {
215         DSNode *N = Call.getCalleeNode();
216         assert(N && "Null call site callee node!");
217         GW.emitEdge(&Call, 1, N, -1, "color=gray63,tailclip=false");
218       }
219
220       for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)
221         if (DSNode *N = Call.getPtrArg(j).getNode()) {
222           int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;
223           if (EdgeDest == 0) EdgeDest = -1;
224           GW.emitEdge(&Call, j+2, N, EdgeDest, "color=gray63,tailclip=false");
225         }
226     }
227   }
228 };
229 }   // end namespace llvm
230
231 void DSNode::print(std::ostream &O, const DSGraph *G) const {
232   GraphWriter<const DSGraph *> W(O, G);
233   W.writeNode(this);
234 }
235
236 void DSGraph::print(std::ostream &O) const {
237   WriteGraph(O, this, "DataStructures");
238 }
239
240 void DSGraph::writeGraphToFile(std::ostream &O,
241                                const std::string &GraphName) const {
242   std::string Filename = GraphName + ".dot";
243   O << "Writing '" << Filename << "'...";
244   std::ofstream F(Filename.c_str());
245   
246   if (F.good()) {
247     print(F);
248     unsigned NumCalls = shouldPrintAuxCalls() ?
249       getAuxFunctionCalls().size() : getFunctionCalls().size();
250     O << " [" << getGraphSize() << "+" << NumCalls << "]\n";
251   } else {
252     O << "  error opening file for writing!\n";
253   }
254 }
255
256 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
257 /// then cleanup.  For use from the debugger.
258 ///
259 void DSGraph::viewGraph() const {
260   std::ofstream F("/tmp/tempgraph.dot");
261   if (!F.good()) {
262     std::cerr << "Error opening '/tmp/tempgraph.dot' for temporary graph!\n";
263     return;
264   }
265   print(F);
266   F.close();
267   if (system("dot -Tps -Gsize=10,7.5 -Grotate=90 /tmp/tempgraph.dot > /tmp/tempgraph.ps"))
268     std::cerr << "Error running dot: 'dot' not in path?\n";
269   system("gv /tmp/tempgraph.ps");
270   system("rm /tmp/tempgraph.dot /tmp/tempgraph.ps");
271 }
272
273
274 template <typename Collection>
275 static void printCollection(const Collection &C, std::ostream &O,
276                             const Module *M, const std::string &Prefix) {
277   if (M == 0) {
278     O << "Null Module pointer, cannot continue!\n";
279     return;
280   }
281
282   unsigned TotalNumNodes = 0, TotalCallNodes = 0;
283   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
284     if (C.hasGraph(*I)) {
285       DSGraph &Gr = C.getDSGraph((Function&)*I);
286       unsigned NumCalls = Gr.shouldPrintAuxCalls() ?
287         Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();
288       bool IsDuplicateGraph = false;
289
290       if (I->getName() == "main" || !OnlyPrintMain) {
291         Function *SCCFn = Gr.retnodes_begin()->first;
292         if (&*I == SCCFn) {
293           Gr.writeGraphToFile(O, Prefix+I->getName());
294         } else {
295           IsDuplicateGraph = true; // Don't double count node/call nodes.
296           O << "Didn't write '" << Prefix+I->getName()
297             << ".dot' - Graph already emitted to '" << Prefix+SCCFn->getName()
298             << "\n";
299         }
300       } else {
301         Function *SCCFn = Gr.retnodes_begin()->first;
302         if (&*I == SCCFn) {
303           O << "Skipped Writing '" << Prefix+I->getName() << ".dot'... ["
304             << Gr.getGraphSize() << "+" << NumCalls << "]\n";
305         } else {
306           IsDuplicateGraph = true; // Don't double count node/call nodes.
307         }
308       }
309
310       if (!IsDuplicateGraph) {
311         unsigned GraphSize = Gr.getGraphSize();
312         if (MaxGraphSize < GraphSize) MaxGraphSize = GraphSize;
313
314         TotalNumNodes += Gr.getGraphSize();
315         TotalCallNodes += NumCalls;
316         for (DSGraph::node_iterator NI = Gr.node_begin(), E = Gr.node_end();
317              NI != E; ++NI)
318           if (NI->isNodeCompletelyFolded())
319             ++NumFoldedNodes;
320       }
321     }
322
323   DSGraph &GG = C.getGlobalsGraph();
324   TotalNumNodes  += GG.getGraphSize();
325   TotalCallNodes += GG.getFunctionCalls().size();
326   if (!OnlyPrintMain) {
327     GG.writeGraphToFile(O, Prefix+"GlobalsGraph");
328   } else {
329     O << "Skipped Writing '" << Prefix << "GlobalsGraph.dot'... ["
330       << GG.getGraphSize() << "+" << GG.getFunctionCalls().size() << "]\n";
331   }
332
333   O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes 
334     << "] nodes total" << std::endl;
335 }
336
337
338 // print - Print out the analysis results...
339 void LocalDataStructures::print(std::ostream &O, const Module *M) const {
340   if (DontPrintAnything) return;
341   printCollection(*this, O, M, "ds.");
342 }
343
344 void BUDataStructures::print(std::ostream &O, const Module *M) const {
345   if (DontPrintAnything) return;
346   printCollection(*this, O, M, "bu.");
347 }
348
349 void TDDataStructures::print(std::ostream &O, const Module *M) const {
350   if (DontPrintAnything) return;
351   printCollection(*this, O, M, "td.");
352 }
353
354 void CompleteBUDataStructures::print(std::ostream &O, const Module *M) const {
355   if (DontPrintAnything) return;
356   printCollection(*this, O, M, "cbu.");
357 }
358
359
360 void EquivClassGraphs::print(std::ostream &O, const Module *M) const {
361   if (DontPrintAnything) return;
362   printCollection(*this, O, M, "eq.");
363 }
364