For PR351:
[oota-llvm.git] / tools / bugpoint / OptimizerDriver.cpp
1 //===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
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 // 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.
21
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"
32 #include <fstream>
33 using namespace llvm;
34
35 namespace {
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);
39 }
40
41 /// writeProgramToFile - This writes the current "Program" to the named bytecode
42 /// file.  If an error occurs, true is returned.
43 ///
44 bool BugDriver::writeProgramToFile(const std::string &Filename,
45                                    Module *M) const {
46   std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
47                                std::ios::binary;
48   std::ofstream Out(Filename.c_str(), io_mode);
49   if (!Out.good()) return true;
50   WriteBytecodeToFile(M ? M : Program, Out, /*compression=*/true);
51   return false;
52 }
53
54
55 /// EmitProgressBytecode - This function is used to output the current Program
56 /// to a file named "bugpoint-ID.bc".
57 ///
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
61   //
62   std::string Filename = "bugpoint-" + ID + ".bc";
63   if (writeProgramToFile(Filename)) {
64     std::cerr <<  "Error opening file '" << Filename << "' for writing!\n";
65     return;
66   }
67
68   std::cout << "Emitted bytecode to '" << Filename << "'\n";
69   if (NoFlyer || PassesToRun.empty()) return;
70   std::cout << "\n*** You can reproduce the problem with: ";
71
72   unsigned PassType = PassesToRun[0]->getPassType();
73   for (unsigned i = 1, e = PassesToRun.size(); i != e; ++i)
74     PassType &= PassesToRun[i]->getPassType();
75
76   if (PassType & PassInfo::Analysis)
77     std::cout << "analyze";
78   else if (PassType & PassInfo::Optimization)
79     std::cout << "opt";
80   else if (PassType & PassInfo::LLC)
81     std::cout << "llc";
82   else
83     std::cout << "bugpoint";
84   std::cout << " " << Filename << " ";
85   std::cout << getPassesString(PassesToRun) << "\n";
86 }
87
88 int BugDriver::runPassesAsChild(const std::vector<const PassInfo*> &Passes) {
89
90   std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
91                                std::ios::binary;
92   std::ofstream OutFile(ChildOutput.c_str(), io_mode);
93   if (!OutFile.good()) {
94     std::cerr << "Error opening bytecode file: " << ChildOutput << "\n";
95     return 1;
96   }
97
98   PassManager PM;
99   // Make sure that the appropriate target data is always used...
100   PM.add(new TargetData("bugpoint", Program));
101
102   for (unsigned i = 0, e = Passes.size(); i != e; ++i) {
103     if (Passes[i]->getNormalCtor())
104       PM.add(Passes[i]->getNormalCtor()());
105     else
106       std::cerr << "Cannot create pass yet: " << Passes[i]->getPassName()
107                 << "\n";
108   }
109   // Check that the module is well formed on completion of optimization
110   PM.add(createVerifierPass());
111
112   // Write bytecode out to disk as the last step...
113   PM.add(new WriteBytecodePass(&OutFile));
114
115   // Run all queued passes.
116   PM.run(*Program);
117
118   return 0;
119 }
120
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
127 /// failed.
128 ///
129 bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes,
130                           std::string &OutputFilename, bool DeleteOutput,
131                           bool Quiet) const{
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();
137
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 |
142                                std::ios::binary;
143   std::ofstream InFile(inputFilename.c_str(), io_mode);
144   if (!InFile.good()) {
145     std::cerr << "Error opening bytecode file: " << inputFilename << "\n";
146     return(1);
147   }
148   WriteBytecodeToFile(Program,InFile,false);
149   InFile.close();
150
151   // setup the child process' arguments
152   const char** args = (const char**)
153     alloca(sizeof(const char*)*(Passes.size()+10));
154   int n = 0;
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();
167   args[n++] = 0;
168
169   sys::Path prog(sys::Program::FindProgramByName(ToolName));
170   int result = sys::Program::ExecuteAndWait(prog,args);
171
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();
176
177   // Remove the temporary input file as well
178   inputFilename.eraseFromDisk();
179
180   if (!Quiet) {
181     if (result == 0)
182       std::cout << "Success!\n";
183     else if (result > 0)
184       std::cout << "Exited with error code '" << result << "'\n";
185     else if (result < 0)
186       std::cout << "Crashed with signal #" << abs(result) << "\n";
187     if (result & 0x01000000)
188       std::cout << "Dumped core\n";
189   }
190
191   // Was the child successful?
192   return result != 0;
193 }
194
195
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
198 /// failure.
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";
208       delete OldProgram;
209       EmitProgressBytecode("pass-error",  false);
210       exit(debugOptimizerCrash());
211     }
212     swapProgramIn(OldProgram);
213     return 0;
214   }
215
216   // Restore the current program.
217   swapProgramIn(OldProgram);
218
219   Module *Ret = ParseInputFile(BytecodeResult);
220   if (Ret == 0) {
221     std::cerr << getToolName() << ": Error reading bytecode file '"
222               << BytecodeResult << "'!\n";
223     exit(1);
224   }
225   sys::Path(BytecodeResult).eraseFromDisk();  // No longer need the file on disk
226   return Ret;
227 }