1 //===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains code used to execute the program utilizing one of the
11 // various ways of running LLVM bitcode.
13 //===----------------------------------------------------------------------===//
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"
27 // OutputType - Allow the user to specify the way code should be run, to test
28 // for miscompilation.
31 AutoPick, RunLLI, RunJIT, RunLLC, RunLLCIA, RunCBE, CBE_bug, LLC_Safe,
36 AbsTolerance("abs-tolerance", cl::desc("Absolute error tolerated"),
39 RelTolerance("rel-tolerance", cl::desc("Relative error tolerated"),
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(RunCBE, "run-cbe", "Compile with CBE"),
52 clEnumValN(CBE_bug,"cbe-bug", "Find CBE bugs"),
53 clEnumValN(LLC_Safe, "llc-safe", "Use LLC for all"),
54 clEnumValN(CompileCustom, "compile-custom",
55 "Use -compile-command to define a command to "
56 "compile the bitcode. Useful to avoid linking."),
57 clEnumValN(Custom, "run-custom",
58 "Use -exec-command to define a command to execute "
59 "the bitcode. Useful for cross-compilation."),
64 SafeInterpreterSel(cl::desc("Specify \"safe\" i.e. known-good backend:"),
65 cl::values(clEnumValN(AutoPick, "safe-auto", "Use best guess"),
66 clEnumValN(RunLLC, "safe-run-llc", "Compile with LLC"),
67 clEnumValN(RunCBE, "safe-run-cbe", "Compile with CBE"),
68 clEnumValN(Custom, "safe-run-custom",
69 "Use -exec-command to define a command to execute "
70 "the bitcode. Useful for cross-compilation."),
75 SafeInterpreterPath("safe-path",
76 cl::desc("Specify the path to the \"safe\" backend program"),
80 AppendProgramExitCode("append-exit-code",
81 cl::desc("Append the exit code to the output so it gets diff'd too"),
85 InputFile("input", cl::init("/dev/null"),
86 cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
89 AdditionalSOs("additional-so",
90 cl::desc("Additional shared objects to load "
91 "into executing programs"));
94 AdditionalLinkerArgs("Xlinker",
95 cl::desc("Additional arguments to pass to the linker"));
98 CustomCompileCommand("compile-command", cl::init("llc"),
99 cl::desc("Command to compile the bitcode (use with -compile-custom) "
103 CustomExecCommand("exec-command", cl::init("simulate"),
104 cl::desc("Command to execute the bitcode (use with -run-custom) "
105 "(default: simulate)"));
109 // Anything specified after the --args option are taken as arguments to the
110 // program being debugged.
111 cl::list<std::string>
112 InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
113 cl::ZeroOrMore, cl::PositionalEatsArgs);
116 OutputPrefix("output-prefix", cl::init("bugpoint"),
117 cl::desc("Prefix to use for outputs (default: 'bugpoint')"));
121 cl::list<std::string>
122 ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
123 cl::ZeroOrMore, cl::PositionalEatsArgs);
125 cl::list<std::string>
126 SafeToolArgv("safe-tool-args", cl::Positional,
127 cl::desc("<safe-tool arguments>..."),
128 cl::ZeroOrMore, cl::PositionalEatsArgs);
131 GCCBinary("gcc", cl::init("gcc"),
132 cl::desc("The gcc binary to use. (default 'gcc')"));
134 cl::list<std::string>
135 GCCToolArgv("gcc-tool-args", cl::Positional,
136 cl::desc("<gcc-tool arguments>..."),
137 cl::ZeroOrMore, cl::PositionalEatsArgs);
140 //===----------------------------------------------------------------------===//
141 // BugDriver method implementation
144 /// initializeExecutionEnvironment - This method is used to set up the
145 /// environment for executing LLVM programs.
147 bool BugDriver::initializeExecutionEnvironment() {
148 outs() << "Initializing execution environment: ";
150 // Create an instance of the AbstractInterpreter interface as specified on
155 switch (InterpreterSel) {
157 InterpreterSel = RunCBE;
159 AbstractInterpreter::createCBE(getToolName(), Message, GCCBinary,
160 &ToolArgv, &GCCToolArgv);
162 InterpreterSel = RunJIT;
163 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
167 InterpreterSel = RunLLC;
168 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
169 GCCBinary, &ToolArgv,
173 InterpreterSel = RunLLI;
174 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
178 InterpreterSel = AutoPick;
179 Message = "Sorry, I can't automatically select an interpreter!\n";
183 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
189 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
190 GCCBinary, &ToolArgv,
192 InterpreterSel == RunLLCIA);
195 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
200 Interpreter = AbstractInterpreter::createCBE(getToolName(), Message,
201 GCCBinary, &ToolArgv,
206 AbstractInterpreter::createCustomCompiler(Message, CustomCompileCommand);
210 AbstractInterpreter::createCustomExecutor(Message, CustomExecCommand);
215 else // Display informational messages on stdout instead of stderr
218 std::string Path = SafeInterpreterPath;
220 Path = getToolName();
221 std::vector<std::string> SafeToolArgs = SafeToolArgv;
222 switch (SafeInterpreterSel) {
224 // In "cbe-bug" mode, default to using LLC as the "safe" backend.
225 if (!SafeInterpreter &&
226 InterpreterSel == CBE_bug) {
227 SafeInterpreterSel = RunLLC;
228 SafeToolArgs.push_back("--relocation-model=pic");
229 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
235 // In "llc-safe" mode, default to using LLC as the "safe" backend.
236 if (!SafeInterpreter &&
237 InterpreterSel == LLC_Safe) {
238 SafeInterpreterSel = RunLLC;
239 SafeToolArgs.push_back("--relocation-model=pic");
240 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
246 // Pick a backend that's different from the test backend. The JIT and
247 // LLC backends share a lot of code, so prefer to use the CBE as the
248 // safe back-end when testing them.
249 if (!SafeInterpreter &&
250 InterpreterSel != RunCBE) {
251 SafeInterpreterSel = RunCBE;
252 SafeInterpreter = AbstractInterpreter::createCBE(Path.c_str(), Message,
257 if (!SafeInterpreter &&
258 InterpreterSel != RunLLC &&
259 InterpreterSel != RunJIT) {
260 SafeInterpreterSel = RunLLC;
261 SafeToolArgs.push_back("--relocation-model=pic");
262 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
267 if (!SafeInterpreter) {
268 SafeInterpreterSel = AutoPick;
269 Message = "Sorry, I can't automatically select an interpreter!\n";
274 SafeToolArgs.push_back("--relocation-model=pic");
275 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
276 GCCBinary, &SafeToolArgs,
278 SafeInterpreterSel == RunLLCIA);
281 SafeInterpreter = AbstractInterpreter::createCBE(Path.c_str(), Message,
282 GCCBinary, &SafeToolArgs,
287 AbstractInterpreter::createCustomExecutor(Message, CustomExecCommand);
290 Message = "Sorry, this back-end is not supported by bugpoint as the "
291 "\"safe\" backend right now!\n";
294 if (!SafeInterpreter) { outs() << Message << "\nExiting.\n"; exit(1); }
296 gcc = GCC::create(Message, GCCBinary, &GCCToolArgv);
297 if (!gcc) { outs() << Message << "\nExiting.\n"; exit(1); }
299 // If there was an error creating the selected interpreter, quit with error.
300 return Interpreter == 0;
303 /// compileProgram - Try to compile the specified module, returning false and
304 /// setting Error if an error occurs. This is used for code generation
307 void BugDriver::compileProgram(Module *M, std::string *Error) const {
308 // Emit the program to a bitcode file...
309 sys::Path BitcodeFile (OutputPrefix + "-test-program.bc");
311 if (BitcodeFile.makeUnique(true, &ErrMsg)) {
312 errs() << ToolName << ": Error making unique filename: " << ErrMsg
316 if (writeProgramToFile(BitcodeFile.str(), M)) {
317 errs() << ToolName << ": Error emitting bitcode to file '"
318 << BitcodeFile.str() << "'!\n";
322 // Remove the temporary bitcode file when we are done.
323 FileRemover BitcodeFileRemover(BitcodeFile.str(), !SaveTemps);
325 // Actually compile the program!
326 Interpreter->compileProgram(BitcodeFile.str(), Error, Timeout, MemoryLimit);
330 /// executeProgram - This method runs "Program", capturing the output of the
331 /// program to a file, returning the filename of the file. A recommended
332 /// filename may be optionally specified.
334 std::string BugDriver::executeProgram(const Module *Program,
335 std::string OutputFile,
336 std::string BitcodeFile,
337 const std::string &SharedObj,
338 AbstractInterpreter *AI,
339 std::string *Error) const {
340 if (AI == 0) AI = Interpreter;
341 assert(AI && "Interpreter should have been created already!");
342 bool CreatedBitcode = false;
344 if (BitcodeFile.empty()) {
345 // Emit the program to a bitcode file...
346 sys::Path uniqueFilename(OutputPrefix + "-test-program.bc");
347 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
348 errs() << ToolName << ": Error making unique filename: "
352 BitcodeFile = uniqueFilename.str();
354 if (writeProgramToFile(BitcodeFile, Program)) {
355 errs() << ToolName << ": Error emitting bitcode to file '"
356 << BitcodeFile << "'!\n";
359 CreatedBitcode = true;
362 // Remove the temporary bitcode file when we are done.
363 sys::Path BitcodePath(BitcodeFile);
364 FileRemover BitcodeFileRemover(BitcodePath.str(),
365 CreatedBitcode && !SaveTemps);
367 if (OutputFile.empty()) OutputFile = OutputPrefix + "-execution-output";
369 // Check to see if this is a valid output filename...
370 sys::Path uniqueFile(OutputFile);
371 if (uniqueFile.makeUnique(true, &ErrMsg)) {
372 errs() << ToolName << ": Error making unique filename: "
376 OutputFile = uniqueFile.str();
378 // Figure out which shared objects to run, if any.
379 std::vector<std::string> SharedObjs(AdditionalSOs);
380 if (!SharedObj.empty())
381 SharedObjs.push_back(SharedObj);
383 int RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile, OutputFile,
384 Error, AdditionalLinkerArgs, SharedObjs,
385 Timeout, MemoryLimit);
390 errs() << "<timeout>";
391 static bool FirstTimeout = true;
394 "*** Program execution timed out! This mechanism is designed to handle\n"
395 " programs stuck in infinite loops gracefully. The -timeout option\n"
396 " can be used to change the timeout threshold or disable it completely\n"
397 " (with -timeout=0). This message is only displayed once.\n";
398 FirstTimeout = false;
402 if (AppendProgramExitCode) {
403 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
404 outFile << "exit " << RetVal << '\n';
408 // Return the filename we captured the output to.
412 /// executeProgramSafely - Used to create reference output with the "safe"
413 /// backend, if reference output is not provided.
415 std::string BugDriver::executeProgramSafely(const Module *Program,
416 std::string OutputFile,
417 std::string *Error) const {
418 return executeProgram(Program, OutputFile, "", "", SafeInterpreter, Error);
421 std::string BugDriver::compileSharedObject(const std::string &BitcodeFile,
422 std::string &Error) {
423 assert(Interpreter && "Interpreter should have been created already!");
424 sys::Path OutputFile;
426 // Using the known-good backend.
427 GCC::FileType FT = SafeInterpreter->OutputCode(BitcodeFile, OutputFile,
432 std::string SharedObjectFile;
433 bool Failure = gcc->MakeSharedObject(OutputFile.str(), FT, SharedObjectFile,
434 AdditionalLinkerArgs, Error);
440 // Remove the intermediate C file
441 OutputFile.eraseFromDisk();
443 return "./" + SharedObjectFile;
446 /// createReferenceFile - calls compileProgram and then records the output
447 /// into ReferenceOutputFile. Returns true if reference file created, false
448 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
451 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
453 compileProgram(Program, &Error);
457 ReferenceOutputFile = executeProgramSafely(Program, Filename, &Error);
458 if (!Error.empty()) {
460 if (Interpreter != SafeInterpreter) {
461 errs() << "*** There is a bug running the \"safe\" backend. Either"
462 << " debug it (for example with the -run-cbe bugpoint option,"
463 << " if CBE is being used as the \"safe\" backend), or fix the"
464 << " error some other way.\n";
468 outs() << "\nReference output is: " << ReferenceOutputFile << "\n\n";
472 /// diffProgram - This method executes the specified module and diffs the
473 /// output against the file specified by ReferenceOutputFile. If the output
474 /// is different, 1 is returned. If there is a problem with the code
475 /// generator (e.g., llc crashes), this will set ErrMsg.
477 bool BugDriver::diffProgram(const Module *Program,
478 const std::string &BitcodeFile,
479 const std::string &SharedObject,
481 std::string *ErrMsg) const {
482 // Execute the program, generating an output file...
483 sys::Path Output(executeProgram(Program, "", BitcodeFile, SharedObject, 0,
485 if (!ErrMsg->empty())
489 bool FilesDifferent = false;
490 if (int Diff = DiffFilesWithTolerance(sys::Path(ReferenceOutputFile),
491 sys::Path(Output.str()),
492 AbsTolerance, RelTolerance, &Error)) {
494 errs() << "While diffing output: " << Error << '\n';
497 FilesDifferent = true;
500 // Remove the generated output if there are no differences.
501 Output.eraseFromDisk();
504 // Remove the bitcode file if we are supposed to.
506 sys::Path(BitcodeFile).eraseFromDisk();
507 return FilesDifferent;
510 bool BugDriver::isExecutingJIT() {
511 return InterpreterSel == RunJIT;