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