GraphWriter.h revision 9d5b532de9bdca37810a59a93a69128441b02c55
1//===-- llvm/Support/GraphWriter.h - Write graph to a .dot file -*- C++ -*-===//
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 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/DOTGraphTraits.h"
27#include "llvm/ADT/GraphTraits.h"
28#include "llvm/System/Path.h"
29#include <vector>
30#include <iostream>
31#include <fstream>
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 '"':
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 *const *Node) {
108    writeNode(*Node);
109  }
110
111  void writeNode(NodeType *Node) {
112    std::string NodeAttributes = DOTTraits::getNodeAttributes(Node);
113
114    O << "\tNode" << reinterpret_cast<const void*>(Node) << " [shape=record,";
115    if (!NodeAttributes.empty()) O << NodeAttributes << ",";
116    O << "label=\"{";
117
118    if (!DOTTraits::renderGraphFromBottomUp()) {
119      O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
120
121      // If we should include the address of the node in the label, do so now.
122      if (DOTTraits::hasNodeAddressLabel(Node, G))
123        O << "|" << (void*)Node;
124    }
125
126    // Print out the fields of the current node...
127    child_iterator EI = GTraits::child_begin(Node);
128    child_iterator EE = GTraits::child_end(Node);
129    if (EI != EE) {
130      if (!DOTTraits::renderGraphFromBottomUp()) O << "|";
131      O << "{";
132
133      for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
134        if (i) O << "|";
135        O << "<g" << i << ">" << DOTTraits::getEdgeSourceLabel(Node, EI);
136      }
137
138      if (EI != EE)
139        O << "|<g64>truncated...";
140      O << "}";
141      if (DOTTraits::renderGraphFromBottomUp()) O << "|";
142    }
143
144    if (DOTTraits::renderGraphFromBottomUp()) {
145      O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
146
147      // If we should include the address of the node in the label, do so now.
148      if (DOTTraits::hasNodeAddressLabel(Node, G))
149        O << "|" << (void*)Node;
150    }
151
152    O << "}\"];\n";   // Finish printing the "node" line
153
154    // Output all of the edges now
155    EI = GTraits::child_begin(Node);
156    for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
157      writeEdge(Node, i, EI);
158    for (; EI != EE; ++EI)
159      writeEdge(Node, 64, EI);
160  }
161
162  void writeEdge(NodeType *Node, unsigned edgeidx, child_iterator EI) {
163    if (NodeType *TargetNode = *EI) {
164      int DestPort = -1;
165      if (DOTTraits::edgeTargetsEdgeSource(Node, EI)) {
166        child_iterator TargetIt = DOTTraits::getEdgeTarget(Node, EI);
167
168        // Figure out which edge this targets...
169        unsigned Offset = std::distance(GTraits::child_begin(TargetNode),
170                                        TargetIt);
171        DestPort = static_cast<int>(Offset);
172      }
173
174      emitEdge(reinterpret_cast<const void*>(Node), edgeidx,
175               reinterpret_cast<const void*>(TargetNode), DestPort,
176               DOTTraits::getEdgeAttributes(Node, EI));
177    }
178  }
179
180  /// emitSimpleNode - Outputs a simple (non-record) node
181  void emitSimpleNode(const void *ID, const std::string &Attr,
182                      const std::string &Label, unsigned NumEdgeSources = 0,
183                      const std::vector<std::string> *EdgeSourceLabels = 0) {
184    O << "\tNode" << ID << "[ ";
185    if (!Attr.empty())
186      O << Attr << ",";
187    O << " label =\"";
188    if (NumEdgeSources) O << "{";
189    O << DOT::EscapeString(Label);
190    if (NumEdgeSources) {
191      O << "|{";
192
193      for (unsigned i = 0; i != NumEdgeSources; ++i) {
194        if (i) O << "|";
195        O << "<g" << i << ">";
196        if (EdgeSourceLabels) O << (*EdgeSourceLabels)[i];
197      }
198      O << "}}";
199    }
200    O << "\"];\n";
201  }
202
203  /// emitEdge - Output an edge from a simple node into the graph...
204  void emitEdge(const void *SrcNodeID, int SrcNodePort,
205                const void *DestNodeID, int DestNodePort,
206                const std::string &Attrs) {
207    if (SrcNodePort  > 64) return;             // Eminating from truncated part?
208    if (DestNodePort > 64) DestNodePort = 64;  // Targetting the truncated part?
209
210    O << "\tNode" << SrcNodeID;
211    if (SrcNodePort >= 0)
212      O << ":g" << SrcNodePort;
213    O << " -> Node" << reinterpret_cast<const void*>(DestNodeID);
214    if (DestNodePort >= 0)
215      O << ":g" << DestNodePort;
216
217    if (!Attrs.empty())
218      O << "[" << Attrs << "]";
219    O << ";\n";
220  }
221};
222
223template<typename GraphType>
224std::ostream &WriteGraph(std::ostream &O, const GraphType &G,
225                         const std::string &Name = "") {
226  // Start the graph emission process...
227  GraphWriter<GraphType> W(O, G);
228
229  // Output the header for the graph...
230  W.writeHeader(Name);
231
232  // Emit all of the nodes in the graph...
233  W.writeNodes();
234
235  // Output any customizations on the graph
236  DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
237
238  // Output the end of the graph
239  W.writeFooter();
240  return O;
241}
242
243template<typename GraphType>
244sys::Path WriteGraph(const GraphType &G,
245                     const std::string& Name,
246                     const std::string& Title = "") {
247  sys::Path Filename = sys::Path::GetTemporaryDirectory();;
248  Filename.appendComponent(Name + ".dot");
249  Filename.makeUnique();
250  std::cerr << "Writing '" << Filename << "'... ";
251
252  std::ofstream O(Filename.c_str());
253
254  if (O.good()) {
255    // Start the graph emission process...
256    GraphWriter<GraphType> W(O, G);
257
258    // Output the header for the graph...
259    W.writeHeader(Title);
260
261    // Emit all of the nodes in the graph...
262    W.writeNodes();
263
264    // Output any customizations on the graph
265    DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
266
267    // Output the end of the graph
268    W.writeFooter();
269    std::cerr << " done. \n";
270
271    O.close();
272
273  } else {
274    std::cerr << "error opening file for writing!\n";
275    Filename.clear();
276  }
277
278  return Filename;
279}
280
281/// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
282/// then cleanup.  For use from the debugger.
283///
284template<typename GraphType>
285void ViewGraph(const GraphType& G,
286               const std::string& Name,
287               const std::string& Title = "") {
288  sys::Path Filename =  WriteGraph(G, Name, Title);
289
290  if (Filename.isEmpty()) {
291    return;
292  }
293
294  DisplayGraph(Filename);
295}
296
297} // End llvm namespace
298
299#endif
300