LLVM 22.0.0git
GraphWriter.h
Go to the documentation of this file.
1//===- llvm/Support/GraphWriter.h - Write graph to a .dot file --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a simple interface that can be used to print out generic
10// LLVM graphs to ".dot" files. "dot" is a tool that is part of the AT&T
11// graphviz package (http://www.research.att.com/sw/tools/graphviz/) which can
12// be used to turn the files output by this interface into a variety of
13// different graphics formats.
14//
15// Graphs do not need to implement any interface past what is already required
16// by the GraphTraits template, but they can choose to implement specializations
17// of the DOTGraphTraits template if they want to customize the graphs output in
18// any way.
19//
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_SUPPORT_GRAPHWRITER_H
23#define LLVM_SUPPORT_GRAPHWRITER_H
24
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/Twine.h"
32#include <iterator>
33#include <string>
34#include <type_traits>
35#include <vector>
36
37namespace llvm {
38
39namespace DOT { // Private functions...
40
41LLVM_ABI std::string EscapeString(const std::string &Label);
42
43/// Get a color string for this node number. Simply round-robin selects
44/// from a reasonable number of colors.
45LLVM_ABI StringRef getColorString(unsigned NodeNumber);
46
47} // end namespace DOT
48
49namespace GraphProgram {
50
51enum Name {
56 CIRCO
57};
58
59} // end namespace GraphProgram
60
61LLVM_ABI bool DisplayGraph(StringRef Filename, bool wait = true,
63
64template <typename GraphType, typename Derived> class GraphWriterBase {
65protected:
67 const GraphType &G;
68 bool RenderUsingHTML = false;
69
72 using NodeRef = typename GTraits::NodeRef;
73 using node_iterator = typename GTraits::nodes_iterator;
74 using child_iterator = typename GTraits::ChildIteratorType;
76
77 static_assert(std::is_pointer_v<NodeRef>,
78 "FIXME: Currently GraphWriterBase requires the NodeRef type to "
79 "be a pointer.\nThe pointer usage should be moved to "
80 "DOTGraphTraits, and removed from GraphWriterBase itself.");
81
82 // Cast the 'this' pointer to the derived type and return a reference.
83 Derived &getDerived() { return *static_cast<Derived *>(this); }
84 const Derived &getDerived() const {
85 return *static_cast<const Derived *>(this);
86 }
87
88 // Writes the edge labels of the node to O and returns true if there are any
89 // edge labels not equal to the empty string "".
91 child_iterator EI = GTraits::child_begin(Node);
92 child_iterator EE = GTraits::child_end(Node);
93 bool hasEdgeSourceLabels = false;
94
96 O << "</tr><tr>";
97
98 for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
99 std::string label = DTraits.getEdgeSourceLabel(Node, EI);
100
101 if (label.empty())
102 continue;
103
104 hasEdgeSourceLabels = true;
105
106 if (RenderUsingHTML)
107 O << "<td colspan=\"1\" port=\"s" << i << "\">" << label << "</td>";
108 else {
109 if (i)
110 O << "|";
111
112 O << "<s" << i << ">" << DOT::EscapeString(label);
113 }
114 }
115
116 if (EI != EE && hasEdgeSourceLabels) {
117 if (RenderUsingHTML)
118 O << "<td colspan=\"1\" port=\"s64\">truncated...</td>";
119 else
120 O << "|<s64>truncated...";
121 }
122
123 return hasEdgeSourceLabels;
124 }
125
126public:
127 GraphWriterBase(raw_ostream &o, const GraphType &g, bool SN) : O(o), G(g) {
128 DTraits = DOTTraits(SN);
130 }
131 virtual ~GraphWriterBase() {}
132
133 void writeGraph(const std::string &Title = "") {
134 // Output the header for the graph...
135 getDerived().writeHeader(Title);
136
137 // Emit all of the nodes in the graph...
138 getDerived().writeNodes();
139
140 // Output any customizations on the graph
142
143 // Output the end of the graph
144 getDerived().writeFooter();
145 }
146
147 void writeHeader(const std::string &Title) {
148 std::string GraphName(DTraits.getGraphName(G));
149
150 if (!Title.empty())
151 O << "digraph \"" << DOT::EscapeString(Title) << "\" {\n";
152 else if (!GraphName.empty())
153 O << "digraph \"" << DOT::EscapeString(GraphName) << "\" {\n";
154 else
155 O << "digraph unnamed {\n";
156
158 O << "\trankdir=\"BT\";\n";
159
160 if (!Title.empty())
161 O << "\tlabel=\"" << DOT::EscapeString(Title) << "\";\n";
162 else if (!GraphName.empty())
163 O << "\tlabel=\"" << DOT::EscapeString(GraphName) << "\";\n";
165 O << "\n";
166 }
167
168 void writeFooter() {
169 // Finish off the graph
170 O << "}\n";
171 }
172
173 void writeNodes() {
174 // Loop over the graph, printing it out...
175 for (const auto Node : nodes<GraphType>(G))
177 getDerived().writeNode(Node);
178 }
179
181
183 std::string NodeAttributes = DTraits.getNodeAttributes(Node, G);
184
185 O << "\tNode" << static_cast<const void *>(Node) << " [shape=";
186 if (RenderUsingHTML)
187 O << "none,";
188 else
189 O << "record,";
190
191 if (!NodeAttributes.empty()) O << NodeAttributes << ",";
192 O << "label=";
193
194 if (RenderUsingHTML) {
195 // Count the numbewr of edges out of the node to determine how
196 // many columns to span (max 64)
197 unsigned ColSpan = 0;
198 child_iterator EI = GTraits::child_begin(Node);
199 child_iterator EE = GTraits::child_end(Node);
200 for (; EI != EE && ColSpan != 64; ++EI, ++ColSpan)
201 ;
202 if (ColSpan == 0)
203 ColSpan = 1;
204 // Include truncated messages when counting.
205 if (EI != EE)
206 ++ColSpan;
207 O << "<<table border=\"0\" cellborder=\"1\" cellspacing=\"0\""
208 << " cellpadding=\"0\"><tr><td align=\"text\" colspan=\"" << ColSpan
209 << "\">";
210 } else {
211 O << "\"{";
212 }
213
215 if (RenderUsingHTML)
216 O << DTraits.getNodeLabel(Node, G) << "</td>";
217 else
219
220 // If we should include the address of the node in the label, do so now.
221 std::string Id = DTraits.getNodeIdentifierLabel(Node, G);
222 if (!Id.empty())
223 O << "|" << DOT::EscapeString(Id);
224
225 std::string NodeDesc = DTraits.getNodeDescription(Node, G);
226 if (!NodeDesc.empty())
227 O << "|" << DOT::EscapeString(NodeDesc);
228 }
229
230 std::string edgeSourceLabels;
231 raw_string_ostream EdgeSourceLabels(edgeSourceLabels);
232 bool hasEdgeSourceLabels = getEdgeSourceLabels(EdgeSourceLabels, Node);
233
234 if (hasEdgeSourceLabels) {
236 if (!RenderUsingHTML)
237 O << "|";
238
239 if (RenderUsingHTML)
240 O << edgeSourceLabels;
241 else
242 O << "{" << edgeSourceLabels << "}";
243
245 if (!RenderUsingHTML)
246 O << "|";
247 }
248
250 if (RenderUsingHTML)
252 else
254
255 // If we should include the address of the node in the label, do so now.
256 std::string Id = DTraits.getNodeIdentifierLabel(Node, G);
257 if (!Id.empty())
258 O << "|" << DOT::EscapeString(Id);
259
260 std::string NodeDesc = DTraits.getNodeDescription(Node, G);
261 if (!NodeDesc.empty())
262 O << "|" << DOT::EscapeString(NodeDesc);
263 }
264
266 O << "|{";
267
268 unsigned i = 0, e = DTraits.numEdgeDestLabels(Node);
269 for (; i != e && i != 64; ++i) {
270 if (i) O << "|";
271 O << "<d" << i << ">"
273 }
274
275 if (i != e)
276 O << "|<d64>truncated...";
277 O << "}";
278 }
279
280 if (RenderUsingHTML)
281 O << "</tr></table>>";
282 else
283 O << "}\"";
284 O << "];\n"; // Finish printing the "node" line
285
286 // Output all of the edges now
287 child_iterator EI = GTraits::child_begin(Node);
288 child_iterator EE = GTraits::child_end(Node);
289 for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
290 if (!DTraits.isNodeHidden(*EI, G))
291 writeEdge(Node, i, EI);
292 for (; EI != EE; ++EI)
293 if (!DTraits.isNodeHidden(*EI, G))
294 writeEdge(Node, 64, EI);
295 }
296
297 void writeEdge(NodeRef Node, unsigned edgeidx, child_iterator EI) {
298 if (NodeRef TargetNode = *EI) {
299 int DestPort = -1;
302
303 // Figure out which edge this targets...
304 unsigned Offset =
305 (unsigned)std::distance(GTraits::child_begin(TargetNode), TargetIt);
306 DestPort = static_cast<int>(Offset);
307 }
308
309 if (DTraits.getEdgeSourceLabel(Node, EI).empty())
310 edgeidx = -1;
311
312 getDerived().emitEdge(static_cast<const void *>(Node), edgeidx,
313 static_cast<const void *>(TargetNode), DestPort,
315 }
316 }
317
318 /// emitSimpleNode - Outputs a simple (non-record) node
319 void emitSimpleNode(const void *ID, const std::string &Attr,
320 const std::string &Label, unsigned NumEdgeSources = 0,
321 const std::vector<std::string> *EdgeSourceLabels = nullptr) {
322 O << "\tNode" << ID << "[ ";
323 if (!Attr.empty())
324 O << Attr << ",";
325 O << " label =\"";
326 if (NumEdgeSources) O << "{";
327 O << DOT::EscapeString(Label);
328 if (NumEdgeSources) {
329 O << "|{";
330
331 for (unsigned i = 0; i != NumEdgeSources; ++i) {
332 if (i) O << "|";
333 O << "<s" << i << ">";
334 if (EdgeSourceLabels) O << DOT::EscapeString((*EdgeSourceLabels)[i]);
335 }
336 O << "}}";
337 }
338 O << "\"];\n";
339 }
340
341 /// emitEdge - Output an edge from a simple node into the graph...
342 void emitEdge(const void *SrcNodeID, int SrcNodePort,
343 const void *DestNodeID, int DestNodePort,
344 const std::string &Attrs) {
345 if (SrcNodePort > 64) return; // Eminating from truncated part?
346 if (DestNodePort > 64) DestNodePort = 64; // Targeting the truncated part?
347
348 O << "\tNode" << SrcNodeID;
349 if (SrcNodePort >= 0)
350 O << ":s" << SrcNodePort;
351 O << " -> Node" << DestNodeID;
352 if (DestNodePort >= 0 && DTraits.hasEdgeDestLabels())
353 O << ":d" << DestNodePort;
354
355 if (!Attrs.empty())
356 O << "[" << Attrs << "]";
357 O << ";\n";
358 }
359
360 /// getOStream - Get the raw output stream into the graph file. Useful to
361 /// write fancy things using addCustomGraphFeatures().
363 return O;
364 }
365};
366
367template <typename GraphType>
368class GraphWriter : public GraphWriterBase<GraphType, GraphWriter<GraphType>> {
369public:
370 GraphWriter(raw_ostream &o, const GraphType &g, bool SN)
371 : GraphWriterBase<GraphType, GraphWriter<GraphType>>(o, g, SN) {}
372 ~GraphWriter() override {}
373};
374
375template <typename GraphType>
376raw_ostream &WriteGraph(raw_ostream &O, const GraphType &G,
377 bool ShortNames = false, const Twine &Title = "") {
378 // Start the graph emission process...
379 GraphWriter<GraphType> W(O, G, ShortNames);
380
381 // Emit the graph.
382 W.writeGraph(Title.str());
383
384 return O;
385}
386
387LLVM_ABI std::string createGraphFilename(const Twine &Name, int &FD);
388
389/// Writes graph into a provided @c Filename.
390/// If @c Filename is empty, generates a random one.
391/// \return The resulting filename, or an empty string if writing
392/// failed.
393template <typename GraphType>
394std::string WriteGraph(const GraphType &G, const Twine &Name,
395 bool ShortNames = false,
396 const Twine &Title = "",
397 std::string Filename = "") {
398 int FD;
399 if (Filename.empty()) {
400 Filename = createGraphFilename(Name.str(), FD);
401 } else {
402 std::error_code EC = sys::fs::openFileForWrite(
404
405 // Writing over an existing file is not considered an error.
406 if (EC == std::errc::file_exists) {
407 errs() << "file exists, overwriting" << "\n";
408 } else if (EC) {
409 errs() << "error writing into file" << "\n";
410 return "";
411 } else {
412 errs() << "writing to the newly created file " << Filename << "\n";
413 }
414 }
415 raw_fd_ostream O(FD, /*shouldClose=*/ true);
416
417 if (FD == -1) {
418 errs() << "error opening file '" << Filename << "' for writing!\n";
419 return "";
420 }
421
422 llvm::WriteGraph(O, G, ShortNames, Title);
423 errs() << " done. \n";
424
425 return Filename;
426}
427
428/// DumpDotGraph - Just dump a dot graph to the user-provided file name.
429#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
430template <typename GraphType>
432dumpDotGraphToFile(const GraphType &G, const Twine &FileName,
433 const Twine &Title, bool ShortNames = false,
434 const Twine &Name = "") {
435 llvm::WriteGraph(G, Name, ShortNames, Title, FileName.str());
436}
437#endif
438
439/// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
440/// then cleanup. For use from the debugger.
441///
442template<typename GraphType>
443void ViewGraph(const GraphType &G, const Twine &Name,
444 bool ShortNames = false, const Twine &Title = "",
446 std::string Filename = llvm::WriteGraph(G, Name, ShortNames, Title);
447
448 if (Filename.empty())
449 return;
450
451 DisplayGraph(Filename, false, Program);
452}
453
454} // end namespace llvm
455
456#endif // LLVM_SUPPORT_GRAPHWRITER_H
#define LLVM_ABI
Definition: Compiler.h:213
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:638
std::string Name
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
#define G(x, y, z)
Definition: MD5.cpp:56
INLINE void g(uint32_t *state, size_t a, size_t b, size_t c, size_t d, uint32_t x, uint32_t y)
void writeEdge(NodeRef Node, unsigned edgeidx, child_iterator EI)
Definition: GraphWriter.h:297
typename GTraits::ChildIteratorType child_iterator
Definition: GraphWriter.h:74
bool getEdgeSourceLabels(raw_ostream &O, NodeRef Node)
Definition: GraphWriter.h:90
const Derived & getDerived() const
Definition: GraphWriter.h:84
raw_ostream & O
Definition: GraphWriter.h:66
bool isNodeHidden(NodeRef Node)
Definition: GraphWriter.h:180
void writeHeader(const std::string &Title)
Definition: GraphWriter.h:147
typename GTraits::NodeRef NodeRef
Definition: GraphWriter.h:72
void writeGraph(const std::string &Title="")
Definition: GraphWriter.h:133
void writeNode(NodeRef Node)
Definition: GraphWriter.h:182
GraphWriterBase(raw_ostream &o, const GraphType &g, bool SN)
Definition: GraphWriter.h:127
void emitSimpleNode(const void *ID, const std::string &Attr, const std::string &Label, unsigned NumEdgeSources=0, const std::vector< std::string > *EdgeSourceLabels=nullptr)
emitSimpleNode - Outputs a simple (non-record) node
Definition: GraphWriter.h:319
void emitEdge(const void *SrcNodeID, int SrcNodePort, const void *DestNodeID, int DestNodePort, const std::string &Attrs)
emitEdge - Output an edge from a simple node into the graph...
Definition: GraphWriter.h:342
raw_ostream & getOStream()
getOStream - Get the raw output stream into the graph file.
Definition: GraphWriter.h:362
Derived & getDerived()
Definition: GraphWriter.h:83
const GraphType & G
Definition: GraphWriter.h:67
virtual ~GraphWriterBase()
Definition: GraphWriter.h:131
typename GTraits::nodes_iterator node_iterator
Definition: GraphWriter.h:73
DOTGraphTraits< GraphType > DOTTraits
Definition: GraphWriter.h:70
GraphWriter(raw_ostream &o, const GraphType &g, bool SN)
Definition: GraphWriter.h:370
~GraphWriter() override
Definition: GraphWriter.h:372
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:461
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:662
LLVM_ABI std::string EscapeString(const std::string &Label)
Definition: GraphWriter.cpp:56
LLVM_ABI StringRef getColorString(unsigned NodeNumber)
Get a color string for this node number.
Definition: GraphWriter.cpp:91
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:762
@ CD_CreateAlways
CD_CreateAlways - When opening a file:
Definition: FileSystem.h:734
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp=CD_CreateAlways, OpenFlags Flags=OF_None, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
Definition: FileSystem.h:1072
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:477
LLVM_ABI bool DisplayGraph(StringRef Filename, bool wait=true, GraphProgram::Name program=GraphProgram::DOT)
LLVM_DUMP_METHOD void dumpDotGraphToFile(const GraphType &G, const Twine &FileName, const Twine &Title, bool ShortNames=false, const Twine &Name="")
DumpDotGraph - Just dump a dot graph to the user-provided file name.
Definition: GraphWriter.h:432
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
Definition: GraphWriter.h:376
LLVM_ABI std::string createGraphFilename(const Twine &Name, int &FD)
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
Definition: GraphWriter.h:443
static std::string getNodeIdentifierLabel(const void *, const GraphType &)
static bool isNodeHidden(const void *, const GraphType &)
isNodeHidden - If the function returns true, the given node is not displayed in the graph.
static std::string getGraphName(const GraphType &)
getGraphName - Return the label for the graph as a whole.
static EdgeIter getEdgeTarget(const void *, EdgeIter I)
getEdgeTarget - If edgeTargetsEdgeSource returns true, this method is called to determine which outgo...
static std::string getGraphProperties(const GraphType &)
getGraphProperties - Return any custom properties that should be included in the top level graph stru...
static std::string getEdgeAttributes(const void *, EdgeIter, const GraphType &)
If you want to override the dot attributes printed for a particular edge, override this method.
std::string getNodeLabel(const void *, const GraphType &)
getNodeLabel - Given a node and a pointer to the top level graph, return the label to print in the no...
static bool edgeTargetsEdgeSource(const void *, EdgeIter)
edgeTargetsEdgeSource - This method returns true if this outgoing edge should actually target another...
static bool renderGraphFromBottomUp()
renderGraphFromBottomUp - If this function returns true, the graph is emitted bottom-up instead of to...
static std::string getEdgeDestLabel(const void *, unsigned)
getEdgeDestLabel - If hasEdgeDestLabels, this function returns the incoming edge label with the given...
static std::string getEdgeSourceLabel(const void *, EdgeIter)
getEdgeSourceLabel - If you want to label the edge source itself, implement this method.
static bool hasEdgeDestLabels()
hasEdgeDestLabels - If this function returns true, the graph is able to provide labels for edge desti...
static bool renderNodesUsingHTML()
static void addCustomGraphFeatures(const GraphType &, GraphWriter &)
addCustomGraphFeatures - If a graph is made up of more than just straight-forward nodes and edges,...
static std::string getNodeDescription(const void *, const GraphType &)
static std::string getNodeAttributes(const void *, const GraphType &)
If you want to specify custom node attributes, this is the place to do so.
static unsigned numEdgeDestLabels(const void *)
numEdgeDestLabels - If hasEdgeDestLabels, this function returns the number of incoming edge labels th...
typename GraphType::UnknownGraphTypeError NodeRef
Definition: GraphTraits.h:95