add support for -- for symmetry
[oota-llvm.git] / include / Support / GraphWriter.h
1 //===-- Support/GraphWriter.h - Write a 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 SUPPORT_GRAPHWRITER_H
24 #define SUPPORT_GRAPHWRITER_H
25
26 #include "Support/DOTGraphTraits.h"
27 #include "Support/GraphTraits.h"
28 #include <vector>
29 #include <iostream>
30
31 namespace llvm {
32
33 namespace 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
62 template<typename GraphType>
63 class 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;
72 public:
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     std::string GraphName = DOTTraits::getGraphName(G);
82     if (!GraphName.empty())
83       O << "\tlabel=\"" << DOT::EscapeString(GraphName) << "\";\n";
84     O << DOTTraits::getGraphProperties(G);
85     O << "\n";
86   }
87
88   void writeFooter() {
89     // Finish off the graph
90     O << "}\n";
91   }
92
93   void writeNodes() {
94     // Loop over the graph, printing it out...
95     for (node_iterator I = GTraits::nodes_begin(G), E = GTraits::nodes_end(G);
96          I != E; ++I)
97       writeNode(&*I);
98   }
99
100   void writeNode(NodeType *Node) {
101     std::string NodeAttributes = DOTTraits::getNodeAttributes(Node);
102       
103     O << "\tNode" << reinterpret_cast<const void*>(Node) << " [shape=record,";
104     if (!NodeAttributes.empty()) O << NodeAttributes << ",";
105     O << "label=\"{"
106       << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
107     
108     // Print out the fields of the current node...
109     child_iterator EI = GTraits::child_begin(Node);
110     child_iterator EE = GTraits::child_end(Node);
111     if (EI != EE) {
112       O << "|{";
113       
114       for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
115         if (i) O << "|";
116         O << "<g" << i << ">" << DOTTraits::getEdgeSourceLabel(Node, EI);
117       }
118       
119       if (EI != EE)
120         O << "|truncated...";
121       O << "}";
122     }
123     O << "}\"];\n";   // Finish printing the "node" line
124     
125     // Output all of the edges now
126     EI = GTraits::child_begin(Node);
127     for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
128       writeEdge(Node, i, EI);
129   }
130
131   void writeEdge(NodeType *Node, unsigned edgeidx, child_iterator EI) {
132     if (NodeType *TargetNode = *EI) {
133       int DestPort = -1;
134       if (DOTTraits::edgeTargetsEdgeSource(Node, EI)) {
135         child_iterator TargetIt = DOTTraits::getEdgeTarget(Node, EI);
136
137         // Figure out which edge this targets...
138         unsigned Offset = std::distance(GTraits::child_begin(TargetNode),
139                                         TargetIt);
140         DestPort = static_cast<int>(Offset);
141       }
142
143       emitEdge(reinterpret_cast<const void*>(Node), edgeidx,
144                reinterpret_cast<const void*>(TargetNode), DestPort,
145                DOTTraits::getEdgeAttributes(Node, EI));
146     }
147   }
148
149   /// emitSimpleNode - Outputs a simple (non-record) node
150   void emitSimpleNode(const void *ID, const std::string &Attr,
151                       const std::string &Label, unsigned NumEdgeSources = 0,
152                       const std::vector<std::string> *EdgeSourceLabels = 0) {
153     O << "\tNode" << ID << "[ ";
154     if (!Attr.empty())
155       O << Attr << ",";
156     O << " label =\"";
157     if (NumEdgeSources) O << "{";
158     O << DOT::EscapeString(Label);
159     if (NumEdgeSources) {
160       O << "|{";
161       
162       for (unsigned i = 0; i != NumEdgeSources; ++i) {
163         if (i) O << "|";
164         O << "<g" << i << ">";
165         if (EdgeSourceLabels) O << (*EdgeSourceLabels)[i];
166       }
167       O << "}}";
168     }
169     O << "\"];\n";
170   }
171
172   /// emitEdge - Output an edge from a simple node into the graph...
173   void emitEdge(const void *SrcNodeID, int SrcNodePort,
174                 const void *DestNodeID, int DestNodePort,
175                 const std::string &Attrs) {
176     if (SrcNodePort  > 64) return;             // Eminating from truncated part?
177     if (DestNodePort > 64) DestNodePort = 64;  // Targetting the truncated part?
178
179     O << "\tNode" << SrcNodeID;
180     if (SrcNodePort >= 0)
181       O << ":g" << SrcNodePort;
182     O << " -> Node" << reinterpret_cast<const void*>(DestNodeID);
183     if (DestNodePort >= 0)
184       O << ":g" << DestNodePort;    
185
186     if (!Attrs.empty())
187       O << "[" << Attrs << "]";
188     O << ";\n";
189   }
190 };
191
192 template<typename GraphType>
193 std::ostream &WriteGraph(std::ostream &O, const GraphType &G,
194                          const std::string &Name = "") {
195   // Start the graph emission process...
196   GraphWriter<GraphType> W(O, G);
197
198   // Output the header for the graph...
199   W.writeHeader(Name);
200
201   // Emit all of the nodes in the graph...
202   W.writeNodes();
203
204   // Output any customizations on the graph
205   DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
206
207   // Output the end of the graph
208   W.writeFooter();
209   return O;
210 }
211
212 } // End llvm namespace
213
214 #endif