LLVM  14.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 
25 #include "llvm/ADT/GraphTraits.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Twine.h"
31 #include <algorithm>
32 #include <cstddef>
33 #include <iterator>
34 #include <string>
35 #include <type_traits>
36 #include <vector>
37 
38 namespace llvm {
39 
40 namespace DOT { // Private functions...
41 
42 std::string EscapeString(const std::string &Label);
43 
44 /// Get a color string for this node number. Simply round-robin selects
45 /// from a reasonable number of colors.
46 StringRef getColorString(unsigned NodeNumber);
47 
48 } // end namespace DOT
49 
50 namespace GraphProgram {
51 
52 enum Name {
53  DOT,
54  FDP,
58 };
59 
60 } // end namespace GraphProgram
61 
62 bool DisplayGraph(StringRef Filename, bool wait = true,
64 
65 template<typename GraphType>
66 class GraphWriter {
67  raw_ostream &O;
68  const GraphType &G;
69  bool RenderUsingHTML = false;
70 
71  using DOTTraits = DOTGraphTraits<GraphType>;
72  using GTraits = GraphTraits<GraphType>;
73  using NodeRef = typename GTraits::NodeRef;
74  using node_iterator = typename GTraits::nodes_iterator;
75  using child_iterator = typename GTraits::ChildIteratorType;
76  DOTTraits DTraits;
77 
78  static_assert(std::is_pointer<NodeRef>::value,
79  "FIXME: Currently GraphWriter requires the NodeRef type to be "
80  "a pointer.\nThe pointer usage should be moved to "
81  "DOTGraphTraits, and removed from GraphWriter itself.");
82 
83  // Writes the edge labels of the node to O and returns true if there are any
84  // edge labels not equal to the empty string "".
85  bool getEdgeSourceLabels(raw_ostream &O, NodeRef Node) {
86  child_iterator EI = GTraits::child_begin(Node);
87  child_iterator EE = GTraits::child_end(Node);
88  bool hasEdgeSourceLabels = false;
89 
90  if (RenderUsingHTML)
91  O << "</tr><tr>";
92 
93  for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
94  std::string label = DTraits.getEdgeSourceLabel(Node, EI);
95 
96  if (label.empty())
97  continue;
98 
99  hasEdgeSourceLabels = true;
100 
101  if (RenderUsingHTML)
102  O << "<td colspan=\"1\" port=\"s" << i << "\">" << label << "</td>";
103  else {
104  if (i)
105  O << "|";
106 
107  O << "<s" << i << ">" << DOT::EscapeString(label);
108  }
109  }
110 
111  if (EI != EE && hasEdgeSourceLabels) {
112  if (RenderUsingHTML)
113  O << "<td colspan=\"1\" port=\"s64\">truncated...</td>";
114  else
115  O << "|<s64>truncated...";
116  }
117 
118  return hasEdgeSourceLabels;
119  }
120 
121 public:
122  GraphWriter(raw_ostream &o, const GraphType &g, bool SN) : O(o), G(g) {
123  DTraits = DOTTraits(SN);
124  RenderUsingHTML = DTraits.renderNodesUsingHTML();
125  }
126 
127  void writeGraph(const std::string &Title = "") {
128  // Output the header for the graph...
129  writeHeader(Title);
130 
131  // Emit all of the nodes in the graph...
132  writeNodes();
133 
134  // Output any customizations on the graph
136 
137  // Output the end of the graph
138  writeFooter();
139  }
140 
141  void writeHeader(const std::string &Title) {
142  std::string GraphName(DTraits.getGraphName(G));
143 
144  if (!Title.empty())
145  O << "digraph \"" << DOT::EscapeString(Title) << "\" {\n";
146  else if (!GraphName.empty())
147  O << "digraph \"" << DOT::EscapeString(GraphName) << "\" {\n";
148  else
149  O << "digraph unnamed {\n";
150 
151  if (DTraits.renderGraphFromBottomUp())
152  O << "\trankdir=\"BT\";\n";
153 
154  if (!Title.empty())
155  O << "\tlabel=\"" << DOT::EscapeString(Title) << "\";\n";
156  else if (!GraphName.empty())
157  O << "\tlabel=\"" << DOT::EscapeString(GraphName) << "\";\n";
158  O << DTraits.getGraphProperties(G);
159  O << "\n";
160  }
161 
162  void writeFooter() {
163  // Finish off the graph
164  O << "}\n";
165  }
166 
167  void writeNodes() {
168  // Loop over the graph, printing it out...
169  for (const auto Node : nodes<GraphType>(G))
170  if (!isNodeHidden(Node))
171  writeNode(Node);
172  }
173 
174  bool isNodeHidden(NodeRef Node) { return DTraits.isNodeHidden(Node, G); }
175 
176  void writeNode(NodeRef Node) {
177  std::string NodeAttributes = DTraits.getNodeAttributes(Node, G);
178 
179  O << "\tNode" << static_cast<const void *>(Node) << " [shape=";
180  if (RenderUsingHTML)
181  O << "none,";
182  else
183  O << "record,";
184 
185  if (!NodeAttributes.empty()) O << NodeAttributes << ",";
186  O << "label=";
187 
188  if (RenderUsingHTML) {
189  // Count the numbewr of edges out of the node to determine how
190  // many columns to span (max 64)
191  unsigned ColSpan = 0;
192  child_iterator EI = GTraits::child_begin(Node);
193  child_iterator EE = GTraits::child_end(Node);
194  for (; EI != EE && ColSpan != 64; ++EI, ++ColSpan)
195  ;
196  if (ColSpan == 0)
197  ColSpan = 1;
198  // Include truncated messages when counting.
199  if (EI != EE)
200  ++ColSpan;
201  O << "<<table border=\"0\" cellborder=\"1\" cellspacing=\"0\""
202  << " cellpadding=\"0\"><tr><td align=\"text\" colspan=\"" << ColSpan
203  << "\">";
204  } else
205  O << "\"{";
206 
207  if (!DTraits.renderGraphFromBottomUp()) {
208  if (RenderUsingHTML)
209  O << DTraits.getNodeLabel(Node, G) << "</td>";
210  else
211  O << DOT::EscapeString(DTraits.getNodeLabel(Node, G));
212 
213  // If we should include the address of the node in the label, do so now.
214  std::string Id = DTraits.getNodeIdentifierLabel(Node, G);
215  if (!Id.empty())
216  O << "|" << DOT::EscapeString(Id);
217 
218  std::string NodeDesc = DTraits.getNodeDescription(Node, G);
219  if (!NodeDesc.empty())
220  O << "|" << DOT::EscapeString(NodeDesc);
221  }
222 
223  std::string edgeSourceLabels;
224  raw_string_ostream EdgeSourceLabels(edgeSourceLabels);
225  bool hasEdgeSourceLabels = getEdgeSourceLabels(EdgeSourceLabels, Node);
226 
227  if (hasEdgeSourceLabels) {
228  if (!DTraits.renderGraphFromBottomUp())
229  if (!RenderUsingHTML)
230  O << "|";
231 
232  if (RenderUsingHTML)
233  O << EdgeSourceLabels.str();
234  else
235  O << "{" << EdgeSourceLabels.str() << "}";
236 
237  if (DTraits.renderGraphFromBottomUp())
238  if (!RenderUsingHTML)
239  O << "|";
240  }
241 
242  if (DTraits.renderGraphFromBottomUp()) {
243  if (RenderUsingHTML)
244  O << DTraits.getNodeLabel(Node, G);
245  else
246  O << DOT::EscapeString(DTraits.getNodeLabel(Node, G));
247 
248  // If we should include the address of the node in the label, do so now.
249  std::string Id = DTraits.getNodeIdentifierLabel(Node, G);
250  if (!Id.empty())
251  O << "|" << DOT::EscapeString(Id);
252 
253  std::string NodeDesc = DTraits.getNodeDescription(Node, G);
254  if (!NodeDesc.empty())
255  O << "|" << DOT::EscapeString(NodeDesc);
256  }
257 
258  if (DTraits.hasEdgeDestLabels()) {
259  O << "|{";
260 
261  unsigned i = 0, e = DTraits.numEdgeDestLabels(Node);
262  for (; i != e && i != 64; ++i) {
263  if (i) O << "|";
264  O << "<d" << i << ">"
265  << DOT::EscapeString(DTraits.getEdgeDestLabel(Node, i));
266  }
267 
268  if (i != e)
269  O << "|<d64>truncated...";
270  O << "}";
271  }
272 
273  if (RenderUsingHTML)
274  O << "</tr></table>>";
275  else
276  O << "}\"";
277  O << "];\n"; // Finish printing the "node" line
278 
279  // Output all of the edges now
280  child_iterator EI = GTraits::child_begin(Node);
281  child_iterator EE = GTraits::child_end(Node);
282  for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
283  if (!DTraits.isNodeHidden(*EI, G))
284  writeEdge(Node, i, EI);
285  for (; EI != EE; ++EI)
286  if (!DTraits.isNodeHidden(*EI, G))
287  writeEdge(Node, 64, EI);
288  }
289 
290  void writeEdge(NodeRef Node, unsigned edgeidx, child_iterator EI) {
291  if (NodeRef TargetNode = *EI) {
292  int DestPort = -1;
293  if (DTraits.edgeTargetsEdgeSource(Node, EI)) {
294  child_iterator TargetIt = DTraits.getEdgeTarget(Node, EI);
295 
296  // Figure out which edge this targets...
297  unsigned Offset =
298  (unsigned)std::distance(GTraits::child_begin(TargetNode), TargetIt);
299  DestPort = static_cast<int>(Offset);
300  }
301 
302  if (DTraits.getEdgeSourceLabel(Node, EI).empty())
303  edgeidx = -1;
304 
305  emitEdge(static_cast<const void*>(Node), edgeidx,
306  static_cast<const void*>(TargetNode), DestPort,
307  DTraits.getEdgeAttributes(Node, EI, G));
308  }
309  }
310 
311  /// emitSimpleNode - Outputs a simple (non-record) node
312  void emitSimpleNode(const void *ID, const std::string &Attr,
313  const std::string &Label, unsigned NumEdgeSources = 0,
314  const std::vector<std::string> *EdgeSourceLabels = nullptr) {
315  O << "\tNode" << ID << "[ ";
316  if (!Attr.empty())
317  O << Attr << ",";
318  O << " label =\"";
319  if (NumEdgeSources) O << "{";
320  O << DOT::EscapeString(Label);
321  if (NumEdgeSources) {
322  O << "|{";
323 
324  for (unsigned i = 0; i != NumEdgeSources; ++i) {
325  if (i) O << "|";
326  O << "<s" << i << ">";
327  if (EdgeSourceLabels) O << DOT::EscapeString((*EdgeSourceLabels)[i]);
328  }
329  O << "}}";
330  }
331  O << "\"];\n";
332  }
333 
334  /// emitEdge - Output an edge from a simple node into the graph...
335  void emitEdge(const void *SrcNodeID, int SrcNodePort,
336  const void *DestNodeID, int DestNodePort,
337  const std::string &Attrs) {
338  if (SrcNodePort > 64) return; // Eminating from truncated part?
339  if (DestNodePort > 64) DestNodePort = 64; // Targeting the truncated part?
340 
341  O << "\tNode" << SrcNodeID;
342  if (SrcNodePort >= 0)
343  O << ":s" << SrcNodePort;
344  O << " -> Node" << DestNodeID;
345  if (DestNodePort >= 0 && DTraits.hasEdgeDestLabels())
346  O << ":d" << DestNodePort;
347 
348  if (!Attrs.empty())
349  O << "[" << Attrs << "]";
350  O << ";\n";
351  }
352 
353  /// getOStream - Get the raw output stream into the graph file. Useful to
354  /// write fancy things using addCustomGraphFeatures().
356  return O;
357  }
358 };
359 
360 template<typename GraphType>
361 raw_ostream &WriteGraph(raw_ostream &O, const GraphType &G,
362  bool ShortNames = false,
363  const Twine &Title = "") {
364  // Start the graph emission process...
365  GraphWriter<GraphType> W(O, G, ShortNames);
366 
367  // Emit the graph.
368  W.writeGraph(Title.str());
369 
370  return O;
371 }
372 
373 std::string createGraphFilename(const Twine &Name, int &FD);
374 
375 /// Writes graph into a provided @c Filename.
376 /// If @c Filename is empty, generates a random one.
377 /// \return The resulting filename, or an empty string if writing
378 /// failed.
379 template <typename GraphType>
380 std::string WriteGraph(const GraphType &G, const Twine &Name,
381  bool ShortNames = false,
382  const Twine &Title = "",
383  std::string Filename = "") {
384  int FD;
385  if (Filename.empty()) {
386  Filename = createGraphFilename(Name.str(), FD);
387  } else {
388  std::error_code EC = sys::fs::openFileForWrite(
390 
391  // Writing over an existing file is not considered an error.
392  if (EC == std::errc::file_exists) {
393  errs() << "file exists, overwriting" << "\n";
394  } else if (EC) {
395  errs() << "error writing into file" << "\n";
396  return "";
397  } else {
398  errs() << "writing to the newly created file " << Filename << "\n";
399  }
400  }
401  raw_fd_ostream O(FD, /*shouldClose=*/ true);
402 
403  if (FD == -1) {
404  errs() << "error opening file '" << Filename << "' for writing!\n";
405  return "";
406  }
407 
408  llvm::WriteGraph(O, G, ShortNames, Title);
409  errs() << " done. \n";
410 
411  return Filename;
412 }
413 
414 /// DumpDotGraph - Just dump a dot graph to the user-provided file name.
415 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
416 template <typename GraphType>
417 LLVM_DUMP_METHOD void
418 dumpDotGraphToFile(const GraphType &G, const Twine &FileName,
419  const Twine &Title, bool ShortNames = false,
420  const Twine &Name = "") {
421  llvm::WriteGraph(G, Name, ShortNames, Title, FileName.str());
422 }
423 #endif
424 
425 /// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
426 /// then cleanup. For use from the debugger.
427 ///
428 template<typename GraphType>
429 void ViewGraph(const GraphType &G, const Twine &Name,
430  bool ShortNames = false, const Twine &Title = "",
432  std::string Filename = llvm::WriteGraph(G, Name, ShortNames, Title);
433 
434  if (Filename.empty())
435  return;
436 
437  DisplayGraph(Filename, false, Program);
438 }
439 
440 } // end namespace llvm
441 
442 #endif // LLVM_SUPPORT_GRAPHWRITER_H
i
i
Definition: README.txt:29
llvm::GraphProgram::TWOPI
@ TWOPI
Definition: GraphWriter.h:56
llvm::sys::fs::openFileForWrite
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:1065
Attrs
Function Attrs
Definition: README_ALTIVEC.txt:215
LLVM_DUMP_METHOD
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:510
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
llvm::GraphWriter
Definition: ScheduleDAG.h:34
FileSystem.h
StringRef.h
llvm::createGraphFilename
std::string createGraphFilename(const Twine &Name, int &FD)
Definition: GraphWriter.cpp:109
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:631
llvm::RISCVFenceField::W
@ W
Definition: RISCVBaseInfo.h:208
llvm::GraphWriter::isNodeHidden
bool isNodeHidden(NodeRef Node)
Definition: GraphWriter.h:174
llvm::DOT::EscapeString
std::string EscapeString(const std::string &Label)
Definition: GraphWriter.cpp:52
llvm::GraphProgram::CIRCO
@ CIRCO
Definition: GraphWriter.h:57
llvm::GraphWriter::writeHeader
void writeHeader(const std::string &Title)
Definition: GraphWriter.h:141
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:80
llvm::errs
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Definition: raw_ostream.cpp:894
llvm::GraphWriter::getOStream
raw_ostream & getOStream()
getOStream - Get the raw output stream into the graph file.
Definition: GraphWriter.h:355
g
should just be implemented with a CLZ instruction Since there are other e g
Definition: README.txt:709
llvm::ViewGraph
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:429
llvm::GraphWriter::writeFooter
void writeFooter()
Definition: GraphWriter.h:162
GraphTraits.h
llvm::DOT::getColorString
StringRef getColorString(unsigned NodeNumber)
Get a color string for this node number.
Definition: GraphWriter.cpp:87
llvm::GraphWriter::writeGraph
void writeGraph(const std::string &Title="")
Definition: GraphWriter.h:127
Twine.h
llvm::GraphProgram::DOT
@ DOT
Definition: GraphWriter.h:53
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::GraphWriter::writeEdge
void writeEdge(NodeRef Node, unsigned edgeidx, child_iterator EI)
Definition: GraphWriter.h:290
llvm::DOTGraphTraits< GraphType >
llvm::Twine::str
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
G
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
llvm::RISCVFenceField::O
@ O
Definition: RISCVBaseInfo.h:206
llvm::sys::fs::OF_Text
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:761
llvm::GraphProgram::FDP
@ FDP
Definition: GraphWriter.h:54
llvm::dumpDotGraphToFile
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:418
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:57
llvm::DisplayGraph
bool DisplayGraph(StringRef Filename, bool wait=true, GraphProgram::Name program=GraphProgram::DOT)
Definition: GraphWriter.cpp:187
G
#define G(x, y, z)
Definition: MD5.cpp:56
llvm::DefaultDOTGraphTraits::addCustomGraphFeatures
static void addCustomGraphFeatures(const GraphType &, GraphWriter &)
addCustomGraphFeatures - If a graph is made up of more than just straight-forward nodes and edges,...
Definition: DOTGraphTraits.h:157
llvm::WriteGraph
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
Definition: GraphWriter.h:361
llvm::sys::fs::CD_CreateAlways
@ CD_CreateAlways
CD_CreateAlways - When opening a file:
Definition: FileSystem.h:733
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
Node
Definition: ItaniumDemangle.h:235
llvm::raw_fd_ostream
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:443
llvm::GraphWriter::emitSimpleNode
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:312
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:83
llvm::GraphWriter::GraphWriter
GraphWriter(raw_ostream &o, const GraphType &g, bool SN)
Definition: GraphWriter.h:122
llvm::GraphProgram::Name
Name
Definition: GraphWriter.h:52
DOTGraphTraits.h
llvm::GraphWriter::writeNodes
void writeNodes()
Definition: GraphWriter.h:167
llvm::GraphProgram::NEATO
@ NEATO
Definition: GraphWriter.h:55
llvm::GraphTraits::NodeRef
typename GraphType::UnknownGraphTypeError NodeRef
Definition: GraphTraits.h:78
raw_ostream.h
llvm::AMDGPU::VGPRIndexMode::Id
Id
Definition: SIDefines.h:232
llvm::raw_string_ostream::str
std::string & str()
Returns the string's reference.
Definition: raw_ostream.h:649
llvm::GraphWriter::emitEdge
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:335
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:38
llvm::GraphWriter::writeNode
void writeNode(NodeRef Node)
Definition: GraphWriter.h:176