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