1 //===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 // Note: as a short term hack, the old Unix-specific code and platform-
19 // independent code co-exist via conditional compilation until it is verified
20 // that the new code works correctly on Unix.
22 #include "BugDriver.h"
23 #include "llvm/Module.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/Analysis/Verifier.h"
26 #include "llvm/Bytecode/WriteBytecodePass.h"
27 #include "llvm/Bitcode/ReaderWriter.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Support/FileUtilities.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Streams.h"
32 #include "llvm/System/Path.h"
33 #include "llvm/System/Program.h"
34 #include "llvm/Config/alloca.h"
36 #define DONT_GET_PLUGIN_LOADER_OPTION
37 #include "llvm/Support/PluginLoader.h"
42 static bool Bitcode = false;
46 // ChildOutput - This option captures the name of the child output file that
47 // is set up by the parent bugpoint process
48 cl::opt<std::string> ChildOutput("child-output", cl::ReallyHidden);
49 cl::opt<bool> UseValgrind("enable-valgrind",
50 cl::desc("Run optimizations through valgrind"));
53 /// writeProgramToFile - This writes the current "Program" to the named bytecode
54 /// file. If an error occurs, true is returned.
56 bool BugDriver::writeProgramToFile(const std::string &Filename,
58 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
60 std::ofstream Out(Filename.c_str(), io_mode);
61 if (!Out.good()) return true;
64 WriteBytecodeToFile(M ? M : Program, L, /*compression=*/false);
72 /// EmitProgressBytecode - This function is used to output the current Program
73 /// to a file named "bugpoint-ID.bc".
75 void BugDriver::EmitProgressBytecode(const std::string &ID, bool NoFlyer) {
76 // Output the input to the current pass to a bytecode file, emit a message
77 // telling the user how to reproduce it: opt -foo blah.bc
79 std::string Filename = "bugpoint-" + ID + ".bc";
80 if (writeProgramToFile(Filename)) {
81 cerr << "Error opening file '" << Filename << "' for writing!\n";
85 cout << "Emitted bytecode to '" << Filename << "'\n";
86 if (NoFlyer || PassesToRun.empty()) return;
87 cout << "\n*** You can reproduce the problem with: ";
88 cout << "opt " << Filename << " ";
89 cout << getPassesString(PassesToRun) << "\n";
92 int BugDriver::runPassesAsChild(const std::vector<const PassInfo*> &Passes) {
94 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
96 std::ofstream OutFile(ChildOutput.c_str(), io_mode);
97 if (!OutFile.good()) {
98 cerr << "Error opening bytecode file: " << ChildOutput << "\n";
103 // Make sure that the appropriate target data is always used...
104 PM.add(new TargetData(Program));
106 for (unsigned i = 0, e = Passes.size(); i != e; ++i) {
107 if (Passes[i]->getNormalCtor())
108 PM.add(Passes[i]->getNormalCtor()());
110 cerr << "Cannot create pass yet: " << Passes[i]->getPassName() << "\n";
112 // Check that the module is well formed on completion of optimization
113 PM.add(createVerifierPass());
115 // Write bytecode out to disk as the last step...
118 PM.add(CreateBitcodeWriterPass(OutFile));
120 PM.add(new WriteBytecodePass(&L));
122 // Run all queued passes.
128 /// runPasses - Run the specified passes on Program, outputting a bytecode file
129 /// and writing the filename into OutputFile if successful. If the
130 /// optimizations fail for some reason (optimizer crashes), return true,
131 /// otherwise return false. If DeleteOutput is set to true, the bytecode is
132 /// deleted on success, and the filename string is undefined. This prints to
133 /// cout a single line message indicating whether compilation was successful or
136 bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes,
137 std::string &OutputFilename, bool DeleteOutput,
139 // setup the output file name
141 sys::Path uniqueFilename("bugpoint-output.bc");
143 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
144 cerr << getToolName() << ": Error making unique filename: "
148 OutputFilename = uniqueFilename.toString();
150 // set up the input file name
151 sys::Path inputFilename("bugpoint-input.bc");
152 if (inputFilename.makeUnique(true, &ErrMsg)) {
153 cerr << getToolName() << ": Error making unique filename: "
157 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
159 std::ofstream InFile(inputFilename.c_str(), io_mode);
160 if (!InFile.good()) {
161 cerr << "Error opening bytecode file: " << inputFilename << "\n";
165 WriteBytecodeToFile(Program,L,false);
168 // setup the child process' arguments
169 const char** args = (const char**)
170 alloca(sizeof(const char*) *
171 (Passes.size()+13+2*PluginLoader::getNumPlugins()));
173 sys::Path tool = sys::Program::FindProgramByName(ToolName);
175 args[n++] = "valgrind";
176 args[n++] = "--error-exitcode=1";
178 args[n++] = tool.c_str();
180 args[n++] = ToolName.c_str();
182 args[n++] = "-as-child";
183 args[n++] = "-child-output";
184 args[n++] = OutputFilename.c_str();
185 std::vector<std::string> pass_args;
186 for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
187 pass_args.push_back( std::string("-load"));
188 pass_args.push_back( PluginLoader::getPlugin(i));
190 for (std::vector<const PassInfo*>::const_iterator I = Passes.begin(),
191 E = Passes.end(); I != E; ++I )
192 pass_args.push_back( std::string("-") + (*I)->getPassArgument() );
193 for (std::vector<std::string>::const_iterator I = pass_args.begin(),
194 E = pass_args.end(); I != E; ++I )
195 args[n++] = I->c_str();
196 args[n++] = inputFilename.c_str();
201 prog = sys::Program::FindProgramByName("valgrind");
204 int result = sys::Program::ExecuteAndWait(prog, args, 0, 0,
205 Timeout, MemoryLimit, &ErrMsg);
207 // If we are supposed to delete the bytecode file or if the passes crashed,
208 // remove it now. This may fail if the file was never created, but that's ok.
209 if (DeleteOutput || result != 0)
210 sys::Path(OutputFilename).eraseFromDisk();
212 // Remove the temporary input file as well
213 inputFilename.eraseFromDisk();
217 cout << "Success!\n";
219 cout << "Exited with error code '" << result << "'\n";
220 else if (result < 0) {
222 cout << "Execute failed: " << ErrMsg << "\n";
224 cout << "Crashed with signal #" << abs(result) << "\n";
226 if (result & 0x01000000)
227 cout << "Dumped core\n";
230 // Was the child successful?
235 /// runPassesOn - Carefully run the specified set of pass on the specified
236 /// module, returning the transformed module on success, or a null pointer on
238 Module *BugDriver::runPassesOn(Module *M,
239 const std::vector<const PassInfo*> &Passes,
240 bool AutoDebugCrashes) {
241 Module *OldProgram = swapProgramIn(M);
242 std::string BytecodeResult;
243 if (runPasses(Passes, BytecodeResult, false/*delete*/, true/*quiet*/)) {
244 if (AutoDebugCrashes) {
245 cerr << " Error running this sequence of passes"
246 << " on the input program!\n";
248 EmitProgressBytecode("pass-error", false);
249 exit(debugOptimizerCrash());
251 swapProgramIn(OldProgram);
255 // Restore the current program.
256 swapProgramIn(OldProgram);
258 Module *Ret = ParseInputFile(BytecodeResult);
260 cerr << getToolName() << ": Error reading bytecode file '"
261 << BytecodeResult << "'!\n";
264 sys::Path(BytecodeResult).eraseFromDisk(); // No longer need the file on disk