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/Target/TargetData.h"
28 #include "llvm/Support/FileUtilities.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/System/Program.h"
36 // ChildOutput - This option captures the name of the child output file that
37 // is set up by the parent bugpoint process
38 cl::opt<std::string> ChildOutput("child-output", cl::ReallyHidden);
41 /// writeProgramToFile - This writes the current "Program" to the named bytecode
42 /// file. If an error occurs, true is returned.
44 bool BugDriver::writeProgramToFile(const std::string &Filename,
46 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
48 std::ofstream Out(Filename.c_str(), io_mode);
49 if (!Out.good()) return true;
50 WriteBytecodeToFile(M ? M : Program, Out, /*compression=*/true);
55 /// EmitProgressBytecode - This function is used to output the current Program
56 /// to a file named "bugpoint-ID.bc".
58 void BugDriver::EmitProgressBytecode(const std::string &ID, bool NoFlyer) {
59 // Output the input to the current pass to a bytecode file, emit a message
60 // telling the user how to reproduce it: opt -foo blah.bc
62 std::string Filename = "bugpoint-" + ID + ".bc";
63 if (writeProgramToFile(Filename)) {
64 std::cerr << "Error opening file '" << Filename << "' for writing!\n";
68 std::cout << "Emitted bytecode to '" << Filename << "'\n";
69 if (NoFlyer || PassesToRun.empty()) return;
70 std::cout << "\n*** You can reproduce the problem with: ";
72 unsigned PassType = PassesToRun[0]->getPassType();
73 for (unsigned i = 1, e = PassesToRun.size(); i != e; ++i)
74 PassType &= PassesToRun[i]->getPassType();
76 if (PassType & PassInfo::Analysis)
77 std::cout << "analyze";
78 else if (PassType & PassInfo::Optimization)
80 else if (PassType & PassInfo::LLC)
83 std::cout << "bugpoint";
84 std::cout << " " << Filename << " ";
85 std::cout << getPassesString(PassesToRun) << "\n";
88 int BugDriver::runPassesAsChild(const std::vector<const PassInfo*> &Passes) {
90 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
92 std::ofstream OutFile(ChildOutput.c_str(), io_mode);
93 if (!OutFile.good()) {
94 std::cerr << "Error opening bytecode file: " << ChildOutput << "\n";
99 // Make sure that the appropriate target data is always used...
100 PM.add(new TargetData("bugpoint", Program));
102 for (unsigned i = 0, e = Passes.size(); i != e; ++i) {
103 if (Passes[i]->getNormalCtor())
104 PM.add(Passes[i]->getNormalCtor()());
106 std::cerr << "Cannot create pass yet: " << Passes[i]->getPassName()
109 // Check that the module is well formed on completion of optimization
110 PM.add(createVerifierPass());
112 // Write bytecode out to disk as the last step...
113 PM.add(new WriteBytecodePass(&OutFile));
115 // Run all queued passes.
121 /// runPasses - Run the specified passes on Program, outputting a bytecode file
122 /// and writing the filename into OutputFile if successful. If the
123 /// optimizations fail for some reason (optimizer crashes), return true,
124 /// otherwise return false. If DeleteOutput is set to true, the bytecode is
125 /// deleted on success, and the filename string is undefined. This prints to
126 /// cout a single line message indicating whether compilation was successful or
129 bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes,
130 std::string &OutputFilename, bool DeleteOutput,
132 // setup the output file name
133 std::cout << std::flush;
134 sys::Path uniqueFilename("bugpoint-output.bc");
135 uniqueFilename.makeUnique();
136 OutputFilename = uniqueFilename.toString();
138 // set up the input file name
139 sys::Path inputFilename("bugpoint-input.bc");
140 inputFilename.makeUnique();
141 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
143 std::ofstream InFile(inputFilename.c_str(), io_mode);
144 if (!InFile.good()) {
145 std::cerr << "Error opening bytecode file: " << inputFilename << "\n";
148 WriteBytecodeToFile(Program,InFile,false);
151 // setup the child process' arguments
152 const char** args = (const char**)
153 alloca(sizeof(const char*)*(Passes.size()+10));
155 args[n++] = ToolName.c_str();
156 args[n++] = "-as-child";
157 args[n++] = "-child-output";
158 args[n++] = OutputFilename.c_str();
159 std::vector<std::string> pass_args;
160 for (std::vector<const PassInfo*>::const_iterator I = Passes.begin(),
161 E = Passes.end(); I != E; ++I )
162 pass_args.push_back( std::string("-") + (*I)->getPassArgument() );
163 for (std::vector<std::string>::const_iterator I = pass_args.begin(),
164 E = pass_args.end(); I != E; ++I )
165 args[n++] = I->c_str();
166 args[n++] = inputFilename.c_str();
169 sys::Path prog(sys::Program::FindProgramByName(ToolName));
170 int result = sys::Program::ExecuteAndWait(prog,args);
172 // If we are supposed to delete the bytecode file or if the passes crashed,
173 // remove it now. This may fail if the file was never created, but that's ok.
174 if (DeleteOutput || result != 0)
175 sys::Path(OutputFilename).eraseFromDisk();
177 // Remove the temporary input file as well
178 inputFilename.eraseFromDisk();
182 std::cout << "Success!\n";
184 std::cout << "Exited with error code '" << result << "'\n";
186 std::cout << "Crashed with signal #" << abs(result) << "\n";
187 if (result & 0x01000000)
188 std::cout << "Dumped core\n";
191 // Was the child successful?
196 /// runPassesOn - Carefully run the specified set of pass on the specified
197 /// module, returning the transformed module on success, or a null pointer on
199 Module *BugDriver::runPassesOn(Module *M,
200 const std::vector<const PassInfo*> &Passes,
201 bool AutoDebugCrashes) {
202 Module *OldProgram = swapProgramIn(M);
203 std::string BytecodeResult;
204 if (runPasses(Passes, BytecodeResult, false/*delete*/, true/*quiet*/)) {
205 if (AutoDebugCrashes) {
206 std::cerr << " Error running this sequence of passes"
207 << " on the input program!\n";
209 EmitProgressBytecode("pass-error", false);
210 exit(debugOptimizerCrash());
212 swapProgramIn(OldProgram);
216 // Restore the current program.
217 swapProgramIn(OldProgram);
219 Module *Ret = ParseInputFile(BytecodeResult);
221 std::cerr << getToolName() << ": Error reading bytecode file '"
222 << BytecodeResult << "'!\n";
225 sys::Path(BytecodeResult).eraseFromDisk(); // No longer need the file on disk