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