add explicit #includes of iostream
[oota-llvm.git] / tools / bugpoint / ExecutionDriver.cpp
1 //===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
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 contains code used to execute the program utilizing one of the
11 // various ways of running LLVM bytecode.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "BugDriver.h"
16 #include "llvm/Support/ToolRunner.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/SystemUtils.h"
21 #include <fstream>
22 #include <iostream>
23 using namespace llvm;
24
25 namespace {
26   // OutputType - Allow the user to specify the way code should be run, to test
27   // for miscompilation.
28   //
29   enum OutputType {
30     AutoPick, RunLLI, RunJIT, RunLLC, RunCBE
31   };
32
33   cl::opt<double>
34   AbsTolerance("abs-tolerance", cl::desc("Absolute error tolerated"),
35                cl::init(0.0));
36   cl::opt<double>
37   RelTolerance("rel-tolerance", cl::desc("Relative error tolerated"),
38                cl::init(0.0));
39
40   cl::opt<OutputType>
41   InterpreterSel(cl::desc("Specify how LLVM code should be executed:"),
42                  cl::values(clEnumValN(AutoPick, "auto", "Use best guess"),
43                             clEnumValN(RunLLI, "run-int",
44                                        "Execute with the interpreter"),
45                             clEnumValN(RunJIT, "run-jit", "Execute with JIT"),
46                             clEnumValN(RunLLC, "run-llc", "Compile with LLC"),
47                             clEnumValN(RunCBE, "run-cbe", "Compile with CBE"),
48                             clEnumValEnd),
49                  cl::init(AutoPick));
50
51   cl::opt<bool>
52   CheckProgramExitCode("check-exit-code",
53                    cl::desc("Assume nonzero exit code is failure (default on)"),
54                        cl::init(true));
55
56   cl::opt<std::string>
57   InputFile("input", cl::init("/dev/null"),
58             cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
59
60   cl::list<std::string>
61   AdditionalSOs("additional-so",
62                 cl::desc("Additional shared objects to load "
63                          "into executing programs"));
64
65   cl::opt<unsigned>
66   TimeoutValue("timeout", cl::init(300), cl::value_desc("seconds"),
67                cl::desc("Number of seconds program is allowed to run before it "
68                         "is killed (default is 300s), 0 disables timeout"));
69 }
70
71 namespace llvm {
72   // Anything specified after the --args option are taken as arguments to the
73   // program being debugged.
74   cl::list<std::string>
75   InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
76             cl::ZeroOrMore, cl::PositionalEatsArgs);
77
78   cl::list<std::string>
79   ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
80            cl::ZeroOrMore, cl::PositionalEatsArgs);
81 }
82
83 //===----------------------------------------------------------------------===//
84 // BugDriver method implementation
85 //
86
87 /// initializeExecutionEnvironment - This method is used to set up the
88 /// environment for executing LLVM programs.
89 ///
90 bool BugDriver::initializeExecutionEnvironment() {
91   std::cout << "Initializing execution environment: ";
92
93   // Create an instance of the AbstractInterpreter interface as specified on
94   // the command line
95   cbe = 0;
96   std::string Message;
97
98   switch (InterpreterSel) {
99   case AutoPick:
100     InterpreterSel = RunCBE;
101     Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
102                                                        &ToolArgv);
103     if (!Interpreter) {
104       InterpreterSel = RunJIT;
105       Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
106                                                    &ToolArgv);
107     }
108     if (!Interpreter) {
109       InterpreterSel = RunLLC;
110       Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
111                                                    &ToolArgv);
112     }
113     if (!Interpreter) {
114       InterpreterSel = RunLLI;
115       Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
116                                                    &ToolArgv);
117     }
118     if (!Interpreter) {
119       InterpreterSel = AutoPick;
120       Message = "Sorry, I can't automatically select an interpreter!\n";
121     }
122     break;
123   case RunLLI:
124     Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
125                                                  &ToolArgv);
126     break;
127   case RunLLC:
128     Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
129                                                  &ToolArgv);
130     break;
131   case RunJIT:
132     Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
133                                                  &ToolArgv);
134     break;
135   case RunCBE:
136     Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
137                                                        &ToolArgv);
138     break;
139   default:
140     Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
141     break;
142   }
143   std::cerr << Message;
144
145   // Initialize auxiliary tools for debugging
146   if (!cbe) {
147     cbe = AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv);
148     if (!cbe) { std::cout << Message << "\nExiting.\n"; exit(1); }
149   }
150   gcc = GCC::create(getToolName(), Message);
151   if (!gcc) { std::cout << Message << "\nExiting.\n"; exit(1); }
152
153   // If there was an error creating the selected interpreter, quit with error.
154   return Interpreter == 0;
155 }
156
157 /// compileProgram - Try to compile the specified module, throwing an exception
158 /// if an error occurs, or returning normally if not.  This is used for code
159 /// generation crash testing.
160 ///
161 void BugDriver::compileProgram(Module *M) {
162   // Emit the program to a bytecode file...
163   sys::Path BytecodeFile ("bugpoint-test-program.bc");
164   BytecodeFile.makeUnique();
165   if (writeProgramToFile(BytecodeFile.toString(), M)) {
166     std::cerr << ToolName << ": Error emitting bytecode to file '"
167               << BytecodeFile << "'!\n";
168     exit(1);
169   }
170
171     // Remove the temporary bytecode file when we are done.
172   FileRemover BytecodeFileRemover(BytecodeFile);
173
174   // Actually compile the program!
175   Interpreter->compileProgram(BytecodeFile.toString());
176 }
177
178
179 /// executeProgram - This method runs "Program", capturing the output of the
180 /// program to a file, returning the filename of the file.  A recommended
181 /// filename may be optionally specified.
182 ///
183 std::string BugDriver::executeProgram(std::string OutputFile,
184                                       std::string BytecodeFile,
185                                       const std::string &SharedObj,
186                                       AbstractInterpreter *AI,
187                                       bool *ProgramExitedNonzero) {
188   if (AI == 0) AI = Interpreter;
189   assert(AI && "Interpreter should have been created already!");
190   bool CreatedBytecode = false;
191   if (BytecodeFile.empty()) {
192     // Emit the program to a bytecode file...
193     sys::Path uniqueFilename("bugpoint-test-program.bc");
194     uniqueFilename.makeUnique();
195     BytecodeFile = uniqueFilename.toString();
196
197     if (writeProgramToFile(BytecodeFile, Program)) {
198       std::cerr << ToolName << ": Error emitting bytecode to file '"
199                 << BytecodeFile << "'!\n";
200       exit(1);
201     }
202     CreatedBytecode = true;
203   }
204
205   // Remove the temporary bytecode file when we are done.
206   sys::Path BytecodePath (BytecodeFile);
207   FileRemover BytecodeFileRemover(BytecodePath, CreatedBytecode);
208
209   if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";
210
211   // Check to see if this is a valid output filename...
212   sys::Path uniqueFile(OutputFile);
213   uniqueFile.makeUnique();
214   OutputFile = uniqueFile.toString();
215
216   // Figure out which shared objects to run, if any.
217   std::vector<std::string> SharedObjs(AdditionalSOs);
218   if (!SharedObj.empty())
219     SharedObjs.push_back(SharedObj);
220
221   // Actually execute the program!
222   int RetVal = AI->ExecuteProgram(BytecodeFile, InputArgv, InputFile,
223                                   OutputFile, SharedObjs, TimeoutValue);
224
225   if (RetVal == -1) {
226     std::cerr << "<timeout>";
227     static bool FirstTimeout = true;
228     if (FirstTimeout) {
229       std::cout << "\n"
230  "*** Program execution timed out!  This mechanism is designed to handle\n"
231  "    programs stuck in infinite loops gracefully.  The -timeout option\n"
232  "    can be used to change the timeout threshold or disable it completely\n"
233  "    (with -timeout=0).  This message is only displayed once.\n";
234       FirstTimeout = false;
235     }
236   }
237
238   if (ProgramExitedNonzero != 0)
239     *ProgramExitedNonzero = (RetVal != 0);
240
241   // Return the filename we captured the output to.
242   return OutputFile;
243 }
244
245 /// executeProgramWithCBE - Used to create reference output with the C
246 /// backend, if reference output is not provided.
247 ///
248 std::string BugDriver::executeProgramWithCBE(std::string OutputFile) {
249   bool ProgramExitedNonzero;
250   std::string outFN = executeProgram(OutputFile, "", "",
251                                      (AbstractInterpreter*)cbe,
252                                      &ProgramExitedNonzero);
253   if (ProgramExitedNonzero) {
254     std::cerr
255       << "Warning: While generating reference output, program exited with\n"
256       << "non-zero exit code. This will NOT be treated as a failure.\n";
257     CheckProgramExitCode = false;
258   }
259   return outFN;
260 }
261
262 std::string BugDriver::compileSharedObject(const std::string &BytecodeFile) {
263   assert(Interpreter && "Interpreter should have been created already!");
264   sys::Path OutputCFile;
265
266   // Using CBE
267   cbe->OutputC(BytecodeFile, OutputCFile);
268
269 #if 0 /* This is an alternative, as yet unimplemented */
270   // Using LLC
271   std::string Message;
272   LLC *llc = createLLCtool(Message);
273   if (llc->OutputAsm(BytecodeFile, OutputFile)) {
274     std::cerr << "Could not generate asm code with `llc', exiting.\n";
275     exit(1);
276   }
277 #endif
278
279   std::string SharedObjectFile;
280   if (gcc->MakeSharedObject(OutputCFile.toString(), GCC::CFile,
281                             SharedObjectFile))
282     exit(1);
283
284   // Remove the intermediate C file
285   OutputCFile.eraseFromDisk();
286
287   return "./" + SharedObjectFile;
288 }
289
290
291 /// diffProgram - This method executes the specified module and diffs the output
292 /// against the file specified by ReferenceOutputFile.  If the output is
293 /// different, true is returned.
294 ///
295 bool BugDriver::diffProgram(const std::string &BytecodeFile,
296                             const std::string &SharedObject,
297                             bool RemoveBytecode) {
298   bool ProgramExitedNonzero;
299
300   // Execute the program, generating an output file...
301   sys::Path Output (executeProgram("", BytecodeFile, SharedObject, 0,
302                                       &ProgramExitedNonzero));
303
304   // If we're checking the program exit code, assume anything nonzero is bad.
305   if (CheckProgramExitCode && ProgramExitedNonzero) {
306     Output.eraseFromDisk();
307     if (RemoveBytecode)
308       sys::Path(BytecodeFile).eraseFromDisk();
309     return true;
310   }
311
312   std::string Error;
313   bool FilesDifferent = false;
314   if (int Diff = DiffFilesWithTolerance(sys::Path(ReferenceOutputFile),
315                                         sys::Path(Output.toString()),
316                                         AbsTolerance, RelTolerance, &Error)) {
317     if (Diff == 2) {
318       std::cerr << "While diffing output: " << Error << '\n';
319       exit(1);
320     }
321     FilesDifferent = true;
322   }
323
324   // Remove the generated output.
325   Output.eraseFromDisk();
326
327   // Remove the bytecode file if we are supposed to.
328   if (RemoveBytecode)
329     sys::Path(BytecodeFile).eraseFromDisk();
330   return FilesDifferent;
331 }
332
333 bool BugDriver::isExecutingJIT() {
334   return InterpreterSel == RunJIT;
335 }
336