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"
26 // OutputType - Allow the user to specify the way code should be run, to test
27 // for miscompilation.
30 AutoPick, RunLLI, RunJIT, RunLLC, RunCBE, CBE_bug, LLC_Safe, Custom
34 AbsTolerance("abs-tolerance", cl::desc("Absolute error tolerated"),
37 RelTolerance("rel-tolerance", cl::desc("Relative error tolerated"),
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."),
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."),
68 SafeInterpreterPath("safe-path",
69 cl::desc("Specify the path to the \"safe\" backend program"),
73 AppendProgramExitCode("append-exit-code",
74 cl::desc("Append the exit code to the output so it gets diff'd too"),
78 InputFile("input", cl::init("/dev/null"),
79 cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
82 AdditionalSOs("additional-so",
83 cl::desc("Additional shared objects to load "
84 "into executing programs"));
87 AdditionalLinkerArgs("Xlinker",
88 cl::desc("Additional arguments to pass to the linker"));
91 CustomExecCommand("exec-command", cl::init("simulate"),
92 cl::desc("Command to execute the bitcode (use with -run-custom) "
93 "(default: simulate)"));
97 // Anything specified after the --args option are taken as arguments to the
98 // program being debugged.
100 InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
101 cl::ZeroOrMore, cl::PositionalEatsArgs);
105 cl::list<std::string>
106 ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
107 cl::ZeroOrMore, cl::PositionalEatsArgs);
109 cl::list<std::string>
110 SafeToolArgv("safe-tool-args", cl::Positional,
111 cl::desc("<safe-tool arguments>..."),
112 cl::ZeroOrMore, cl::PositionalEatsArgs);
114 cl::list<std::string>
115 GCCToolArgv("gcc-tool-args", cl::Positional,
116 cl::desc("<gcc-tool arguments>..."),
117 cl::ZeroOrMore, cl::PositionalEatsArgs);
120 //===----------------------------------------------------------------------===//
121 // BugDriver method implementation
124 /// initializeExecutionEnvironment - This method is used to set up the
125 /// environment for executing LLVM programs.
127 bool BugDriver::initializeExecutionEnvironment() {
128 outs() << "Initializing execution environment: ";
130 // Create an instance of the AbstractInterpreter interface as specified on
135 switch (InterpreterSel) {
137 InterpreterSel = RunCBE;
139 AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv,
142 InterpreterSel = RunJIT;
143 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
147 InterpreterSel = RunLLC;
148 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
149 &ToolArgv, &GCCToolArgv);
152 InterpreterSel = RunLLI;
153 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
157 InterpreterSel = AutoPick;
158 Message = "Sorry, I can't automatically select an interpreter!\n";
162 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
167 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
168 &ToolArgv, &GCCToolArgv);
171 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
176 Interpreter = AbstractInterpreter::createCBE(getToolName(), Message,
177 &ToolArgv, &GCCToolArgv);
180 Interpreter = AbstractInterpreter::createCustom(Message, CustomExecCommand);
183 Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
188 else // Display informational messages on stdout instead of stderr
191 std::string Path = SafeInterpreterPath;
193 Path = getToolName();
194 std::vector<std::string> SafeToolArgs = SafeToolArgv;
195 switch (SafeInterpreterSel) {
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,
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,
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,
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,
236 if (!SafeInterpreter) {
237 SafeInterpreterSel = AutoPick;
238 Message = "Sorry, I can't automatically select an interpreter!\n";
242 SafeToolArgs.push_back("--relocation-model=pic");
243 SafeInterpreter = AbstractInterpreter::createLLC(Path.c_str(), Message,
248 SafeInterpreter = AbstractInterpreter::createCBE(Path.c_str(), Message,
253 SafeInterpreter = AbstractInterpreter::createCustom(Message,
257 Message = "Sorry, this back-end is not supported by bugpoint as the "
258 "\"safe\" backend right now!\n";
261 if (!SafeInterpreter) { outs() << Message << "\nExiting.\n"; exit(1); }
263 gcc = GCC::create(Message, &GCCToolArgv);
264 if (!gcc) { outs() << Message << "\nExiting.\n"; exit(1); }
266 // If there was an error creating the selected interpreter, quit with error.
267 return Interpreter == 0;
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.
274 void BugDriver::compileProgram(Module *M) {
275 // Emit the program to a bitcode file...
276 sys::Path BitcodeFile ("bugpoint-test-program.bc");
278 if (BitcodeFile.makeUnique(true,&ErrMsg)) {
279 errs() << ToolName << ": Error making unique filename: " << ErrMsg
283 if (writeProgramToFile(BitcodeFile.toString(), M)) {
284 errs() << ToolName << ": Error emitting bitcode to file '"
285 << BitcodeFile << "'!\n";
289 // Remove the temporary bitcode file when we are done.
290 FileRemover BitcodeFileRemover(BitcodeFile, !SaveTemps);
292 // Actually compile the program!
293 Interpreter->compileProgram(BitcodeFile.toString());
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.
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;
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: "
318 BitcodeFile = uniqueFilename.toString();
320 if (writeProgramToFile(BitcodeFile, Program)) {
321 errs() << ToolName << ": Error emitting bitcode to file '"
322 << BitcodeFile << "'!\n";
325 CreatedBitcode = true;
328 // Remove the temporary bitcode file when we are done.
329 sys::Path BitcodePath (BitcodeFile);
330 FileRemover BitcodeFileRemover(BitcodePath, CreatedBitcode && !SaveTemps);
332 if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";
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: "
341 OutputFile = uniqueFile.toString();
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);
348 int RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile,
349 OutputFile, AdditionalLinkerArgs, SharedObjs,
350 Timeout, MemoryLimit);
353 errs() << "<timeout>";
354 static bool FirstTimeout = true;
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;
365 if (AppendProgramExitCode) {
366 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
367 outFile << "exit " << RetVal << '\n';
371 if (ProgramExitedNonzero != 0)
372 *ProgramExitedNonzero = (RetVal != 0);
374 // Return the filename we captured the output to.
378 /// executeProgramSafely - Used to create reference output with the "safe"
379 /// backend, if reference output is not provided.
381 std::string BugDriver::executeProgramSafely(std::string OutputFile) {
382 bool ProgramExitedNonzero;
383 std::string outFN = executeProgram(OutputFile, "", "", SafeInterpreter,
384 &ProgramExitedNonzero);
388 std::string BugDriver::compileSharedObject(const std::string &BitcodeFile) {
389 assert(Interpreter && "Interpreter should have been created already!");
390 sys::Path OutputFile;
392 // Using the known-good backend.
393 GCC::FileType FT = SafeInterpreter->OutputCode(BitcodeFile, OutputFile);
395 std::string SharedObjectFile;
396 if (gcc->MakeSharedObject(OutputFile.toString(), FT,
397 SharedObjectFile, AdditionalLinkerArgs))
400 // Remove the intermediate C file
401 OutputFile.eraseFromDisk();
403 return "./" + SharedObjectFile;
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
411 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
413 compileProgram(Program);
414 } catch (ToolExecutionError &) {
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";
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.
438 bool BugDriver::diffProgram(const std::string &BitcodeFile,
439 const std::string &SharedObject,
440 bool RemoveBitcode) {
441 bool ProgramExitedNonzero;
443 // Execute the program, generating an output file...
444 sys::Path Output(executeProgram("", BitcodeFile, SharedObject, 0,
445 &ProgramExitedNonzero));
448 bool FilesDifferent = false;
449 if (int Diff = DiffFilesWithTolerance(sys::Path(ReferenceOutputFile),
450 sys::Path(Output.toString()),
451 AbsTolerance, RelTolerance, &Error)) {
453 errs() << "While diffing output: " << Error << '\n';
456 FilesDifferent = true;
459 // Remove the generated output if there are no differences.
460 Output.eraseFromDisk();
463 // Remove the bitcode file if we are supposed to.
465 sys::Path(BitcodeFile).eraseFromDisk();
466 return FilesDifferent;
469 bool BugDriver::isExecutingJIT() {
470 return InterpreterSel == RunJIT;