GraphWriter.h revision 7ed47a13356daed2a34cd2209a31f92552e3bdd8
1//===-- llvm/Support/GraphWriter.h - Write graph to a .dot file -*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a simple interface that can be used to print out generic
11// LLVM graphs to ".dot" files.  "dot" is a tool that is part of the AT&T
12// graphviz package (http://www.research.att.com/sw/tools/graphviz/) which can
13// be used to turn the files output by this interface into a variety of
14// different graphics formats.
15//
16// Graphs do not need to implement any interface past what is already required
17// by the GraphTraits template, but they can choose to implement specializations
18// of the DOTGraphTraits template if they want to customize the graphs output in
19// any way.
20//
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_SUPPORT_GRAPHWRITER_H
24#define LLVM_SUPPORT_GRAPHWRITER_H
25
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/DOTGraphTraits.h"
28#include "llvm/ADT/GraphTraits.h"
29#include "llvm/System/Path.h"
30#include <fstream>
31#include <vector>
32
33namespace llvm {
34
35namespace DOT {  // Private functions...
36  inline std::string EscapeString(const std::string &Label) {
37    std::string Str(Label);
38    for (unsigned i = 0; i != Str.length(); ++i)
39      switch (Str[i]) {
40      case '\n':
41        Str.insert(Str.begin()+i, '\\');  // Escape character...
42        ++i;
43        Str[i] = 'n';
44        break;
45      case '\t':
46        Str.insert(Str.begin()+i, ' ');  // Convert to two spaces
47        ++i;
48        Str[i] = ' ';
49        break;
50      case '\\':
51        if (i+1 != Str.length() && Str[i+1] == 'l')
52          break;  // don't disturb \l
53      case '{': case '}':
54      case '<': case '>':
55      case '|': case '"':
56        Str.insert(Str.begin()+i, '\\');  // Escape character...
57        ++i;  // don't infinite loop
58        break;
59      }
60    return Str;
61  }
62}
63
64void DisplayGraph(const sys::Path& Filename);
65
66template<typename GraphType>
67class GraphWriter {
68  std::ostream &O;
69  const GraphType &G;
70
71  typedef DOTGraphTraits<GraphType>           DOTTraits;
72  typedef GraphTraits<GraphType>              GTraits;
73  typedef typename GTraits::NodeType          NodeType;
74  typedef typename GTraits::nodes_iterator    node_iterator;
75  typedef typename GTraits::ChildIteratorType child_iterator;
76public:
77  GraphWriter(std::ostream &o, const GraphType &g) : O(o), G(g) {}
78
79  void writeHeader(const std::string &Name) {
80    if (Name.empty())
81      O << "digraph foo {\n";        // Graph name doesn't matter
82    else
83      O << "digraph " << Name << " {\n";
84
85    if (DOTTraits::renderGraphFromBottomUp())
86      O << "\trankdir=\"BT\";\n";
87
88    std::string GraphName = DOTTraits::getGraphName(G);
89    if (!GraphName.empty())
90      O << "\tlabel=\"" << DOT::EscapeString(GraphName) << "\";\n";
91    O << DOTTraits::getGraphProperties(G);
92    O << "\n";
93  }
94
95  void writeFooter() {
96    // Finish off the graph
97    O << "}\n";
98  }
99
100  void writeNodes() {
101    // Loop over the graph, printing it out...
102    for (node_iterator I = GTraits::nodes_begin(G), E = GTraits::nodes_end(G);
103         I != E; ++I)
104      writeNode(*I);
105  }
106
107  void writeNode(NodeType& Node) {
108    writeNode(&Node);
109  }
110
111  void writeNode(NodeType *const *Node) {
112    writeNode(*Node);
113  }
114
115  void writeNode(NodeType *Node) {
116    std::string NodeAttributes = DOTTraits::getNodeAttributes(Node, G);
117
118    O << "\tNode" << reinterpret_cast<const void*>(Node) << " [shape=record,";
119    if (!NodeAttributes.empty()) O << NodeAttributes << ",";
120    O << "label=\"{";
121
122    if (!DOTTraits::renderGraphFromBottomUp()) {
123      O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
124
125      // If we should include the address of the node in the label, do so now.
126      if (DOTTraits::hasNodeAddressLabel(Node, G))
127        O << "|" << (void*)Node;
128    }
129
130    // Print out the fields of the current node...
131    child_iterator EI = GTraits::child_begin(Node);
132    child_iterator EE = GTraits::child_end(Node);
133    if (EI != EE) {
134      if (!DOTTraits::renderGraphFromBottomUp()) O << "|";
135      O << "{";
136
137      for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
138        if (i) O << "|";
139        O << "<g" << i << ">" << DOTTraits::getEdgeSourceLabel(Node, EI);
140      }
141
142      if (EI != EE)
143        O << "|<g64>truncated...";
144      O << "}";
145      if (DOTTraits::renderGraphFromBottomUp()) O << "|";
146    }
147
148    if (DOTTraits::renderGraphFromBottomUp()) {
149      O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
150
151      // If we should include the address of the node in the label, do so now.
152      if (DOTTraits::hasNodeAddressLabel(Node, G))
153        O << "|" << (void*)Node;
154    }
155
156    O << "}\"];\n";   // Finish printing the "node" line
157
158    // Output all of the edges now
159    EI = GTraits::child_begin(Node);
160    for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
161      writeEdge(Node, i, EI);
162    for (; EI != EE; ++EI)
163      writeEdge(Node, 64, EI);
164  }
165
166  void writeEdge(NodeType *Node, unsigned edgeidx, child_iterator EI) {
167    if (NodeType *TargetNode = *EI) {
168      int DestPort = -1;
169      if (DOTTraits::edgeTargetsEdgeSource(Node, EI)) {
170        child_iterator TargetIt = DOTTraits::getEdgeTarget(Node, EI);
171
172        // Figure out which edge this targets...
173        unsigned Offset = std::distance(GTraits::child_begin(TargetNode),
174                                        TargetIt);
175        DestPort = static_cast<int>(Offset);
176      }
177
178      emitEdge(reinterpret_cast<const void*>(Node), edgeidx,
179               reinterpret_cast<const void*>(TargetNode), DestPort,
180               DOTTraits::getEdgeAttributes(Node, EI));
181    }
182  }
183
184  /// emitSimpleNode - Outputs a simple (non-record) node
185  void emitSimpleNode(const void *ID, const std::string &Attr,
186                      const std::string &Label, unsigned NumEdgeSources = 0,
187                      const std::vector<std::string> *EdgeSourceLabels = 0) {
188    O << "\tNode" << ID << "[ ";
189    if (!Attr.empty())
190      O << Attr << ",";
191    O << " label =\"";
192    if (NumEdgeSources) O << "{";
193    O << DOT::EscapeString(Label);
194    if (NumEdgeSources) {
195      O << "|{";
196
197      for (unsigned i = 0; i != NumEdgeSources; ++i) {
198        if (i) O << "|";
199        O << "<g" << i << ">";
200        if (EdgeSourceLabels) O << (*EdgeSourceLabels)[i];
201      }
202      O << "}}";
203    }
204    O << "\"];\n";
205  }
206
207  /// emitEdge - Output an edge from a simple node into the graph...
208  void emitEdge(const void *SrcNodeID, int SrcNodePort,
209                const void *DestNodeID, int DestNodePort,
210                const std::string &Attrs) {
211    if (SrcNodePort  > 64) return;             // Eminating from truncated part?
212    if (DestNodePort > 64) DestNodePort = 64;  // Targetting the truncated part?
213
214    O << "\tNode" << SrcNodeID;
215    if (SrcNodePort >= 0)
216      O << ":g" << SrcNodePort;
217    O << " -> Node" << reinterpret_cast<const void*>(DestNodeID);
218    if (DestNodePort >= 0)
219      O << ":g" << DestNodePort;
220
221    if (!Attrs.empty())
222      O << "[" << Attrs << "]";
223    O << ";\n";
224  }
225};
226
227template<typename GraphType>
228std::ostream &WriteGraph(std::ostream &O, const GraphType &G,
229                         const std::string &Name = "") {
230  // Start the graph emission process...
231  GraphWriter<GraphType> W(O, G);
232
233  // Output the header for the graph...
234  W.writeHeader(Name);
235
236  // Emit all of the nodes in the graph...
237  W.writeNodes();
238
239  // Output any customizations on the graph
240  DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
241
242  // Output the end of the graph
243  W.writeFooter();
244  return O;
245}
246
247template<typename GraphType>
248sys::Path WriteGraph(const GraphType &G,
249                     const std::string& Name,
250                     const std::string& Title = "") {
251  std::string ErrMsg;
252  sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
253  if (Filename.isEmpty()) {
254    cerr << "Error: " << ErrMsg << "\n";
255    return Filename;
256  }
257  Filename.appendComponent(Name + ".dot");
258  if (Filename.makeUnique(true,&ErrMsg)) {
259    cerr << "Error: " << ErrMsg << "\n";
260    return sys::Path();
261  }
262
263  cerr << "Writing '" << Filename << "'... ";
264
265  std::ofstream O(Filename.c_str());
266
267  if (O.good()) {
268    // Start the graph emission process...
269    GraphWriter<GraphType> W(O, G);
270
271    // Output the header for the graph...
272    W.writeHeader(Title);
273
274    // Emit all of the nodes in the graph...
275    W.writeNodes();
276
277    // Output any customizations on the graph
278    DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
279
280    // Output the end of the graph
281    W.writeFooter();
282    cerr << " done. \n";
283
284    O.close();
285
286  } else {
287    cerr << "error opening file for writing!\n";
288    Filename.clear();
289  }
290
291  return Filename;
292}
293
294/// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
295/// then cleanup.  For use from the debugger.
296///
297template<typename GraphType>
298void ViewGraph(const GraphType& G,
299               const std::string& Name,
300               const std::string& Title = "") {
301  sys::Path Filename =  WriteGraph(G, Name, Title);
302
303  if (Filename.isEmpty()) {
304    return;
305  }
306
307  DisplayGraph(Filename);
308}
309
310} // End llvm namespace
311
312#endif
313