GraphWriter.h revision 34cd4a484e532cc463fd5a4bf59b88d13c5467c1
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())
52          switch (Str[i+1]) {
53            case 'l': continue; // don't disturb \l
54            case '|': case '{': case '}':
55               Str.erase(Str.begin()+i); continue;
56            default: break;
57          }
58      case '{': case '}':
59      case '<': case '>':
60      case '|': case '"':
61        Str.insert(Str.begin()+i, '\\');  // Escape character...
62        ++i;  // don't infinite loop
63        break;
64      }
65    return Str;
66  }
67}
68
69void DisplayGraph(const sys::Path& Filename);
70
71template<typename GraphType>
72class GraphWriter {
73  std::ostream &O;
74  const GraphType &G;
75
76  typedef DOTGraphTraits<GraphType>           DOTTraits;
77  typedef GraphTraits<GraphType>              GTraits;
78  typedef typename GTraits::NodeType          NodeType;
79  typedef typename GTraits::nodes_iterator    node_iterator;
80  typedef typename GTraits::ChildIteratorType child_iterator;
81public:
82  GraphWriter(std::ostream &o, const GraphType &g) : O(o), G(g) {}
83
84  void writeHeader(const std::string &Name) {
85    if (Name.empty())
86      O << "digraph foo {\n";        // Graph name doesn't matter
87    else
88      O << "digraph " << Name << " {\n";
89
90    if (DOTTraits::renderGraphFromBottomUp())
91      O << "\trankdir=\"BT\";\n";
92
93    std::string GraphName = DOTTraits::getGraphName(G);
94    if (!GraphName.empty())
95      O << "\tlabel=\"" << DOT::EscapeString(GraphName) << "\";\n";
96    O << DOTTraits::getGraphProperties(G);
97    O << "\n";
98  }
99
100  void writeFooter() {
101    // Finish off the graph
102    O << "}\n";
103  }
104
105  void writeNodes() {
106    // Loop over the graph, printing it out...
107    for (node_iterator I = GTraits::nodes_begin(G), E = GTraits::nodes_end(G);
108         I != E; ++I)
109      writeNode(*I);
110  }
111
112  void writeNode(NodeType& Node) {
113    writeNode(&Node);
114  }
115
116  void writeNode(NodeType *const *Node) {
117    writeNode(*Node);
118  }
119
120  void writeNode(NodeType *Node) {
121    std::string NodeAttributes = DOTTraits::getNodeAttributes(Node, G);
122
123    O << "\tNode" << reinterpret_cast<const void*>(Node) << " [shape=record,";
124    if (!NodeAttributes.empty()) O << NodeAttributes << ",";
125    O << "label=\"{";
126
127    if (!DOTTraits::renderGraphFromBottomUp()) {
128      O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
129
130      // If we should include the address of the node in the label, do so now.
131      if (DOTTraits::hasNodeAddressLabel(Node, G))
132        O << "|" << (void*)Node;
133    }
134
135    // Print out the fields of the current node...
136    child_iterator EI = GTraits::child_begin(Node);
137    child_iterator EE = GTraits::child_end(Node);
138    if (EI != EE) {
139      if (!DOTTraits::renderGraphFromBottomUp()) O << "|";
140      O << "{";
141
142      for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
143        if (i) O << "|";
144        O << "<g" << i << ">" << DOTTraits::getEdgeSourceLabel(Node, EI);
145      }
146
147      if (EI != EE)
148        O << "|<g64>truncated...";
149      O << "}";
150      if (DOTTraits::renderGraphFromBottomUp()) O << "|";
151    }
152
153    if (DOTTraits::renderGraphFromBottomUp()) {
154      O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
155
156      // If we should include the address of the node in the label, do so now.
157      if (DOTTraits::hasNodeAddressLabel(Node, G))
158        O << "|" << (void*)Node;
159    }
160
161    O << "}\"];\n";   // Finish printing the "node" line
162
163    // Output all of the edges now
164    EI = GTraits::child_begin(Node);
165    for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
166      writeEdge(Node, i, EI);
167    for (; EI != EE; ++EI)
168      writeEdge(Node, 64, EI);
169  }
170
171  void writeEdge(NodeType *Node, unsigned edgeidx, child_iterator EI) {
172    if (NodeType *TargetNode = *EI) {
173      int DestPort = -1;
174      if (DOTTraits::edgeTargetsEdgeSource(Node, EI)) {
175        child_iterator TargetIt = DOTTraits::getEdgeTarget(Node, EI);
176
177        // Figure out which edge this targets...
178        unsigned Offset =
179          (unsigned)std::distance(GTraits::child_begin(TargetNode), TargetIt);
180        DestPort = static_cast<int>(Offset);
181      }
182
183      emitEdge(reinterpret_cast<const void*>(Node), edgeidx,
184               reinterpret_cast<const void*>(TargetNode), DestPort,
185               DOTTraits::getEdgeAttributes(Node, EI));
186    }
187  }
188
189  /// emitSimpleNode - Outputs a simple (non-record) node
190  void emitSimpleNode(const void *ID, const std::string &Attr,
191                      const std::string &Label, unsigned NumEdgeSources = 0,
192                      const std::vector<std::string> *EdgeSourceLabels = 0) {
193    O << "\tNode" << ID << "[ ";
194    if (!Attr.empty())
195      O << Attr << ",";
196    O << " label =\"";
197    if (NumEdgeSources) O << "{";
198    O << DOT::EscapeString(Label);
199    if (NumEdgeSources) {
200      O << "|{";
201
202      for (unsigned i = 0; i != NumEdgeSources; ++i) {
203        if (i) O << "|";
204        O << "<g" << i << ">";
205        if (EdgeSourceLabels) O << (*EdgeSourceLabels)[i];
206      }
207      O << "}}";
208    }
209    O << "\"];\n";
210  }
211
212  /// emitEdge - Output an edge from a simple node into the graph...
213  void emitEdge(const void *SrcNodeID, int SrcNodePort,
214                const void *DestNodeID, int DestNodePort,
215                const std::string &Attrs) {
216    if (SrcNodePort  > 64) return;             // Eminating from truncated part?
217    if (DestNodePort > 64) DestNodePort = 64;  // Targetting the truncated part?
218
219    O << "\tNode" << SrcNodeID;
220    if (SrcNodePort >= 0)
221      O << ":g" << SrcNodePort;
222    O << " -> Node" << reinterpret_cast<const void*>(DestNodeID);
223    if (DestNodePort >= 0)
224      O << ":g" << DestNodePort;
225
226    if (!Attrs.empty())
227      O << "[" << Attrs << "]";
228    O << ";\n";
229  }
230};
231
232template<typename GraphType>
233std::ostream &WriteGraph(std::ostream &O, const GraphType &G,
234                         const std::string &Name = "") {
235  // Start the graph emission process...
236  GraphWriter<GraphType> W(O, G);
237
238  // Output the header for the graph...
239  W.writeHeader(Name);
240
241  // Emit all of the nodes in the graph...
242  W.writeNodes();
243
244  // Output any customizations on the graph
245  DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
246
247  // Output the end of the graph
248  W.writeFooter();
249  return O;
250}
251
252template<typename GraphType>
253sys::Path WriteGraph(const GraphType &G,
254                     const std::string& Name,
255                     const std::string& Title = "") {
256  std::string ErrMsg;
257  sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
258  if (Filename.isEmpty()) {
259    cerr << "Error: " << ErrMsg << "\n";
260    return Filename;
261  }
262  Filename.appendComponent(Name + ".dot");
263  if (Filename.makeUnique(true,&ErrMsg)) {
264    cerr << "Error: " << ErrMsg << "\n";
265    return sys::Path();
266  }
267
268  cerr << "Writing '" << Filename << "'... ";
269
270  std::ofstream O(Filename.c_str());
271
272  if (O.good()) {
273    // Start the graph emission process...
274    GraphWriter<GraphType> W(O, G);
275
276    // Output the header for the graph...
277    W.writeHeader(Title);
278
279    // Emit all of the nodes in the graph...
280    W.writeNodes();
281
282    // Output any customizations on the graph
283    DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
284
285    // Output the end of the graph
286    W.writeFooter();
287    cerr << " done. \n";
288
289    O.close();
290
291  } else {
292    cerr << "error opening file for writing!\n";
293    Filename.clear();
294  }
295
296  return Filename;
297}
298
299/// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
300/// then cleanup.  For use from the debugger.
301///
302template<typename GraphType>
303void ViewGraph(const GraphType& G,
304               const std::string& Name,
305               const std::string& Title = "") {
306  sys::Path Filename =  WriteGraph(G, Name, Title);
307
308  if (Filename.isEmpty()) {
309    return;
310  }
311
312  DisplayGraph(Filename);
313}
314
315} // End llvm namespace
316
317#endif
318