]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Support/GraphWriter.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Support / GraphWriter.cpp
1 //===-- GraphWriter.cpp - Implements GraphWriter support routines ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements misc. GraphWriter support routines.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/GraphWriter.h"
15 #include "llvm/Config/config.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/Support/Program.h"
19 using namespace llvm;
20
21 static cl::opt<bool> ViewBackground("view-background", cl::Hidden,
22   cl::desc("Execute graph viewer in the background. Creates tmp file litter."));
23
24 std::string llvm::DOT::EscapeString(const std::string &Label) {
25   std::string Str(Label);
26   for (unsigned i = 0; i != Str.length(); ++i)
27   switch (Str[i]) {
28     case '\n':
29       Str.insert(Str.begin()+i, '\\');  // Escape character...
30       ++i;
31       Str[i] = 'n';
32       break;
33     case '\t':
34       Str.insert(Str.begin()+i, ' ');  // Convert to two spaces
35       ++i;
36       Str[i] = ' ';
37       break;
38     case '\\':
39       if (i+1 != Str.length())
40         switch (Str[i+1]) {
41           case 'l': continue; // don't disturb \l
42           case '|': case '{': case '}':
43             Str.erase(Str.begin()+i); continue;
44           default: break;
45         }
46         LLVM_FALLTHROUGH;
47     case '{': case '}':
48     case '<': case '>':
49     case '|': case '"':
50       Str.insert(Str.begin()+i, '\\');  // Escape character...
51       ++i;  // don't infinite loop
52       break;
53   }
54   return Str;
55 }
56
57 /// \brief Get a color string for this node number. Simply round-robin selects
58 /// from a reasonable number of colors.
59 StringRef llvm::DOT::getColorString(unsigned ColorNumber) {
60   static const int NumColors = 20;
61   static const char* Colors[NumColors] = {
62     "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa",
63     "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff",
64     "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"};
65   return Colors[ColorNumber % NumColors];
66 }
67
68 std::string llvm::createGraphFilename(const Twine &Name, int &FD) {
69   FD = -1;
70   SmallString<128> Filename;
71   std::error_code EC = sys::fs::createTemporaryFile(Name, "dot", FD, Filename);
72   if (EC) {
73     errs() << "Error: " << EC.message() << "\n";
74     return "";
75   }
76
77   errs() << "Writing '" << Filename << "'... ";
78   return Filename.str();
79 }
80
81 // Execute the graph viewer. Return true if there were errors.
82 static bool ExecGraphViewer(StringRef ExecPath, std::vector<const char *> &args,
83                             StringRef Filename, bool wait,
84                             std::string &ErrMsg) {
85   assert(args.back() == nullptr);
86   if (wait) {
87     if (sys::ExecuteAndWait(ExecPath, args.data(), nullptr, nullptr, 0, 0,
88                             &ErrMsg)) {
89       errs() << "Error: " << ErrMsg << "\n";
90       return true;
91     }
92     sys::fs::remove(Filename);
93     errs() << " done. \n";
94   } else {
95     sys::ExecuteNoWait(ExecPath, args.data(), nullptr, nullptr, 0, &ErrMsg);
96     errs() << "Remember to erase graph file: " << Filename << "\n";
97   }
98   return false;
99 }
100
101 namespace {
102 struct GraphSession {
103   std::string LogBuffer;
104   bool TryFindProgram(StringRef Names, std::string &ProgramPath) {
105     raw_string_ostream Log(LogBuffer);
106     SmallVector<StringRef, 8> parts;
107     Names.split(parts, '|');
108     for (auto Name : parts) {
109       if (ErrorOr<std::string> P = sys::findProgramByName(Name)) {
110         ProgramPath = *P;
111         return true;
112       }
113       Log << "  Tried '" << Name << "'\n";
114     }
115     return false;
116   }
117 };
118 } // namespace
119
120 static const char *getProgramName(GraphProgram::Name program) {
121   switch (program) {
122   case GraphProgram::DOT:
123     return "dot";
124   case GraphProgram::FDP:
125     return "fdp";
126   case GraphProgram::NEATO:
127     return "neato";
128   case GraphProgram::TWOPI:
129     return "twopi";
130   case GraphProgram::CIRCO:
131     return "circo";
132   }
133   llvm_unreachable("bad kind");
134 }
135
136 bool llvm::DisplayGraph(StringRef FilenameRef, bool wait,
137                         GraphProgram::Name program) {
138   std::string Filename = FilenameRef;
139   std::string ErrMsg;
140   std::string ViewerPath;
141   GraphSession S;
142
143 #ifdef __APPLE__
144   wait &= !ViewBackground;
145   if (S.TryFindProgram("open", ViewerPath)) {
146     std::vector<const char *> args;
147     args.push_back(ViewerPath.c_str());
148     if (wait)
149       args.push_back("-W");
150     args.push_back(Filename.c_str());
151     args.push_back(nullptr);
152     errs() << "Trying 'open' program... ";
153     if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg))
154       return false;
155   }
156 #endif
157   if (S.TryFindProgram("xdg-open", ViewerPath)) {
158     std::vector<const char *> args;
159     args.push_back(ViewerPath.c_str());
160     args.push_back(Filename.c_str());
161     args.push_back(nullptr);
162     errs() << "Trying 'xdg-open' program... ";
163     if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg))
164       return false;
165   }
166
167   // Graphviz
168   if (S.TryFindProgram("Graphviz", ViewerPath)) {
169     std::vector<const char *> args;
170     args.push_back(ViewerPath.c_str());
171     args.push_back(Filename.c_str());
172     args.push_back(nullptr);
173
174     errs() << "Running 'Graphviz' program... ";
175     return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
176   }
177
178   // xdot
179   if (S.TryFindProgram("xdot|xdot.py", ViewerPath)) {
180     std::vector<const char *> args;
181     args.push_back(ViewerPath.c_str());
182     args.push_back(Filename.c_str());
183
184     args.push_back("-f");
185     args.push_back(getProgramName(program));
186
187     args.push_back(nullptr);
188
189     errs() << "Running 'xdot.py' program... ";
190     return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
191   }
192
193   enum ViewerKind {
194     VK_None,
195     VK_OSXOpen,
196     VK_XDGOpen,
197     VK_Ghostview,
198     VK_CmdStart
199   };
200   ViewerKind Viewer = VK_None;
201 #ifdef __APPLE__
202   if (!Viewer && S.TryFindProgram("open", ViewerPath))
203     Viewer = VK_OSXOpen;
204 #endif
205   if (!Viewer && S.TryFindProgram("gv", ViewerPath))
206     Viewer = VK_Ghostview;
207   if (!Viewer && S.TryFindProgram("xdg-open", ViewerPath))
208     Viewer = VK_XDGOpen;
209 #ifdef LLVM_ON_WIN32
210   if (!Viewer && S.TryFindProgram("cmd", ViewerPath)) {
211     Viewer = VK_CmdStart;
212   }
213 #endif
214
215   // PostScript or PDF graph generator + PostScript/PDF viewer
216   std::string GeneratorPath;
217   if (Viewer &&
218       (S.TryFindProgram(getProgramName(program), GeneratorPath) ||
219        S.TryFindProgram("dot|fdp|neato|twopi|circo", GeneratorPath))) {
220     std::string OutputFilename =
221         Filename + (Viewer == VK_CmdStart ? ".pdf" : ".ps");
222
223     std::vector<const char *> args;
224     args.push_back(GeneratorPath.c_str());
225     if (Viewer == VK_CmdStart)
226       args.push_back("-Tpdf");
227     else
228       args.push_back("-Tps");
229     args.push_back("-Nfontname=Courier");
230     args.push_back("-Gsize=7.5,10");
231     args.push_back(Filename.c_str());
232     args.push_back("-o");
233     args.push_back(OutputFilename.c_str());
234     args.push_back(nullptr);
235
236     errs() << "Running '" << GeneratorPath << "' program... ";
237
238     if (ExecGraphViewer(GeneratorPath, args, Filename, true, ErrMsg))
239       return true;
240
241     // The lifetime of StartArg must include the call of ExecGraphViewer
242     // because the args are passed as vector of char*.
243     std::string StartArg;
244
245     args.clear();
246     args.push_back(ViewerPath.c_str());
247     switch (Viewer) {
248     case VK_OSXOpen:
249       args.push_back("-W");
250       args.push_back(OutputFilename.c_str());
251       break;
252     case VK_XDGOpen:
253       wait = false;
254       args.push_back(OutputFilename.c_str());
255       break;
256     case VK_Ghostview:
257       args.push_back("--spartan");
258       args.push_back(OutputFilename.c_str());
259       break;
260     case VK_CmdStart:
261       args.push_back("/S");
262       args.push_back("/C");
263       StartArg =
264           (StringRef("start ") + (wait ? "/WAIT " : "") + OutputFilename).str();
265       args.push_back(StartArg.c_str());
266       break;
267     case VK_None:
268       llvm_unreachable("Invalid viewer");
269     }
270     args.push_back(nullptr);
271
272     ErrMsg.clear();
273     return ExecGraphViewer(ViewerPath, args, OutputFilename, wait, ErrMsg);
274   }
275
276   // dotty
277   if (S.TryFindProgram("dotty", ViewerPath)) {
278     std::vector<const char *> args;
279     args.push_back(ViewerPath.c_str());
280     args.push_back(Filename.c_str());
281     args.push_back(nullptr);
282
283 // Dotty spawns another app and doesn't wait until it returns
284 #ifdef LLVM_ON_WIN32
285     wait = false;
286 #endif
287     errs() << "Running 'dotty' program... ";
288     return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
289   }
290
291   errs() << "Error: Couldn't find a usable graph viewer program:\n";
292   errs() << S.LogBuffer << "\n";
293   return true;
294 }