Don't use 'using std::error_code' in include/llvm.
[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 is distributed under the University of Illinois Open Source
6 // 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 bitcode.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "BugDriver.h"
16 #include "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 "llvm/Support/raw_ostream.h"
22 #include <fstream>
23
24 using namespace llvm;
25 using std::error_code;
26
27 namespace {
28   // OutputType - Allow the user to specify the way code should be run, to test
29   // for miscompilation.
30   //
31   enum OutputType {
32     AutoPick, RunLLI, RunJIT, RunLLC, RunLLCIA, LLC_Safe, CompileCustom, Custom
33   };
34
35   cl::opt<double>
36   AbsTolerance("abs-tolerance", cl::desc("Absolute error tolerated"),
37                cl::init(0.0));
38   cl::opt<double>
39   RelTolerance("rel-tolerance", cl::desc("Relative error tolerated"),
40                cl::init(0.0));
41
42   cl::opt<OutputType>
43   InterpreterSel(cl::desc("Specify the \"test\" i.e. suspect back-end:"),
44                  cl::values(clEnumValN(AutoPick, "auto", "Use best guess"),
45                             clEnumValN(RunLLI, "run-int",
46                                        "Execute with the interpreter"),
47                             clEnumValN(RunJIT, "run-jit", "Execute with JIT"),
48                             clEnumValN(RunLLC, "run-llc", "Compile with LLC"),
49                             clEnumValN(RunLLCIA, "run-llc-ia",
50                                   "Compile with LLC with integrated assembler"),
51                             clEnumValN(LLC_Safe, "llc-safe", "Use LLC for all"),
52                             clEnumValN(CompileCustom, "compile-custom",
53                             "Use -compile-command to define a command to "
54                             "compile the bitcode. Useful to avoid linking."),
55                             clEnumValN(Custom, "run-custom",
56                             "Use -exec-command to define a command to execute "
57                             "the bitcode. Useful for cross-compilation."),
58                             clEnumValEnd),
59                  cl::init(AutoPick));
60
61   cl::opt<OutputType>
62   SafeInterpreterSel(cl::desc("Specify \"safe\" i.e. known-good backend:"),
63               cl::values(clEnumValN(AutoPick, "safe-auto", "Use best guess"),
64                          clEnumValN(RunLLC, "safe-run-llc", "Compile with LLC"),
65                          clEnumValN(Custom, "safe-run-custom",
66                          "Use -exec-command to define a command to execute "
67                          "the bitcode. Useful for cross-compilation."),
68                          clEnumValEnd),
69                      cl::init(AutoPick));
70
71   cl::opt<std::string>
72   SafeInterpreterPath("safe-path",
73                    cl::desc("Specify the path to the \"safe\" backend program"),
74                    cl::init(""));
75
76   cl::opt<bool>
77   AppendProgramExitCode("append-exit-code",
78       cl::desc("Append the exit code to the output so it gets diff'd too"),
79       cl::init(false));
80
81   cl::opt<std::string>
82   InputFile("input", cl::init("/dev/null"),
83             cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
84
85   cl::list<std::string>
86   AdditionalSOs("additional-so",
87                 cl::desc("Additional shared objects to load "
88                          "into executing programs"));
89
90   cl::list<std::string>
91   AdditionalLinkerArgs("Xlinker",
92       cl::desc("Additional arguments to pass to the linker"));
93
94   cl::opt<std::string>
95   CustomCompileCommand("compile-command", cl::init("llc"),
96       cl::desc("Command to compile the bitcode (use with -compile-custom) "
97                "(default: llc)"));
98
99   cl::opt<std::string>
100   CustomExecCommand("exec-command", cl::init("simulate"),
101       cl::desc("Command to execute the bitcode (use with -run-custom) "
102                "(default: simulate)"));
103 }
104
105 namespace llvm {
106   // Anything specified after the --args option are taken as arguments to the
107   // program being debugged.
108   cl::list<std::string>
109   InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
110             cl::ZeroOrMore, cl::PositionalEatsArgs);
111
112   cl::opt<std::string>
113   OutputPrefix("output-prefix", cl::init("bugpoint"),
114             cl::desc("Prefix to use for outputs (default: 'bugpoint')"));
115 }
116
117 namespace {
118   cl::list<std::string>
119   ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
120            cl::ZeroOrMore, cl::PositionalEatsArgs);
121
122   cl::list<std::string>
123   SafeToolArgv("safe-tool-args", cl::Positional,
124                cl::desc("<safe-tool arguments>..."),
125                cl::ZeroOrMore, cl::PositionalEatsArgs);
126
127   cl::opt<std::string>
128   GCCBinary("gcc", cl::init("gcc"),
129               cl::desc("The gcc binary to use. (default 'gcc')"));
130
131   cl::list<std::string>
132   GCCToolArgv("gcc-tool-args", cl::Positional,
133               cl::desc("<gcc-tool arguments>..."),
134               cl::ZeroOrMore, cl::PositionalEatsArgs);
135 }
136
137 //===----------------------------------------------------------------------===//
138 // BugDriver method implementation
139 //
140
141 /// initializeExecutionEnvironment - This method is used to set up the
142 /// environment for executing LLVM programs.
143 ///
144 bool BugDriver::initializeExecutionEnvironment() {
145   outs() << "Initializing execution environment: ";
146
147   // Create an instance of the AbstractInterpreter interface as specified on
148   // the command line
149   SafeInterpreter = nullptr;
150   std::string Message;
151
152   switch (InterpreterSel) {
153   case AutoPick:
154     if (!Interpreter) {
155       InterpreterSel = RunJIT;
156       Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
157                                                    &ToolArgv);
158     }
159     if (!Interpreter) {
160       InterpreterSel = RunLLC;
161       Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
162                                                    GCCBinary, &ToolArgv,
163                                                    &GCCToolArgv);
164     }
165     if (!Interpreter) {
166       InterpreterSel = RunLLI;
167       Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
168                                                    &ToolArgv);
169     }
170     if (!Interpreter) {
171       InterpreterSel = AutoPick;
172       Message = "Sorry, I can't automatically select an interpreter!\n";
173     }
174     break;
175   case RunLLI:
176     Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
177                                                  &ToolArgv);
178     break;
179   case RunLLC:
180   case RunLLCIA:
181   case LLC_Safe:
182     Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
183                                                  GCCBinary, &ToolArgv,
184                                                  &GCCToolArgv,
185                                                  InterpreterSel == RunLLCIA);
186     break;
187   case RunJIT:
188     Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
189                                                  &ToolArgv);
190     break;
191   case CompileCustom:
192     Interpreter =
193       AbstractInterpreter::createCustomCompiler(Message, CustomCompileCommand);
194     break;
195   case Custom:
196     Interpreter =
197       AbstractInterpreter::createCustomExecutor(Message, CustomExecCommand);
198     break;
199   }
200   if (!Interpreter)
201     errs() << Message;
202   else // Display informational messages on stdout instead of stderr
203     outs() << Message;
204
205   std::string Path = SafeInterpreterPath;
206   if (Path.empty())
207     Path = getToolName();
208   std::vector<std::string> SafeToolArgs = SafeToolArgv;
209   switch (SafeInterpreterSel) {
210   case AutoPick:
211     // In "llc-safe" mode, default to using LLC as the "safe" backend.
212     if (!SafeInterpreter &&
213         InterpreterSel == LLC_Safe) {
214       SafeInterpreterSel = RunLLC;
215       SafeToolArgs.push_back("--relocation-model=pic");
216       SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
217                                                        GCCBinary,
218                                                        &SafeToolArgs,
219                                                        &GCCToolArgv);
220     }
221
222     if (!SafeInterpreter &&
223         InterpreterSel != RunLLC &&
224         InterpreterSel != RunJIT) {
225       SafeInterpreterSel = RunLLC;
226       SafeToolArgs.push_back("--relocation-model=pic");
227       SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
228                                                        GCCBinary,
229                                                        &SafeToolArgs,
230                                                        &GCCToolArgv);
231     }
232     if (!SafeInterpreter) {
233       SafeInterpreterSel = AutoPick;
234       Message = "Sorry, I can't automatically select a safe interpreter!\n";
235     }
236     break;
237   case RunLLC:
238   case RunLLCIA:
239     SafeToolArgs.push_back("--relocation-model=pic");
240     SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
241                                                      GCCBinary, &SafeToolArgs,
242                                                      &GCCToolArgv,
243                                                 SafeInterpreterSel == RunLLCIA);
244     break;
245   case Custom:
246     SafeInterpreter =
247       AbstractInterpreter::createCustomExecutor(Message, CustomExecCommand);
248     break;
249   default:
250     Message = "Sorry, this back-end is not supported by bugpoint as the "
251               "\"safe\" backend right now!\n";
252     break;
253   }
254   if (!SafeInterpreter) { outs() << Message << "\nExiting.\n"; exit(1); }
255
256   gcc = GCC::create(Message, GCCBinary, &GCCToolArgv);
257   if (!gcc) { outs() << Message << "\nExiting.\n"; exit(1); }
258
259   // If there was an error creating the selected interpreter, quit with error.
260   return Interpreter == nullptr;
261 }
262
263 /// compileProgram - Try to compile the specified module, returning false and
264 /// setting Error if an error occurs.  This is used for code generation
265 /// crash testing.
266 ///
267 void BugDriver::compileProgram(Module *M, std::string *Error) const {
268   // Emit the program to a bitcode file...
269   SmallString<128> BitcodeFile;
270   int BitcodeFD;
271   error_code EC = sys::fs::createUniqueFile(
272       OutputPrefix + "-test-program-%%%%%%%.bc", BitcodeFD, BitcodeFile);
273   if (EC) {
274     errs() << ToolName << ": Error making unique filename: " << EC.message()
275            << "\n";
276     exit(1);
277   }
278   if (writeProgramToFile(BitcodeFile.str(), BitcodeFD, M)) {
279     errs() << ToolName << ": Error emitting bitcode to file '" << BitcodeFile
280            << "'!\n";
281     exit(1);
282   }
283
284   // Remove the temporary bitcode file when we are done.
285   FileRemover BitcodeFileRemover(BitcodeFile.str(), !SaveTemps);
286
287   // Actually compile the program!
288   Interpreter->compileProgram(BitcodeFile.str(), Error, Timeout, MemoryLimit);
289 }
290
291
292 /// executeProgram - This method runs "Program", capturing the output of the
293 /// program to a file, returning the filename of the file.  A recommended
294 /// filename may be optionally specified.
295 ///
296 std::string BugDriver::executeProgram(const Module *Program,
297                                       std::string OutputFile,
298                                       std::string BitcodeFile,
299                                       const std::string &SharedObj,
300                                       AbstractInterpreter *AI,
301                                       std::string *Error) const {
302   if (!AI) AI = Interpreter;
303   assert(AI && "Interpreter should have been created already!");
304   bool CreatedBitcode = false;
305   if (BitcodeFile.empty()) {
306     // Emit the program to a bitcode file...
307     SmallString<128> UniqueFilename;
308     int UniqueFD;
309     error_code EC = sys::fs::createUniqueFile(
310         OutputPrefix + "-test-program-%%%%%%%.bc", UniqueFD, UniqueFilename);
311     if (EC) {
312       errs() << ToolName << ": Error making unique filename: "
313              << EC.message() << "!\n";
314       exit(1);
315     }
316     BitcodeFile = UniqueFilename.str();
317
318     if (writeProgramToFile(BitcodeFile, UniqueFD, Program)) {
319       errs() << ToolName << ": Error emitting bitcode to file '"
320              << BitcodeFile << "'!\n";
321       exit(1);
322     }
323     CreatedBitcode = true;
324   }
325
326   // Remove the temporary bitcode file when we are done.
327   std::string BitcodePath(BitcodeFile);
328   FileRemover BitcodeFileRemover(BitcodePath,
329     CreatedBitcode && !SaveTemps);
330
331   if (OutputFile.empty()) OutputFile = OutputPrefix + "-execution-output-%%%%%%%";
332
333   // Check to see if this is a valid output filename...
334   SmallString<128> UniqueFile;
335   error_code EC = sys::fs::createUniqueFile(OutputFile, UniqueFile);
336   if (EC) {
337     errs() << ToolName << ": Error making unique filename: "
338            << EC.message() << "\n";
339     exit(1);
340   }
341   OutputFile = UniqueFile.str();
342
343   // Figure out which shared objects to run, if any.
344   std::vector<std::string> SharedObjs(AdditionalSOs);
345   if (!SharedObj.empty())
346     SharedObjs.push_back(SharedObj);
347
348   int RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile, OutputFile,
349                                   Error, AdditionalLinkerArgs, SharedObjs,
350                                   Timeout, MemoryLimit);
351   if (!Error->empty())
352     return OutputFile;
353
354   if (RetVal == -1) {
355     errs() << "<timeout>";
356     static bool FirstTimeout = true;
357     if (FirstTimeout) {
358       outs() << "\n"
359  "*** Program execution timed out!  This mechanism is designed to handle\n"
360  "    programs stuck in infinite loops gracefully.  The -timeout option\n"
361  "    can be used to change the timeout threshold or disable it completely\n"
362  "    (with -timeout=0).  This message is only displayed once.\n";
363       FirstTimeout = false;
364     }
365   }
366
367   if (AppendProgramExitCode) {
368     std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
369     outFile << "exit " << RetVal << '\n';
370     outFile.close();
371   }
372
373   // Return the filename we captured the output to.
374   return OutputFile;
375 }
376
377 /// executeProgramSafely - Used to create reference output with the "safe"
378 /// backend, if reference output is not provided.
379 ///
380 std::string BugDriver::executeProgramSafely(const Module *Program,
381                                             std::string OutputFile,
382                                             std::string *Error) const {
383   return executeProgram(Program, OutputFile, "", "", SafeInterpreter, Error);
384 }
385
386 std::string BugDriver::compileSharedObject(const std::string &BitcodeFile,
387                                            std::string &Error) {
388   assert(Interpreter && "Interpreter should have been created already!");
389   std::string OutputFile;
390
391   // Using the known-good backend.
392   GCC::FileType FT = SafeInterpreter->OutputCode(BitcodeFile, OutputFile,
393                                                  Error);
394   if (!Error.empty())
395     return "";
396
397   std::string SharedObjectFile;
398   bool Failure = gcc->MakeSharedObject(OutputFile, FT, SharedObjectFile,
399                                        AdditionalLinkerArgs, Error);
400   if (!Error.empty())
401     return "";
402   if (Failure)
403     exit(1);
404
405   // Remove the intermediate C file
406   sys::fs::remove(OutputFile);
407
408   return SharedObjectFile;
409 }
410
411 /// createReferenceFile - calls compileProgram and then records the output
412 /// into ReferenceOutputFile. Returns true if reference file created, false
413 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
414 /// this function.
415 ///
416 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
417   std::string Error;
418   compileProgram(Program, &Error);
419   if (!Error.empty())
420     return false;
421
422   ReferenceOutputFile = executeProgramSafely(Program, Filename, &Error);
423   if (!Error.empty()) {
424     errs() << Error;
425     if (Interpreter != SafeInterpreter) {
426       errs() << "*** There is a bug running the \"safe\" backend.  Either"
427              << " debug it (for example with the -run-jit bugpoint option,"
428              << " if JIT is being used as the \"safe\" backend), or fix the"
429              << " error some other way.\n";
430     }
431     return false;
432   }
433   outs() << "\nReference output is: " << ReferenceOutputFile << "\n\n";
434   return true;
435 }
436
437 /// diffProgram - This method executes the specified module and diffs the
438 /// output against the file specified by ReferenceOutputFile.  If the output
439 /// is different, 1 is returned.  If there is a problem with the code
440 /// generator (e.g., llc crashes), this will set ErrMsg.
441 ///
442 bool BugDriver::diffProgram(const Module *Program,
443                             const std::string &BitcodeFile,
444                             const std::string &SharedObject,
445                             bool RemoveBitcode,
446                             std::string *ErrMsg) const {
447   // Execute the program, generating an output file...
448   std::string Output(
449       executeProgram(Program, "", BitcodeFile, SharedObject, nullptr, ErrMsg));
450   if (!ErrMsg->empty())
451     return false;
452
453   std::string Error;
454   bool FilesDifferent = false;
455   if (int Diff = DiffFilesWithTolerance(ReferenceOutputFile,
456                                         Output,
457                                         AbsTolerance, RelTolerance, &Error)) {
458     if (Diff == 2) {
459       errs() << "While diffing output: " << Error << '\n';
460       exit(1);
461     }
462     FilesDifferent = true;
463   }
464   else {
465     // Remove the generated output if there are no differences.
466     sys::fs::remove(Output);
467   }
468
469   // Remove the bitcode file if we are supposed to.
470   if (RemoveBitcode)
471     sys::fs::remove(BitcodeFile);
472   return FilesDifferent;
473 }
474
475 bool BugDriver::isExecutingJIT() {
476   return InterpreterSel == RunJIT;
477 }
478