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