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