GraphWriter.h revision e6e34bc07c7c3b1c8cd1e231ec543e484301a055
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 <vector>
29#include <iostream>
30
31namespace llvm {
32
33namespace DOT {  // Private functions...
34  inline std::string EscapeString(const std::string &Label) {
35    std::string Str(Label);
36    for (unsigned i = 0; i != Str.length(); ++i)
37      switch (Str[i]) {
38      case '\n':
39        Str.insert(Str.begin()+i, '\\');  // Escape character...
40        ++i;
41        Str[i] = 'n';
42        break;
43      case '\t':
44        Str.insert(Str.begin()+i, ' ');  // Convert to two spaces
45        ++i;
46        Str[i] = ' ';
47        break;
48      case '\\':
49        if (i+1 != Str.length() && Str[i+1] == 'l')
50          break;  // don't disturb \l
51      case '{': case '}':
52      case '<': case '>':
53      case '"':
54        Str.insert(Str.begin()+i, '\\');  // Escape character...
55        ++i;  // don't infinite loop
56        break;
57      }
58    return Str;
59  }
60}
61
62template<typename GraphType>
63class GraphWriter {
64  std::ostream &O;
65  const GraphType &G;
66
67  typedef DOTGraphTraits<GraphType>           DOTTraits;
68  typedef GraphTraits<GraphType>              GTraits;
69  typedef typename GTraits::NodeType          NodeType;
70  typedef typename GTraits::nodes_iterator    node_iterator;
71  typedef typename GTraits::ChildIteratorType child_iterator;
72public:
73  GraphWriter(std::ostream &o, const GraphType &g) : O(o), G(g) {}
74
75  void writeHeader(const std::string &Name) {
76    if (Name.empty())
77      O << "digraph foo {\n";        // Graph name doesn't matter
78    else
79      O << "digraph " << Name << " {\n";
80
81    if (DOTTraits::renderGraphFromBottomUp())
82      O << "\trankdir=\"BT\";\n";
83
84    std::string GraphName = DOTTraits::getGraphName(G);
85    if (!GraphName.empty())
86      O << "\tlabel=\"" << DOT::EscapeString(GraphName) << "\";\n";
87    O << DOTTraits::getGraphProperties(G);
88    O << "\n";
89  }
90
91  void writeFooter() {
92    // Finish off the graph
93    O << "}\n";
94  }
95
96  void writeNodes() {
97    // Loop over the graph, printing it out...
98    for (node_iterator I = GTraits::nodes_begin(G), E = GTraits::nodes_end(G);
99         I != E; ++I)
100      writeNode(&*I);
101  }
102
103  void writeNode(NodeType *const *Node) {
104    writeNode(*Node);
105  }
106
107  void writeNode(NodeType *Node) {
108    std::string NodeAttributes = DOTTraits::getNodeAttributes(Node);
109
110    O << "\tNode" << reinterpret_cast<const void*>(Node) << " [shape=record,";
111    if (!NodeAttributes.empty()) O << NodeAttributes << ",";
112    O << "label=\"{";
113
114    if (!DOTTraits::renderGraphFromBottomUp())
115      O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
116
117    // Print out the fields of the current node...
118    child_iterator EI = GTraits::child_begin(Node);
119    child_iterator EE = GTraits::child_end(Node);
120    if (EI != EE) {
121      if (!DOTTraits::renderGraphFromBottomUp()) O << "|";
122      O << "{";
123
124      for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
125        if (i) O << "|";
126        O << "<g" << i << ">" << DOTTraits::getEdgeSourceLabel(Node, EI);
127      }
128
129      if (EI != EE)
130        O << "|<g64>truncated...";
131      O << "}";
132      if (DOTTraits::renderGraphFromBottomUp()) O << "|";
133    }
134    if (DOTTraits::renderGraphFromBottomUp())
135      O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
136
137    O << "|\\N}\"];\n";   // Finish printing the "node" line
138
139    // Output all of the edges now
140    EI = GTraits::child_begin(Node);
141    for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
142      writeEdge(Node, i, EI);
143    for (; EI != EE; ++EI)
144      writeEdge(Node, 64, EI);
145  }
146
147  void writeEdge(NodeType *Node, unsigned edgeidx, child_iterator EI) {
148    if (NodeType *TargetNode = *EI) {
149      int DestPort = -1;
150      if (DOTTraits::edgeTargetsEdgeSource(Node, EI)) {
151        child_iterator TargetIt = DOTTraits::getEdgeTarget(Node, EI);
152
153        // Figure out which edge this targets...
154        unsigned Offset = std::distance(GTraits::child_begin(TargetNode),
155                                        TargetIt);
156        DestPort = static_cast<int>(Offset);
157      }
158
159      emitEdge(reinterpret_cast<const void*>(Node), edgeidx,
160               reinterpret_cast<const void*>(TargetNode), DestPort,
161               DOTTraits::getEdgeAttributes(Node, EI));
162    }
163  }
164
165  /// emitSimpleNode - Outputs a simple (non-record) node
166  void emitSimpleNode(const void *ID, const std::string &Attr,
167                      const std::string &Label, unsigned NumEdgeSources = 0,
168                      const std::vector<std::string> *EdgeSourceLabels = 0) {
169    O << "\tNode" << ID << "[ ";
170    if (!Attr.empty())
171      O << Attr << ",";
172    O << " label =\"";
173    if (NumEdgeSources) O << "{";
174    O << DOT::EscapeString(Label);
175    if (NumEdgeSources) {
176      O << "|{";
177
178      for (unsigned i = 0; i != NumEdgeSources; ++i) {
179        if (i) O << "|";
180        O << "<g" << i << ">";
181        if (EdgeSourceLabels) O << (*EdgeSourceLabels)[i];
182      }
183      O << "}}";
184    }
185    O << "\"];\n";
186  }
187
188  /// emitEdge - Output an edge from a simple node into the graph...
189  void emitEdge(const void *SrcNodeID, int SrcNodePort,
190                const void *DestNodeID, int DestNodePort,
191                const std::string &Attrs) {
192    if (SrcNodePort  > 64) return;             // Eminating from truncated part?
193    if (DestNodePort > 64) DestNodePort = 64;  // Targetting the truncated part?
194
195    O << "\tNode" << SrcNodeID;
196    if (SrcNodePort >= 0)
197      O << ":g" << SrcNodePort;
198    O << " -> Node" << reinterpret_cast<const void*>(DestNodeID);
199    if (DestNodePort >= 0)
200      O << ":g" << DestNodePort;
201
202    if (!Attrs.empty())
203      O << "[" << Attrs << "]";
204    O << ";\n";
205  }
206};
207
208template<typename GraphType>
209std::ostream &WriteGraph(std::ostream &O, const GraphType &G,
210                         const std::string &Name = "") {
211  // Start the graph emission process...
212  GraphWriter<GraphType> W(O, G);
213
214  // Output the header for the graph...
215  W.writeHeader(Name);
216
217  // Emit all of the nodes in the graph...
218  W.writeNodes();
219
220  // Output any customizations on the graph
221  DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
222
223  // Output the end of the graph
224  W.writeFooter();
225  return O;
226}
227
228} // End llvm namespace
229
230#endif
231