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