1 //===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 bytecode.
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"
27 // OutputType - Allow the user to specify the way code should be run, to test
28 // for miscompilation.
31 AutoPick, RunLLI, RunJIT, RunLLC, RunCBE
35 AbsTolerance("abs-tolerance", cl::desc("Absolute error tolerated"),
38 RelTolerance("rel-tolerance", cl::desc("Relative error tolerated"),
42 InterpreterSel(cl::desc("Specify how LLVM code should be executed:"),
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(RunCBE, "run-cbe", "Compile with CBE"),
53 CheckProgramExitCode("check-exit-code",
54 cl::desc("Assume nonzero exit code is failure (default on)"),
58 InputFile("input", cl::init("/dev/null"),
59 cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
62 AdditionalSOs("additional-so",
63 cl::desc("Additional shared objects to load "
64 "into executing programs"));
67 AdditionalLinkerArgs("Xlinker",
68 cl::desc("Additional arguments to pass to the linker"));
72 // Anything specified after the --args option are taken as arguments to the
73 // program being debugged.
75 InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
76 cl::ZeroOrMore, cl::PositionalEatsArgs);
79 ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
80 cl::ZeroOrMore, cl::PositionalEatsArgs);
83 //===----------------------------------------------------------------------===//
84 // BugDriver method implementation
87 /// initializeExecutionEnvironment - This method is used to set up the
88 /// environment for executing LLVM programs.
90 bool BugDriver::initializeExecutionEnvironment() {
91 std::cout << "Initializing execution environment: ";
93 // Create an instance of the AbstractInterpreter interface as specified on
98 switch (InterpreterSel) {
100 InterpreterSel = RunCBE;
101 Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
104 InterpreterSel = RunJIT;
105 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
109 InterpreterSel = RunLLC;
110 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
114 InterpreterSel = RunLLI;
115 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
119 InterpreterSel = AutoPick;
120 Message = "Sorry, I can't automatically select an interpreter!\n";
124 Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
128 Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
132 Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
136 Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
140 Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
143 std::cerr << Message;
145 // Initialize auxiliary tools for debugging
147 cbe = AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv);
148 if (!cbe) { std::cout << Message << "\nExiting.\n"; exit(1); }
150 gcc = GCC::create(getToolName(), Message);
151 if (!gcc) { std::cout << Message << "\nExiting.\n"; exit(1); }
153 // If there was an error creating the selected interpreter, quit with error.
154 return Interpreter == 0;
157 /// compileProgram - Try to compile the specified module, throwing an exception
158 /// if an error occurs, or returning normally if not. This is used for code
159 /// generation crash testing.
161 void BugDriver::compileProgram(Module *M) {
162 // Emit the program to a bytecode file...
163 sys::Path BytecodeFile ("bugpoint-test-program.bc");
165 if (BytecodeFile.makeUnique(true,&ErrMsg)) {
166 std::cerr << ToolName << ": Error making unique filename: " << ErrMsg
170 if (writeProgramToFile(BytecodeFile.toString(), M)) {
171 std::cerr << ToolName << ": Error emitting bytecode to file '"
172 << BytecodeFile << "'!\n";
176 // Remove the temporary bytecode file when we are done.
177 FileRemover BytecodeFileRemover(BytecodeFile);
179 // Actually compile the program!
180 Interpreter->compileProgram(BytecodeFile.toString());
184 /// executeProgram - This method runs "Program", capturing the output of the
185 /// program to a file, returning the filename of the file. A recommended
186 /// filename may be optionally specified.
188 std::string BugDriver::executeProgram(std::string OutputFile,
189 std::string BytecodeFile,
190 const std::string &SharedObj,
191 AbstractInterpreter *AI,
192 bool *ProgramExitedNonzero) {
193 if (AI == 0) AI = Interpreter;
194 assert(AI && "Interpreter should have been created already!");
195 bool CreatedBytecode = false;
197 if (BytecodeFile.empty()) {
198 // Emit the program to a bytecode file...
199 sys::Path uniqueFilename("bugpoint-test-program.bc");
200 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
201 std::cerr << ToolName << ": Error making unique filename: "
205 BytecodeFile = uniqueFilename.toString();
207 if (writeProgramToFile(BytecodeFile, Program)) {
208 std::cerr << ToolName << ": Error emitting bytecode to file '"
209 << BytecodeFile << "'!\n";
212 CreatedBytecode = true;
215 // Remove the temporary bytecode file when we are done.
216 sys::Path BytecodePath (BytecodeFile);
217 FileRemover BytecodeFileRemover(BytecodePath, CreatedBytecode);
219 if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";
221 // Check to see if this is a valid output filename...
222 sys::Path uniqueFile(OutputFile);
223 if (uniqueFile.makeUnique(true, &ErrMsg)) {
224 std::cerr << ToolName << ": Error making unique filename: "
228 OutputFile = uniqueFile.toString();
230 // Figure out which shared objects to run, if any.
231 std::vector<std::string> SharedObjs(AdditionalSOs);
232 if (!SharedObj.empty())
233 SharedObjs.push_back(SharedObj);
236 // If this is an LLC or CBE run, then the GCC compiler might get run to
237 // compile the program. If so, we should pass the user's -Xlinker options
240 if (InterpreterSel == RunLLC || InterpreterSel == RunCBE)
241 RetVal = AI->ExecuteProgram(BytecodeFile, InputArgv, InputFile,
242 OutputFile, AdditionalLinkerArgs, SharedObjs,
245 RetVal = AI->ExecuteProgram(BytecodeFile, InputArgv, InputFile,
246 OutputFile, std::vector<std::string>(),
247 SharedObjs, Timeout);
250 std::cerr << "<timeout>";
251 static bool FirstTimeout = true;
254 "*** Program execution timed out! This mechanism is designed to handle\n"
255 " programs stuck in infinite loops gracefully. The -timeout option\n"
256 " can be used to change the timeout threshold or disable it completely\n"
257 " (with -timeout=0). This message is only displayed once.\n";
258 FirstTimeout = false;
262 if (ProgramExitedNonzero != 0)
263 *ProgramExitedNonzero = (RetVal != 0);
265 // Return the filename we captured the output to.
269 /// executeProgramWithCBE - Used to create reference output with the C
270 /// backend, if reference output is not provided.
272 std::string BugDriver::executeProgramWithCBE(std::string OutputFile) {
273 bool ProgramExitedNonzero;
274 std::string outFN = executeProgram(OutputFile, "", "",
275 (AbstractInterpreter*)cbe,
276 &ProgramExitedNonzero);
277 if (ProgramExitedNonzero) {
279 << "Warning: While generating reference output, program exited with\n"
280 << "non-zero exit code. This will NOT be treated as a failure.\n";
281 CheckProgramExitCode = false;
286 std::string BugDriver::compileSharedObject(const std::string &BytecodeFile) {
287 assert(Interpreter && "Interpreter should have been created already!");
288 sys::Path OutputCFile;
291 cbe->OutputC(BytecodeFile, OutputCFile);
293 #if 0 /* This is an alternative, as yet unimplemented */
296 LLC *llc = createLLCtool(Message);
297 if (llc->OutputAsm(BytecodeFile, OutputFile)) {
298 std::cerr << "Could not generate asm code with `llc', exiting.\n";
303 std::string SharedObjectFile;
304 if (gcc->MakeSharedObject(OutputCFile.toString(), GCC::CFile,
305 SharedObjectFile, AdditionalLinkerArgs))
308 // Remove the intermediate C file
309 OutputCFile.eraseFromDisk();
311 return "./" + SharedObjectFile;
314 /// createReferenceFile - calls compileProgram and then records the output
315 /// into ReferenceOutputFile. Returns true if reference file created, false
316 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
319 bool BugDriver::createReferenceFile(Module *M, const std::string &Filename){
321 compileProgram(Program);
322 } catch (ToolExecutionError &TEE) {
326 ReferenceOutputFile = executeProgramWithCBE(Filename);
327 std::cout << "Reference output is: " << ReferenceOutputFile << "\n\n";
328 } catch (ToolExecutionError &TEE) {
329 std::cerr << TEE.what();
330 if (Interpreter != cbe) {
331 std::cerr << "*** There is a bug running the C backend. Either debug"
332 << " it (use the -run-cbe bugpoint option), or fix the error"
333 << " some other way.\n";
340 /// diffProgram - This method executes the specified module and diffs the
341 /// output against the file specified by ReferenceOutputFile. If the output
342 /// is different, true is returned. If there is a problem with the code
343 /// generator (e.g., llc crashes), this will throw an exception.
345 bool BugDriver::diffProgram(const std::string &BytecodeFile,
346 const std::string &SharedObject,
347 bool RemoveBytecode) {
348 bool ProgramExitedNonzero;
350 // Execute the program, generating an output file...
351 sys::Path Output(executeProgram("", BytecodeFile, SharedObject, 0,
352 &ProgramExitedNonzero));
354 // If we're checking the program exit code, assume anything nonzero is bad.
355 if (CheckProgramExitCode && ProgramExitedNonzero) {
356 Output.eraseFromDisk();
358 sys::Path(BytecodeFile).eraseFromDisk();
363 bool FilesDifferent = false;
364 if (int Diff = DiffFilesWithTolerance(sys::Path(ReferenceOutputFile),
365 sys::Path(Output.toString()),
366 AbsTolerance, RelTolerance, &Error)) {
368 std::cerr << "While diffing output: " << Error << '\n';
371 FilesDifferent = true;
374 // Remove the generated output.
375 Output.eraseFromDisk();
377 // Remove the bytecode file if we are supposed to.
379 sys::Path(BytecodeFile).eraseFromDisk();
380 return FilesDifferent;
383 bool BugDriver::isExecutingJIT() {
384 return InterpreterSel == RunJIT;