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