1 //===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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. :)
16 //===----------------------------------------------------------------------===//
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"
29 #define DONT_GET_PLUGIN_LOADER_OPTION
30 #include "llvm/Support/PluginLoader.h"
35 #define DEBUG_TYPE "bugpoint"
38 extern cl::opt
<std::string
> OutputPrefix
;
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
);
46 static cl::opt
<std::string
>
47 OptCmd("opt-command", cl::init(""),
48 cl::desc("Path to opt. (default: search path "
51 /// This writes the current "Program" to the named bitcode file. If an error
52 /// occurs, true is returned.
53 static bool writeProgramToFileAux(ToolOutputFile
&Out
, const Module
&M
) {
54 WriteBitcodeToFile(M
, Out
.os(), PreserveBitcodeUseListOrder
);
56 if (!Out
.os().has_error()) {
63 bool BugDriver::writeProgramToFile(const std::string
&Filename
, int FD
,
64 const Module
&M
) const {
65 ToolOutputFile
Out(Filename
, FD
);
66 return writeProgramToFileAux(Out
, M
);
69 bool BugDriver::writeProgramToFile(int FD
, const Module
&M
) const {
70 raw_fd_ostream
OS(FD
, /*shouldClose*/ false);
71 WriteBitcodeToFile(M
, OS
, PreserveBitcodeUseListOrder
);
79 bool BugDriver::writeProgramToFile(const std::string
&Filename
,
80 const Module
&M
) const {
82 ToolOutputFile
Out(Filename
, EC
, sys::fs::F_None
);
84 return writeProgramToFileAux(Out
, M
);
88 /// This function is used to output the current Program to a file named
90 void BugDriver::EmitProgressBitcode(const Module
&M
, const std::string
&ID
,
92 // Output the input to the current pass to a bitcode file, emit a message
93 // telling the user how to reproduce it: opt -foo blah.bc
95 std::string Filename
= OutputPrefix
+ "-" + ID
+ ".bc";
96 if (writeProgramToFile(Filename
, M
)) {
97 errs() << "Error opening file '" << Filename
<< "' for writing!\n";
101 outs() << "Emitted bitcode to '" << Filename
<< "'\n";
102 if (NoFlyer
|| PassesToRun
.empty())
104 outs() << "\n*** You can reproduce the problem with: ";
106 outs() << "valgrind ";
107 outs() << "opt " << Filename
;
108 for (unsigned i
= 0, e
= PluginLoader::getNumPlugins(); i
!= e
; ++i
) {
109 outs() << " -load " << PluginLoader::getPlugin(i
);
111 outs() << " " << getPassesString(PassesToRun
) << "\n";
114 cl::opt
<bool> SilencePasses(
116 cl::desc("Suppress output of running passes (both stdout and stderr)"));
118 static cl::list
<std::string
> OptArgs("opt-args", cl::Positional
,
119 cl::desc("<opt arguments>..."),
120 cl::ZeroOrMore
, cl::PositionalEatsArgs
);
122 /// runPasses - Run the specified passes on Program, outputting a bitcode file
123 /// and writing the filename into OutputFile if successful. If the
124 /// optimizations fail for some reason (optimizer crashes), return true,
125 /// otherwise return false. If DeleteOutput is set to true, the bitcode is
126 /// deleted on success, and the filename string is undefined. This prints to
127 /// outs() a single line message indicating whether compilation was successful
130 bool BugDriver::runPasses(Module
&Program
,
131 const std::vector
<std::string
> &Passes
,
132 std::string
&OutputFilename
, bool DeleteOutput
,
133 bool Quiet
, unsigned NumExtraArgs
,
134 const char *const *ExtraArgs
) const {
135 // setup the output file name
137 SmallString
<128> UniqueFilename
;
138 std::error_code EC
= sys::fs::createUniqueFile(
139 OutputPrefix
+ "-output-%%%%%%%.bc", UniqueFilename
);
141 errs() << getToolName()
142 << ": Error making unique filename: " << EC
.message() << "\n";
145 OutputFilename
= UniqueFilename
.str();
147 // set up the input file name
148 Expected
<sys::fs::TempFile
> Temp
=
149 sys::fs::TempFile::create(OutputPrefix
+ "-input-%%%%%%%.bc");
151 errs() << getToolName()
152 << ": Error making unique filename: " << toString(Temp
.takeError())
156 DiscardTemp Discard
{*Temp
};
157 raw_fd_ostream
OS(Temp
->FD
, /*shouldClose*/ false);
159 WriteBitcodeToFile(Program
, OS
, PreserveBitcodeUseListOrder
);
161 if (OS
.has_error()) {
162 errs() << "Error writing bitcode file: " << Temp
->TmpName
<< "\n";
167 std::string tool
= OptCmd
;
168 if (OptCmd
.empty()) {
169 if (ErrorOr
<std::string
> Path
= sys::findProgramByName("opt"))
172 errs() << Path
.getError().message() << "\n";
175 errs() << "Cannot find `opt' in PATH!\n";
178 if (!sys::fs::exists(tool
)) {
179 errs() << "Specified `opt' binary does not exist: " << tool
<< "\n";
185 if (ErrorOr
<std::string
> Path
= sys::findProgramByName("valgrind"))
188 errs() << Path
.getError().message() << "\n";
192 errs() << "Cannot find `valgrind' in PATH!\n";
196 // setup the child process' arguments
197 SmallVector
<StringRef
, 8> Args
;
199 Args
.push_back("valgrind");
200 Args
.push_back("--error-exitcode=1");
201 Args
.push_back("-q");
202 Args
.push_back(tool
);
204 Args
.push_back(tool
);
206 for (unsigned i
= 0, e
= OptArgs
.size(); i
!= e
; ++i
)
207 Args
.push_back(OptArgs
[i
]);
208 Args
.push_back("-disable-symbolication");
209 Args
.push_back("-o");
210 Args
.push_back(OutputFilename
);
211 std::vector
<std::string
> pass_args
;
212 for (unsigned i
= 0, e
= PluginLoader::getNumPlugins(); i
!= e
; ++i
) {
213 pass_args
.push_back(std::string("-load"));
214 pass_args
.push_back(PluginLoader::getPlugin(i
));
216 for (std::vector
<std::string
>::const_iterator I
= Passes
.begin(),
219 pass_args
.push_back(std::string("-") + (*I
));
220 for (std::vector
<std::string
>::const_iterator I
= pass_args
.begin(),
223 Args
.push_back(I
->c_str());
224 Args
.push_back(Temp
->TmpName
.c_str());
225 for (unsigned i
= 0; i
< NumExtraArgs
; ++i
)
226 Args
.push_back(*ExtraArgs
);
228 LLVM_DEBUG(errs() << "\nAbout to run:\t";
229 for (unsigned i
= 0, e
= Args
.size() - 1; i
!= e
; ++i
) errs()
233 Optional
<StringRef
> Redirects
[3] = {None
, None
, None
};
234 // Redirect stdout and stderr to nowhere if SilencePasses is given.
241 int result
= sys::ExecuteAndWait(Prog
, Args
, None
, Redirects
, Timeout
,
242 MemoryLimit
, &ErrMsg
);
244 // If we are supposed to delete the bitcode file or if the passes crashed,
245 // remove it now. This may fail if the file was never created, but that's ok.
246 if (DeleteOutput
|| result
!= 0)
247 sys::fs::remove(OutputFilename
);
251 outs() << "Success!\n";
253 outs() << "Exited with error code '" << result
<< "'\n";
254 else if (result
< 0) {
256 outs() << "Execute failed: " << ErrMsg
<< "\n";
258 outs() << "Crashed: " << ErrMsg
<< "\n";
260 if (result
& 0x01000000)
261 outs() << "Dumped core\n";
264 // Was the child successful?
268 std::unique_ptr
<Module
>
269 BugDriver::runPassesOn(Module
*M
, const std::vector
<std::string
> &Passes
,
270 unsigned NumExtraArgs
, const char *const *ExtraArgs
) {
271 std::string BitcodeResult
;
272 if (runPasses(*M
, Passes
, BitcodeResult
, false /*delete*/, true /*quiet*/,
273 NumExtraArgs
, ExtraArgs
)) {
277 std::unique_ptr
<Module
> Ret
= parseInputFile(BitcodeResult
, Context
);
279 errs() << getToolName() << ": Error reading bitcode file '" << BitcodeResult
283 sys::fs::remove(BitcodeResult
);