1 //===- GraphWriter.cpp - Implements GraphWriter support routines ----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements misc. GraphWriter support routines.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Support/GraphWriter.h"
15 #include "DebugOptions.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/ErrorOr.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/Program.h"
27 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/CommandLine.h"
34 #include <system_error>
41 struct CreateViewBackground
{
43 return new cl::opt
<bool>("view-background", cl::Hidden
,
44 cl::desc("Execute graph viewer in the background. "
45 "Creates tmp file litter."));
49 static ManagedStatic
<cl::opt
<bool>, CreateViewBackground
> ViewBackground
;
50 void llvm::initGraphWriterOptions() { *ViewBackground
; }
52 void llvm::initGraphWriterOptions() {}
55 std::string
llvm::DOT::EscapeString(const std::string
&Label
) {
56 std::string
Str(Label
);
57 for (unsigned i
= 0; i
!= Str
.length(); ++i
)
60 Str
.insert(Str
.begin()+i
, '\\'); // Escape character...
65 Str
.insert(Str
.begin()+i
, ' '); // Convert to two spaces
70 if (i
+1 != Str
.length())
72 case 'l': continue; // don't disturb \l
73 case '|': case '{': case '}':
74 Str
.erase(Str
.begin()+i
); continue;
81 Str
.insert(Str
.begin()+i
, '\\'); // Escape character...
82 ++i
; // don't infinite loop
88 /// Get a color string for this node number. Simply round-robin selects
89 /// from a reasonable number of colors.
90 StringRef
llvm::DOT::getColorString(unsigned ColorNumber
) {
91 static const int NumColors
= 20;
92 static const char* Colors
[NumColors
] = {
93 "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa",
94 "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff",
95 "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"};
96 return Colors
[ColorNumber
% NumColors
];
99 static std::string
replaceIllegalFilenameChars(std::string Filename
,
100 const char ReplacementChar
) {
101 std::string IllegalChars
=
102 is_style_windows(sys::path::Style::native
) ? "\\/:?\"<>|" : "/";
104 for (char IllegalChar
: IllegalChars
) {
105 std::replace(Filename
.begin(), Filename
.end(), IllegalChar
,
112 std::string
llvm::createGraphFilename(const Twine
&Name
, int &FD
) {
114 SmallString
<128> Filename
;
116 // Windows can't always handle long paths, so limit the length of the name.
117 std::string N
= Name
.str();
118 N
= N
.substr(0, std::min
<std::size_t>(N
.size(), 140));
120 // Replace illegal characters in graph Filename with '_' if needed
121 std::string CleansedName
= replaceIllegalFilenameChars(N
, '_');
124 sys::fs::createTemporaryFile(CleansedName
, "dot", FD
, Filename
);
126 errs() << "Error: " << EC
.message() << "\n";
130 errs() << "Writing '" << Filename
<< "'... ";
131 return std::string(Filename
);
134 // Execute the graph viewer. Return true if there were errors.
135 static bool ExecGraphViewer(StringRef ExecPath
, std::vector
<StringRef
> &args
,
136 StringRef Filename
, bool wait
,
137 std::string
&ErrMsg
) {
139 if (sys::ExecuteAndWait(ExecPath
, args
, std::nullopt
, {}, 0, 0, &ErrMsg
)) {
140 errs() << "Error: " << ErrMsg
<< "\n";
143 sys::fs::remove(Filename
);
144 errs() << " done. \n";
146 sys::ExecuteNoWait(ExecPath
, args
, std::nullopt
, {}, 0, &ErrMsg
);
147 errs() << "Remember to erase graph file: " << Filename
<< "\n";
154 struct GraphSession
{
155 std::string LogBuffer
;
157 bool TryFindProgram(StringRef Names
, std::string
&ProgramPath
) {
158 raw_string_ostream
Log(LogBuffer
);
159 SmallVector
<StringRef
, 8> parts
;
160 Names
.split(parts
, '|');
161 for (auto Name
: parts
) {
162 if (ErrorOr
<std::string
> P
= sys::findProgramByName(Name
)) {
166 Log
<< " Tried '" << Name
<< "'\n";
172 } // end anonymous namespace
174 static const char *getProgramName(GraphProgram::Name program
) {
176 case GraphProgram::DOT
:
178 case GraphProgram::FDP
:
180 case GraphProgram::NEATO
:
182 case GraphProgram::TWOPI
:
184 case GraphProgram::CIRCO
:
187 llvm_unreachable("bad kind");
190 bool llvm::DisplayGraph(StringRef FilenameRef
, bool wait
,
191 GraphProgram::Name program
) {
192 std::string Filename
= std::string(FilenameRef
);
194 std::string ViewerPath
;
198 wait
&= !*ViewBackground
;
199 if (S
.TryFindProgram("open", ViewerPath
)) {
200 std::vector
<StringRef
> args
;
201 args
.push_back(ViewerPath
);
203 args
.push_back("-W");
204 args
.push_back(Filename
);
205 errs() << "Trying 'open' program... ";
206 if (!ExecGraphViewer(ViewerPath
, args
, Filename
, wait
, ErrMsg
))
210 if (S
.TryFindProgram("xdg-open", ViewerPath
)) {
211 std::vector
<StringRef
> args
;
212 args
.push_back(ViewerPath
);
213 args
.push_back(Filename
);
214 errs() << "Trying 'xdg-open' program... ";
215 if (!ExecGraphViewer(ViewerPath
, args
, Filename
, wait
, ErrMsg
))
220 if (S
.TryFindProgram("Graphviz", ViewerPath
)) {
221 std::vector
<StringRef
> args
;
222 args
.push_back(ViewerPath
);
223 args
.push_back(Filename
);
225 errs() << "Running 'Graphviz' program... ";
226 return ExecGraphViewer(ViewerPath
, args
, Filename
, wait
, ErrMsg
);
230 if (S
.TryFindProgram("xdot|xdot.py", ViewerPath
)) {
231 std::vector
<StringRef
> args
;
232 args
.push_back(ViewerPath
);
233 args
.push_back(Filename
);
235 args
.push_back("-f");
236 args
.push_back(getProgramName(program
));
238 errs() << "Running 'xdot.py' program... ";
239 return ExecGraphViewer(ViewerPath
, args
, Filename
, wait
, ErrMsg
);
249 ViewerKind Viewer
= VK_None
;
251 if (!Viewer
&& S
.TryFindProgram("open", ViewerPath
))
254 if (!Viewer
&& S
.TryFindProgram("gv", ViewerPath
))
255 Viewer
= VK_Ghostview
;
256 if (!Viewer
&& S
.TryFindProgram("xdg-open", ViewerPath
))
259 if (!Viewer
&& S
.TryFindProgram("cmd", ViewerPath
)) {
260 Viewer
= VK_CmdStart
;
264 // PostScript or PDF graph generator + PostScript/PDF viewer
265 std::string GeneratorPath
;
267 (S
.TryFindProgram(getProgramName(program
), GeneratorPath
) ||
268 S
.TryFindProgram("dot|fdp|neato|twopi|circo", GeneratorPath
))) {
269 std::string OutputFilename
=
270 Filename
+ (Viewer
== VK_CmdStart
? ".pdf" : ".ps");
272 std::vector
<StringRef
> args
;
273 args
.push_back(GeneratorPath
);
274 if (Viewer
== VK_CmdStart
)
275 args
.push_back("-Tpdf");
277 args
.push_back("-Tps");
278 args
.push_back("-Nfontname=Courier");
279 args
.push_back("-Gsize=7.5,10");
280 args
.push_back(Filename
);
281 args
.push_back("-o");
282 args
.push_back(OutputFilename
);
284 errs() << "Running '" << GeneratorPath
<< "' program... ";
286 if (ExecGraphViewer(GeneratorPath
, args
, Filename
, true, ErrMsg
))
289 // The lifetime of StartArg must include the call of ExecGraphViewer
290 // because the args are passed as vector of char*.
291 std::string StartArg
;
294 args
.push_back(ViewerPath
);
297 args
.push_back("-W");
298 args
.push_back(OutputFilename
);
302 args
.push_back(OutputFilename
);
305 args
.push_back("--spartan");
306 args
.push_back(OutputFilename
);
309 args
.push_back("/S");
310 args
.push_back("/C");
312 (StringRef("start ") + (wait
? "/WAIT " : "") + OutputFilename
).str();
313 args
.push_back(StartArg
);
316 llvm_unreachable("Invalid viewer");
320 return ExecGraphViewer(ViewerPath
, args
, OutputFilename
, wait
, ErrMsg
);
324 if (S
.TryFindProgram("dotty", ViewerPath
)) {
325 std::vector
<StringRef
> args
;
326 args
.push_back(ViewerPath
);
327 args
.push_back(Filename
);
329 // Dotty spawns another app and doesn't wait until it returns
333 errs() << "Running 'dotty' program... ";
334 return ExecGraphViewer(ViewerPath
, args
, Filename
, wait
, ErrMsg
);
337 errs() << "Error: Couldn't find a usable graph viewer program:\n";
338 errs() << S
.LogBuffer
<< "\n";