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