LLVM 19.0.0git
GraphWriter.cpp
Go to the documentation of this file.
1//===- GraphWriter.cpp - Implements GraphWriter support routines ----------===//
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 implements misc. GraphWriter support routines.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "DebugOptions.h"
16
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Config/config.h"
25#include "llvm/Support/Path.h"
28
29#ifdef __APPLE__
31#endif
32
33#include <string>
34#include <system_error>
35#include <vector>
36
37using namespace llvm;
38
39#ifdef __APPLE__
40namespace {
41struct CreateViewBackground {
42 static void *call() {
43 return new cl::opt<bool>("view-background", cl::Hidden,
44 cl::desc("Execute graph viewer in the background. "
45 "Creates tmp file litter."));
46 }
47};
48} // namespace
49static ManagedStatic<cl::opt<bool>, CreateViewBackground> ViewBackground;
50void llvm::initGraphWriterOptions() { *ViewBackground; }
51#else
53#endif
54
55std::string llvm::DOT::EscapeString(const std::string &Label) {
56 std::string Str(Label);
57 for (unsigned i = 0; i != Str.length(); ++i)
58 switch (Str[i]) {
59 case '\n':
60 Str.insert(Str.begin()+i, '\\'); // Escape character...
61 ++i;
62 Str[i] = 'n';
63 break;
64 case '\t':
65 Str.insert(Str.begin()+i, ' '); // Convert to two spaces
66 ++i;
67 Str[i] = ' ';
68 break;
69 case '\\':
70 if (i+1 != Str.length())
71 switch (Str[i+1]) {
72 case 'l': continue; // don't disturb \l
73 case '|': case '{': case '}':
74 Str.erase(Str.begin()+i); continue;
75 default: break;
76 }
77 [[fallthrough]];
78 case '{': case '}':
79 case '<': case '>':
80 case '|': case '"':
81 Str.insert(Str.begin()+i, '\\'); // Escape character...
82 ++i; // don't infinite loop
83 break;
84 }
85 return Str;
86}
87
88/// Get a color string for this node number. Simply round-robin selects
89/// from a reasonable number of colors.
90StringRef 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];
97}
98
99static std::string replaceIllegalFilenameChars(std::string Filename,
100 const char ReplacementChar) {
101 std::string IllegalChars =
102 is_style_windows(sys::path::Style::native) ? "\\/:?\"<>|" : "/";
103
104 for (char IllegalChar : IllegalChars) {
105 std::replace(Filename.begin(), Filename.end(), IllegalChar,
106 ReplacementChar);
107 }
108
109 return Filename;
110}
111
112std::string llvm::createGraphFilename(const Twine &Name, int &FD) {
113 FD = -1;
114 SmallString<128> Filename;
115
116 // Windows can't always handle long paths, so limit the length of the name.
117 std::string N = Name.str();
118 if (N.size() > 140)
119 N.resize(140);
120
121 // Replace illegal characters in graph Filename with '_' if needed
122 std::string CleansedName = replaceIllegalFilenameChars(N, '_');
123
124 std::error_code EC =
125 sys::fs::createTemporaryFile(CleansedName, "dot", FD, Filename);
126 if (EC) {
127 errs() << "Error: " << EC.message() << "\n";
128 return "";
129 }
130
131 errs() << "Writing '" << Filename << "'... ";
132 return std::string(Filename);
133}
134
135// Execute the graph viewer. Return true if there were errors.
136static bool ExecGraphViewer(StringRef ExecPath, std::vector<StringRef> &args,
137 StringRef Filename, bool wait,
138 std::string &ErrMsg) {
139 if (wait) {
140 if (sys::ExecuteAndWait(ExecPath, args, std::nullopt, {}, 0, 0, &ErrMsg)) {
141 errs() << "Error: " << ErrMsg << "\n";
142 return true;
143 }
144 sys::fs::remove(Filename);
145 errs() << " done. \n";
146 } else {
147 sys::ExecuteNoWait(ExecPath, args, std::nullopt, {}, 0, &ErrMsg);
148 errs() << "Remember to erase graph file: " << Filename << "\n";
149 }
150 return false;
151}
152
153namespace {
154
155struct GraphSession {
156 std::string LogBuffer;
157
158 bool TryFindProgram(StringRef Names, std::string &ProgramPath) {
159 raw_string_ostream Log(LogBuffer);
161 Names.split(parts, '|');
162 for (auto Name : parts) {
164 ProgramPath = *P;
165 return true;
166 }
167 Log << " Tried '" << Name << "'\n";
168 }
169 return false;
170 }
171};
172
173} // end anonymous namespace
174
175static const char *getProgramName(GraphProgram::Name program) {
176 switch (program) {
178 return "dot";
180 return "fdp";
182 return "neato";
184 return "twopi";
186 return "circo";
187 }
188 llvm_unreachable("bad kind");
189}
190
191bool llvm::DisplayGraph(StringRef FilenameRef, bool wait,
192 GraphProgram::Name program) {
193 std::string Filename = std::string(FilenameRef);
194 std::string ErrMsg;
195 std::string ViewerPath;
196 GraphSession S;
197
198#ifdef __APPLE__
199 wait &= !*ViewBackground;
200 if (S.TryFindProgram("open", ViewerPath)) {
201 std::vector<StringRef> args;
202 args.push_back(ViewerPath);
203 if (wait)
204 args.push_back("-W");
205 args.push_back(Filename);
206 errs() << "Trying 'open' program... ";
207 if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg))
208 return false;
209 }
210#endif
211 if (S.TryFindProgram("xdg-open", ViewerPath)) {
212 std::vector<StringRef> args;
213 args.push_back(ViewerPath);
214 args.push_back(Filename);
215 errs() << "Trying 'xdg-open' program... ";
216 if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg))
217 return false;
218 }
219
220 // Graphviz
221 if (S.TryFindProgram("Graphviz", ViewerPath)) {
222 std::vector<StringRef> args;
223 args.push_back(ViewerPath);
224 args.push_back(Filename);
225
226 errs() << "Running 'Graphviz' program... ";
227 return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
228 }
229
230 // xdot
231 if (S.TryFindProgram("xdot|xdot.py", ViewerPath)) {
232 std::vector<StringRef> args;
233 args.push_back(ViewerPath);
234 args.push_back(Filename);
235
236 args.push_back("-f");
237 args.push_back(getProgramName(program));
238
239 errs() << "Running 'xdot.py' program... ";
240 return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
241 }
242
243 enum ViewerKind {
244 VK_None,
245 VK_OSXOpen,
246 VK_XDGOpen,
247 VK_Ghostview,
248 VK_CmdStart
249 };
250 ViewerKind Viewer = VK_None;
251#ifdef __APPLE__
252 if (!Viewer && S.TryFindProgram("open", ViewerPath))
253 Viewer = VK_OSXOpen;
254#endif
255 if (!Viewer && S.TryFindProgram("gv", ViewerPath))
256 Viewer = VK_Ghostview;
257 if (!Viewer && S.TryFindProgram("xdg-open", ViewerPath))
258 Viewer = VK_XDGOpen;
259#ifdef _WIN32
260 if (!Viewer && S.TryFindProgram("cmd", ViewerPath)) {
261 Viewer = VK_CmdStart;
262 }
263#endif
264
265 // PostScript or PDF graph generator + PostScript/PDF viewer
266 std::string GeneratorPath;
267 if (Viewer &&
268 (S.TryFindProgram(getProgramName(program), GeneratorPath) ||
269 S.TryFindProgram("dot|fdp|neato|twopi|circo", GeneratorPath))) {
270 std::string OutputFilename =
271 Filename + (Viewer == VK_CmdStart ? ".pdf" : ".ps");
272
273 std::vector<StringRef> args;
274 args.push_back(GeneratorPath);
275 if (Viewer == VK_CmdStart)
276 args.push_back("-Tpdf");
277 else
278 args.push_back("-Tps");
279 args.push_back("-Nfontname=Courier");
280 args.push_back("-Gsize=7.5,10");
281 args.push_back(Filename);
282 args.push_back("-o");
283 args.push_back(OutputFilename);
284
285 errs() << "Running '" << GeneratorPath << "' program... ";
286
287 if (ExecGraphViewer(GeneratorPath, args, Filename, true, ErrMsg))
288 return true;
289
290 // The lifetime of StartArg must include the call of ExecGraphViewer
291 // because the args are passed as vector of char*.
292 std::string StartArg;
293
294 args.clear();
295 args.push_back(ViewerPath);
296 switch (Viewer) {
297 case VK_OSXOpen:
298 args.push_back("-W");
299 args.push_back(OutputFilename);
300 break;
301 case VK_XDGOpen:
302 wait = false;
303 args.push_back(OutputFilename);
304 break;
305 case VK_Ghostview:
306 args.push_back("--spartan");
307 args.push_back(OutputFilename);
308 break;
309 case VK_CmdStart:
310 args.push_back("/S");
311 args.push_back("/C");
312 StartArg =
313 (StringRef("start ") + (wait ? "/WAIT " : "") + OutputFilename).str();
314 args.push_back(StartArg);
315 break;
316 case VK_None:
317 llvm_unreachable("Invalid viewer");
318 }
319
320 ErrMsg.clear();
321 return ExecGraphViewer(ViewerPath, args, OutputFilename, wait, ErrMsg);
322 }
323
324 // dotty
325 if (S.TryFindProgram("dotty", ViewerPath)) {
326 std::vector<StringRef> args;
327 args.push_back(ViewerPath);
328 args.push_back(Filename);
329
330// Dotty spawns another app and doesn't wait until it returns
331#ifdef _WIN32
332 wait = false;
333#endif
334 errs() << "Running 'dotty' program... ";
335 return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
336 }
337
338 errs() << "Error: Couldn't find a usable graph viewer program:\n";
339 errs() << S.LogBuffer << "\n";
340 return true;
341}
std::string Name
Provides ErrorOr<T> smart pointer.
static std::string replaceIllegalFilenameChars(std::string Filename, const char ReplacementChar)
Definition: GraphWriter.cpp:99
static bool ExecGraphViewer(StringRef ExecPath, std::vector< StringRef > &args, StringRef Filename, bool wait, std::string &ErrMsg)
static const char * getProgramName(GraphProgram::Name program)
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
nvptx lower args
#define P(N)
This file defines the SmallString class.
This file defines the SmallVector class.
Represents either an error or a value T.
Definition: ErrorOr.h:56
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:693
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::string EscapeString(const std::string &Label)
Definition: GraphWriter.cpp:55
StringRef getColorString(unsigned NodeNumber)
Get a color string for this node number.
Definition: GraphWriter.cpp:90
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None)
Create a file in the system temporary directory.
Definition: Path.cpp:864
ProcessInfo ExecuteNoWait(StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env, ArrayRef< std::optional< StringRef > > Redirects={}, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr, BitVector *AffinityMask=nullptr, bool DetachProcess=false)
Similar to ExecuteAndWait, but returns immediately.
Definition: Program.cpp:57
int ExecuteAndWait(StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env=std::nullopt, ArrayRef< std::optional< StringRef > > Redirects={}, unsigned SecondsToWait=0, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr, std::optional< ProcessStatistics > *ProcStat=nullptr, BitVector *AffinityMask=nullptr)
This function executes the program using the arguments provided.
Definition: Program.cpp:32
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool DisplayGraph(StringRef Filename, bool wait=true, GraphProgram::Name program=GraphProgram::DOT)
std::string createGraphFilename(const Twine &Name, int &FD)
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void initGraphWriterOptions()
Definition: GraphWriter.cpp:52
#define N