1 //===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
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 defines an interface that allows bugpoint to run various passes
11 // without the threat of a buggy pass corrupting bugpoint (of course, bugpoint
12 // may have its own bugs, but that's another story...).  It achieves this by
13 // forking a copy of itself and having the child process do the optimizations.
14 // If this client dies, we can always fork a new one.  :)
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "BugDriver.h"
19 #include "llvm/Bitcode/BitcodeWriter.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/FileUtilities.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/Program.h"
27 #include "llvm/Support/ToolOutputFile.h"
28 
29 #define DONT_GET_PLUGIN_LOADER_OPTION
30 #include "llvm/Support/PluginLoader.h"
31 
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "bugpoint"
36 
37 namespace llvm {
38 extern cl::opt<std::string> OutputPrefix;
39 }
40 
41 static cl::opt<bool> PreserveBitcodeUseListOrder(
42     "preserve-bc-uselistorder",
43     cl::desc("Preserve use-list order when writing LLVM bitcode."),
44     cl::init(true), cl::Hidden);
45 
46 static cl::opt<std::string>
47     OptCmd("opt-command", cl::init(""),
48            cl::desc("Path to opt. (default: search path "
49                     "for 'opt'.)"));
50 
51 /// writeProgramToFile - This writes the current "Program" to the named bitcode
52 /// file.  If an error occurs, true is returned.
53 ///
54 static bool writeProgramToFileAux(ToolOutputFile &Out, const Module *M) {
55   WriteBitcodeToFile(M, Out.os(), PreserveBitcodeUseListOrder);
56   Out.os().close();
57   if (!Out.os().has_error()) {
58     Out.keep();
59     return false;
60   }
61   return true;
62 }
63 
64 bool BugDriver::writeProgramToFile(const std::string &Filename, int FD,
65                                    const Module *M) const {
66   ToolOutputFile Out(Filename, FD);
67   return writeProgramToFileAux(Out, M);
68 }
69 
70 bool BugDriver::writeProgramToFile(int FD, const Module *M) const {
71   raw_fd_ostream OS(FD, /*shouldClose*/ false);
72   WriteBitcodeToFile(M, OS, PreserveBitcodeUseListOrder);
73   OS.flush();
74   if (!OS.has_error())
75     return false;
76   OS.clear_error();
77   return true;
78 }
79 
80 bool BugDriver::writeProgramToFile(const std::string &Filename,
81                                    const Module *M) const {
82   std::error_code EC;
83   ToolOutputFile Out(Filename, EC, sys::fs::F_None);
84   if (!EC)
85     return writeProgramToFileAux(Out, M);
86   return true;
87 }
88 
89 /// EmitProgressBitcode - This function is used to output the current Program
90 /// to a file named "bugpoint-ID.bc".
91 ///
92 void BugDriver::EmitProgressBitcode(const Module *M, const std::string &ID,
93                                     bool NoFlyer) const {
94   // Output the input to the current pass to a bitcode file, emit a message
95   // telling the user how to reproduce it: opt -foo blah.bc
96   //
97   std::string Filename = OutputPrefix + "-" + ID + ".bc";
98   if (writeProgramToFile(Filename, M)) {
99     errs() << "Error opening file '" << Filename << "' for writing!\n";
100     return;
101   }
102 
103   outs() << "Emitted bitcode to '" << Filename << "'\n";
104   if (NoFlyer || PassesToRun.empty())
105     return;
106   outs() << "\n*** You can reproduce the problem with: ";
107   if (UseValgrind)
108     outs() << "valgrind ";
109   outs() << "opt " << Filename;
110   for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
111     outs() << " -load " << PluginLoader::getPlugin(i);
112   }
113   outs() << " " << getPassesString(PassesToRun) << "\n";
114 }
115 
116 cl::opt<bool> SilencePasses(
117     "silence-passes",
118     cl::desc("Suppress output of running passes (both stdout and stderr)"));
119 
120 static cl::list<std::string> OptArgs("opt-args", cl::Positional,
121                                      cl::desc("<opt arguments>..."),
122                                      cl::ZeroOrMore, cl::PositionalEatsArgs);
123 
124 /// runPasses - Run the specified passes on Program, outputting a bitcode file
125 /// and writing the filename into OutputFile if successful.  If the
126 /// optimizations fail for some reason (optimizer crashes), return true,
127 /// otherwise return false.  If DeleteOutput is set to true, the bitcode is
128 /// deleted on success, and the filename string is undefined.  This prints to
129 /// outs() a single line message indicating whether compilation was successful
130 /// or failed.
131 ///
132 bool BugDriver::runPasses(Module *Program,
133                           const std::vector<std::string> &Passes,
134                           std::string &OutputFilename, bool DeleteOutput,
135                           bool Quiet, unsigned NumExtraArgs,
136                           const char *const *ExtraArgs) const {
137   // setup the output file name
138   outs().flush();
139   SmallString<128> UniqueFilename;
140   std::error_code EC = sys::fs::createUniqueFile(
141       OutputPrefix + "-output-%%%%%%%.bc", UniqueFilename);
142   if (EC) {
143     errs() << getToolName()
144            << ": Error making unique filename: " << EC.message() << "\n";
145     return 1;
146   }
147   OutputFilename = UniqueFilename.str();
148 
149   // set up the input file name
150   Expected<sys::fs::TempFile> Temp =
151       sys::fs::TempFile::create(OutputPrefix + "-input-%%%%%%%.bc");
152   if (!Temp) {
153     errs() << getToolName()
154            << ": Error making unique filename: " << toString(Temp.takeError())
155            << "\n";
156     return 1;
157   }
158   DiscardTemp Discard{*Temp};
159   raw_fd_ostream OS(Temp->FD, /*shouldClose*/ false);
160 
161   WriteBitcodeToFile(Program, OS, PreserveBitcodeUseListOrder);
162   OS.flush();
163   if (OS.has_error()) {
164     errs() << "Error writing bitcode file: " << Temp->TmpName << "\n";
165     OS.clear_error();
166     return 1;
167   }
168 
169   std::string tool = OptCmd;
170   if (OptCmd.empty()) {
171     if (ErrorOr<std::string> Path = sys::findProgramByName("opt"))
172       tool = *Path;
173     else
174       errs() << Path.getError().message() << "\n";
175   }
176   if (tool.empty()) {
177     errs() << "Cannot find `opt' in PATH!\n";
178     return 1;
179   }
180   if (!sys::fs::exists(tool)) {
181     errs() << "Specified `opt' binary does not exist: " << tool << "\n";
182     return 1;
183   }
184 
185   std::string Prog;
186   if (UseValgrind) {
187     if (ErrorOr<std::string> Path = sys::findProgramByName("valgrind"))
188       Prog = *Path;
189     else
190       errs() << Path.getError().message() << "\n";
191   } else
192     Prog = tool;
193   if (Prog.empty()) {
194     errs() << "Cannot find `valgrind' in PATH!\n";
195     return 1;
196   }
197 
198   // setup the child process' arguments
199   SmallVector<const char *, 8> Args;
200   if (UseValgrind) {
201     Args.push_back("valgrind");
202     Args.push_back("--error-exitcode=1");
203     Args.push_back("-q");
204     Args.push_back(tool.c_str());
205   } else
206     Args.push_back(tool.c_str());
207 
208   for (unsigned i = 0, e = OptArgs.size(); i != e; ++i)
209     Args.push_back(OptArgs[i].c_str());
210   Args.push_back("-disable-symbolication");
211   Args.push_back("-o");
212   Args.push_back(OutputFilename.c_str());
213   std::vector<std::string> pass_args;
214   for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
215     pass_args.push_back(std::string("-load"));
216     pass_args.push_back(PluginLoader::getPlugin(i));
217   }
218   for (std::vector<std::string>::const_iterator I = Passes.begin(),
219                                                 E = Passes.end();
220        I != E; ++I)
221     pass_args.push_back(std::string("-") + (*I));
222   for (std::vector<std::string>::const_iterator I = pass_args.begin(),
223                                                 E = pass_args.end();
224        I != E; ++I)
225     Args.push_back(I->c_str());
226   Args.push_back(Temp->TmpName.c_str());
227   for (unsigned i = 0; i < NumExtraArgs; ++i)
228     Args.push_back(*ExtraArgs);
229   Args.push_back(nullptr);
230 
231   DEBUG(errs() << "\nAbout to run:\t";
232         for (unsigned i = 0, e = Args.size() - 1; i != e; ++i) errs()
233         << " " << Args[i];
234         errs() << "\n";);
235 
236   Optional<StringRef> Redirects[3] = {None, None, None};
237   // Redirect stdout and stderr to nowhere if SilencePasses is given.
238   if (SilencePasses) {
239     Redirects[1] = "";
240     Redirects[2] = "";
241   }
242 
243   std::string ErrMsg;
244   int result = sys::ExecuteAndWait(Prog, Args.data(), nullptr, Redirects,
245                                    Timeout, MemoryLimit, &ErrMsg);
246 
247   // If we are supposed to delete the bitcode file or if the passes crashed,
248   // remove it now.  This may fail if the file was never created, but that's ok.
249   if (DeleteOutput || result != 0)
250     sys::fs::remove(OutputFilename);
251 
252   if (!Quiet) {
253     if (result == 0)
254       outs() << "Success!\n";
255     else if (result > 0)
256       outs() << "Exited with error code '" << result << "'\n";
257     else if (result < 0) {
258       if (result == -1)
259         outs() << "Execute failed: " << ErrMsg << "\n";
260       else
261         outs() << "Crashed: " << ErrMsg << "\n";
262     }
263     if (result & 0x01000000)
264       outs() << "Dumped core\n";
265   }
266 
267   // Was the child successful?
268   return result != 0;
269 }
270 
271 std::unique_ptr<Module>
272 BugDriver::runPassesOn(Module *M, const std::vector<std::string> &Passes,
273                        unsigned NumExtraArgs, const char *const *ExtraArgs) {
274   std::string BitcodeResult;
275   if (runPasses(M, Passes, BitcodeResult, false /*delete*/, true /*quiet*/,
276                 NumExtraArgs, ExtraArgs)) {
277     return nullptr;
278   }
279 
280   std::unique_ptr<Module> Ret = parseInputFile(BitcodeResult, Context);
281   if (!Ret) {
282     errs() << getToolName() << ": Error reading bitcode file '" << BitcodeResult
283            << "'!\n";
284     exit(1);
285   }
286   sys::fs::remove(BitcodeResult);
287   return Ret;
288 }
289