For PR351:
[oota-llvm.git] / tools / bugpoint / ToolRunner.cpp
1 //===-- ToolRunner.cpp ----------------------------------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interfaces described in the ToolRunner.h file.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "toolrunner"
15 #include "llvm/Support/ToolRunner.h"
16 #include "llvm/Config/config.h"   // for HAVE_LINK_R
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/FileUtilities.h"
19 #include <fstream>
20 #include <sstream>
21 using namespace llvm;
22
23 ToolExecutionError::~ToolExecutionError() throw() { }
24
25 static void ProcessFailure(std::string ProgPath, const char** Args) {
26   std::ostringstream OS;
27   OS << "\nError running tool:\n ";
28   for (const char **Arg = Args; *Arg; ++Arg)
29     OS << " " << *Arg;
30   OS << "\n";
31
32   // Rerun the compiler, capturing any error messages to print them.
33   sys::Path ErrorFilename("error_messages");
34   ErrorFilename.makeUnique();
35   RunProgramWithTimeout(ProgPath, Args, "/dev/null", ErrorFilename.c_str(),
36                         ErrorFilename.c_str());
37
38   // Print out the error messages generated by GCC if possible...
39   std::ifstream ErrorFile(ErrorFilename.c_str());
40   if (ErrorFile) {
41     std::copy(std::istreambuf_iterator<char>(ErrorFile),
42               std::istreambuf_iterator<char>(),
43               std::ostreambuf_iterator<char>(OS));
44     ErrorFile.close();
45   }
46
47   ErrorFilename.destroyFile();
48   throw ToolExecutionError(OS.str());
49 }
50
51 //===---------------------------------------------------------------------===//
52 // LLI Implementation of AbstractIntepreter interface
53 //
54 namespace {
55   class LLI : public AbstractInterpreter {
56     std::string LLIPath;          // The path to the LLI executable
57     std::vector<std::string> ToolArgs; // Args to pass to LLI
58   public:
59     LLI(const std::string &Path, const std::vector<std::string> *Args)
60       : LLIPath(Path) {
61       ToolArgs.clear ();
62       if (Args) { ToolArgs = *Args; }
63     }
64     
65     virtual int ExecuteProgram(const std::string &Bytecode,
66                                const std::vector<std::string> &Args,
67                                const std::string &InputFile,
68                                const std::string &OutputFile,
69                                const std::vector<std::string> &SharedLibs = 
70                                std::vector<std::string>(),
71                                unsigned Timeout = 0);
72   };
73 }
74
75 int LLI::ExecuteProgram(const std::string &Bytecode,
76                         const std::vector<std::string> &Args,
77                         const std::string &InputFile,
78                         const std::string &OutputFile,
79                         const std::vector<std::string> &SharedLibs,
80                         unsigned Timeout) {
81   if (!SharedLibs.empty())
82     throw ToolExecutionError("LLI currently does not support "
83                              "loading shared libraries.");
84
85   std::vector<const char*> LLIArgs;
86   LLIArgs.push_back(LLIPath.c_str());
87   LLIArgs.push_back("-force-interpreter=true");
88
89   // Add any extra LLI args.
90   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
91     LLIArgs.push_back(ToolArgs[i].c_str());
92
93   LLIArgs.push_back(Bytecode.c_str());
94   // Add optional parameters to the running program from Argv
95   for (unsigned i=0, e = Args.size(); i != e; ++i)
96     LLIArgs.push_back(Args[i].c_str());
97   LLIArgs.push_back(0);
98
99   std::cout << "<lli>" << std::flush;
100   DEBUG(std::cerr << "\nAbout to run:\t";
101         for (unsigned i=0, e = LLIArgs.size()-1; i != e; ++i)
102           std::cerr << " " << LLIArgs[i];
103         std::cerr << "\n";
104         );
105   return RunProgramWithTimeout(LLIPath, &LLIArgs[0],
106                                InputFile, OutputFile, OutputFile, Timeout);
107 }
108
109 // LLI create method - Try to find the LLI executable
110 AbstractInterpreter *AbstractInterpreter::createLLI(const std::string &ProgPath,
111                                                     std::string &Message,
112                                      const std::vector<std::string> *ToolArgs) {
113   std::string LLIPath = FindExecutable("lli", ProgPath).toString();
114   if (!LLIPath.empty()) {
115     Message = "Found lli: " + LLIPath + "\n";
116     return new LLI(LLIPath, ToolArgs);
117   }
118
119   Message = "Cannot find `lli' in executable directory or PATH!\n";
120   return 0;
121 }
122
123 //===----------------------------------------------------------------------===//
124 // LLC Implementation of AbstractIntepreter interface
125 //
126 void LLC::OutputAsm(const std::string &Bytecode, sys::Path &OutputAsmFile) {
127   sys::Path uniqueFile(Bytecode+".llc.s");
128   uniqueFile.makeUnique();
129   OutputAsmFile = uniqueFile;
130   std::vector<const char *> LLCArgs;
131   LLCArgs.push_back (LLCPath.c_str());
132
133   // Add any extra LLC args.
134   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
135     LLCArgs.push_back(ToolArgs[i].c_str());
136
137   LLCArgs.push_back ("-o");
138   LLCArgs.push_back (OutputAsmFile.c_str()); // Output to the Asm file
139   LLCArgs.push_back ("-f");                  // Overwrite as necessary...
140   LLCArgs.push_back (Bytecode.c_str());      // This is the input bytecode
141   LLCArgs.push_back (0);
142
143   std::cout << "<llc>" << std::flush;
144   DEBUG(std::cerr << "\nAbout to run:\t";
145         for (unsigned i=0, e = LLCArgs.size()-1; i != e; ++i)
146           std::cerr << " " << LLCArgs[i];
147         std::cerr << "\n";
148         );
149   if (RunProgramWithTimeout(LLCPath, &LLCArgs[0], "/dev/null", "/dev/null",
150                             "/dev/null"))
151     ProcessFailure(LLCPath, &LLCArgs[0]);
152 }
153
154 void LLC::compileProgram(const std::string &Bytecode) {
155   sys::Path OutputAsmFile;
156   OutputAsm(Bytecode, OutputAsmFile);
157   OutputAsmFile.destroyFile();
158 }
159
160 int LLC::ExecuteProgram(const std::string &Bytecode,
161                         const std::vector<std::string> &Args,
162                         const std::string &InputFile,
163                         const std::string &OutputFile,
164                         const std::vector<std::string> &SharedLibs,
165                         unsigned Timeout) {
166
167   sys::Path OutputAsmFile;
168   OutputAsm(Bytecode, OutputAsmFile);
169   FileRemover OutFileRemover(OutputAsmFile);
170
171   // Assuming LLC worked, compile the result with GCC and run it.
172   return gcc->ExecuteProgram(OutputAsmFile.toString(), Args, GCC::AsmFile,
173                              InputFile, OutputFile, SharedLibs, Timeout);
174 }
175
176 /// createLLC - Try to find the LLC executable
177 ///
178 LLC *AbstractInterpreter::createLLC(const std::string &ProgramPath,
179                                     std::string &Message,
180                                     const std::vector<std::string> *Args) {
181   std::string LLCPath = FindExecutable("llc", ProgramPath).toString();
182   if (LLCPath.empty()) {
183     Message = "Cannot find `llc' in executable directory or PATH!\n";
184     return 0;
185   }
186
187   Message = "Found llc: " + LLCPath + "\n";
188   GCC *gcc = GCC::create(ProgramPath, Message);
189   if (!gcc) {
190     std::cerr << Message << "\n";
191     exit(1);
192   }
193   return new LLC(LLCPath, gcc, Args);
194 }
195
196 //===---------------------------------------------------------------------===//
197 // JIT Implementation of AbstractIntepreter interface
198 //
199 namespace {
200   class JIT : public AbstractInterpreter {
201     std::string LLIPath;          // The path to the LLI executable
202     std::vector<std::string> ToolArgs; // Args to pass to LLI
203   public:
204     JIT(const std::string &Path, const std::vector<std::string> *Args)
205       : LLIPath(Path) {
206       ToolArgs.clear ();
207       if (Args) { ToolArgs = *Args; }
208     }
209     
210     virtual int ExecuteProgram(const std::string &Bytecode,
211                                const std::vector<std::string> &Args,
212                                const std::string &InputFile,
213                                const std::string &OutputFile,
214                                const std::vector<std::string> &SharedLibs = 
215                                std::vector<std::string>(), unsigned Timeout =0);
216   };
217 }
218
219 int JIT::ExecuteProgram(const std::string &Bytecode,
220                         const std::vector<std::string> &Args,
221                         const std::string &InputFile,
222                         const std::string &OutputFile,
223                         const std::vector<std::string> &SharedLibs,
224                         unsigned Timeout) {
225   // Construct a vector of parameters, incorporating those from the command-line
226   std::vector<const char*> JITArgs;
227   JITArgs.push_back(LLIPath.c_str());
228   JITArgs.push_back("-force-interpreter=false");
229
230   // Add any extra LLI args.
231   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
232     JITArgs.push_back(ToolArgs[i].c_str());
233
234   for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i) {
235     JITArgs.push_back("-load");
236     JITArgs.push_back(SharedLibs[i].c_str());
237   }
238   JITArgs.push_back(Bytecode.c_str());
239   // Add optional parameters to the running program from Argv
240   for (unsigned i=0, e = Args.size(); i != e; ++i)
241     JITArgs.push_back(Args[i].c_str());
242   JITArgs.push_back(0);
243
244   std::cout << "<jit>" << std::flush;
245   DEBUG(std::cerr << "\nAbout to run:\t";
246         for (unsigned i=0, e = JITArgs.size()-1; i != e; ++i)
247           std::cerr << " " << JITArgs[i];
248         std::cerr << "\n";
249         );
250   DEBUG(std::cerr << "\nSending output to " << OutputFile << "\n");
251   return RunProgramWithTimeout(LLIPath, &JITArgs[0],
252                                InputFile, OutputFile, OutputFile, Timeout);
253 }
254
255 /// createJIT - Try to find the LLI executable
256 ///
257 AbstractInterpreter *AbstractInterpreter::createJIT(const std::string &ProgPath,
258                    std::string &Message, const std::vector<std::string> *Args) {
259   std::string LLIPath = FindExecutable("lli", ProgPath).toString();
260   if (!LLIPath.empty()) {
261     Message = "Found lli: " + LLIPath + "\n";
262     return new JIT(LLIPath, Args);
263   }
264
265   Message = "Cannot find `lli' in executable directory or PATH!\n";
266   return 0;
267 }
268
269 void CBE::OutputC(const std::string &Bytecode, sys::Path& OutputCFile) {
270   sys::Path uniqueFile(Bytecode+".cbe.c");
271   uniqueFile.makeUnique();
272   OutputCFile = uniqueFile;
273   std::vector<const char *> LLCArgs;
274   LLCArgs.push_back (LLCPath.c_str());
275
276   // Add any extra LLC args.
277   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
278     LLCArgs.push_back(ToolArgs[i].c_str());
279
280   LLCArgs.push_back ("-o");
281   LLCArgs.push_back (OutputCFile.c_str());   // Output to the C file
282   LLCArgs.push_back ("-march=c");            // Output C language
283   LLCArgs.push_back ("-f");                  // Overwrite as necessary...
284   LLCArgs.push_back (Bytecode.c_str());      // This is the input bytecode
285   LLCArgs.push_back (0);
286
287   std::cout << "<cbe>" << std::flush;
288   DEBUG(std::cerr << "\nAbout to run:\t";
289         for (unsigned i=0, e = LLCArgs.size()-1; i != e; ++i)
290           std::cerr << " " << LLCArgs[i];
291         std::cerr << "\n";
292         );
293   if (RunProgramWithTimeout(LLCPath, &LLCArgs[0], "/dev/null", "/dev/null",
294                             "/dev/null"))
295     ProcessFailure(LLCPath, &LLCArgs[0]);
296 }
297
298 void CBE::compileProgram(const std::string &Bytecode) {
299   sys::Path OutputCFile;
300   OutputC(Bytecode, OutputCFile);
301   OutputCFile.destroyFile();
302 }
303
304 int CBE::ExecuteProgram(const std::string &Bytecode,
305                         const std::vector<std::string> &Args,
306                         const std::string &InputFile,
307                         const std::string &OutputFile,
308                         const std::vector<std::string> &SharedLibs,
309                         unsigned Timeout) {
310   sys::Path OutputCFile;
311   OutputC(Bytecode, OutputCFile);
312
313   FileRemover CFileRemove(OutputCFile);
314
315   return gcc->ExecuteProgram(OutputCFile.toString(), Args, GCC::CFile, 
316                              InputFile, OutputFile, SharedLibs, Timeout);
317 }
318
319 /// createCBE - Try to find the 'llc' executable
320 ///
321 CBE *AbstractInterpreter::createCBE(const std::string &ProgramPath,
322                                     std::string &Message,
323                                     const std::vector<std::string> *Args) {
324   std::string LLCPath = FindExecutable("llc", ProgramPath).toString();
325   if (LLCPath.empty()) {
326     Message = 
327       "Cannot find `llc' in executable directory or PATH!\n";
328     return 0;
329   }
330
331   Message = "Found llc: " + LLCPath + "\n";
332   GCC *gcc = GCC::create(ProgramPath, Message);
333   if (!gcc) {
334     std::cerr << Message << "\n";
335     exit(1);
336   }
337   return new CBE(LLCPath, gcc, Args);
338 }
339
340 //===---------------------------------------------------------------------===//
341 // GCC abstraction
342 //
343 int GCC::ExecuteProgram(const std::string &ProgramFile,
344                         const std::vector<std::string> &Args,
345                         FileType fileType,
346                         const std::string &InputFile,
347                         const std::string &OutputFile,
348                         const std::vector<std::string> &SharedLibs,
349                         unsigned Timeout) {
350   std::vector<const char*> GCCArgs;
351
352   GCCArgs.push_back(GCCPath.c_str());
353
354   // Specify the shared libraries to link in...
355   for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i)
356     GCCArgs.push_back(SharedLibs[i].c_str());
357   
358   // Specify -x explicitly in case the extension is wonky
359   GCCArgs.push_back("-x");
360   if (fileType == CFile) {
361     GCCArgs.push_back("c");
362     GCCArgs.push_back("-fno-strict-aliasing");
363   } else {
364     GCCArgs.push_back("assembler");
365   }
366   GCCArgs.push_back(ProgramFile.c_str());  // Specify the input filename...
367   GCCArgs.push_back("-o");
368   sys::Path OutputBinary (ProgramFile+".gcc.exe");
369   OutputBinary.makeUnique();
370   GCCArgs.push_back(OutputBinary.c_str()); // Output to the right file...
371   GCCArgs.push_back("-lm");                // Hard-code the math library...
372   GCCArgs.push_back("-O2");                // Optimize the program a bit...
373 #if defined (HAVE_LINK_R)
374   GCCArgs.push_back("-Wl,-R.");            // Search this dir for .so files
375 #endif
376   GCCArgs.push_back(0);                    // NULL terminator
377
378   std::cout << "<gcc>" << std::flush;
379   if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], "/dev/null", "/dev/null",
380                             "/dev/null")) {
381     ProcessFailure(GCCPath, &GCCArgs[0]);
382     exit(1);
383   }
384
385   std::vector<const char*> ProgramArgs;
386   ProgramArgs.push_back(OutputBinary.c_str());
387   // Add optional parameters to the running program from Argv
388   for (unsigned i=0, e = Args.size(); i != e; ++i)
389     ProgramArgs.push_back(Args[i].c_str());
390   ProgramArgs.push_back(0);                // NULL terminator
391
392   // Now that we have a binary, run it!
393   std::cout << "<program>" << std::flush;
394   DEBUG(std::cerr << "\nAbout to run:\t";
395         for (unsigned i=0, e = ProgramArgs.size()-1; i != e; ++i)
396           std::cerr << " " << ProgramArgs[i];
397         std::cerr << "\n";
398         );
399
400   FileRemover OutputBinaryRemover(OutputBinary);
401   return RunProgramWithTimeout(OutputBinary.toString(), &ProgramArgs[0],
402                                InputFile, OutputFile, OutputFile, Timeout);
403 }
404
405 int GCC::MakeSharedObject(const std::string &InputFile, FileType fileType,
406                           std::string &OutputFile) {
407   sys::Path uniqueFilename(InputFile+LTDL_SHLIB_EXT);
408   uniqueFilename.makeUnique();
409   OutputFile = uniqueFilename.toString();
410
411   // Compile the C/asm file into a shared object
412   const char* GCCArgs[] = {
413     GCCPath.c_str(),
414     "-x", (fileType == AsmFile) ? "assembler" : "c",
415     "-fno-strict-aliasing",
416     InputFile.c_str(),           // Specify the input filename...
417 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
418     "-G",                        // Compile a shared library, `-G' for Sparc
419 #elif (defined(__POWERPC__) || defined(__ppc__)) && defined(__APPLE__)
420     "-single_module",            // link all source files into a single module
421     "-dynamiclib",               // `-dynamiclib' for MacOS X/PowerPC
422     "-undefined",                // in data segment, rather than generating
423     "dynamic_lookup",            // blocks. dynamic_lookup requires that you set
424                                  // MACOSX_DEPLOYMENT_TARGET=10.3 in your env.
425 #else
426     "-shared",                   // `-shared' for Linux/X86, maybe others
427 #endif
428     "-o", OutputFile.c_str(),    // Output to the right filename...
429     "-O2",                       // Optimize the program a bit...
430     0
431   };
432   
433   std::cout << "<gcc>" << std::flush;
434   if (RunProgramWithTimeout(GCCPath, GCCArgs, "/dev/null", "/dev/null",
435                             "/dev/null")) {
436     ProcessFailure(GCCPath, GCCArgs);
437     return 1;
438   }
439   return 0;
440 }
441
442 /// create - Try to find the `gcc' executable
443 ///
444 GCC *GCC::create(const std::string &ProgramPath, std::string &Message) {
445   std::string GCCPath = FindExecutable("gcc", ProgramPath).toString();
446   if (GCCPath.empty()) {
447     Message = "Cannot find `gcc' in executable directory or PATH!\n";
448     return 0;
449   }
450
451   Message = "Found gcc: " + GCCPath + "\n";
452   return new GCC(GCCPath);
453 }