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