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