Have sys::FindProgramByName return a std::string.
[oota-llvm.git] / tools / bugpoint / ToolRunner.cpp
1 //===-- ToolRunner.cpp ----------------------------------------------------===//
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 implements the interfaces described in the ToolRunner.h file.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "toolrunner"
15 #include "ToolRunner.h"
16 #include "llvm/Config/config.h"   // for HAVE_LINK_R
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/Program.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <fstream>
23 #include <sstream>
24 using namespace llvm;
25
26 namespace llvm {
27   cl::opt<bool>
28   SaveTemps("save-temps", cl::init(false), cl::desc("Save temporary files"));
29 }
30
31 namespace {
32   cl::opt<std::string>
33   RemoteClient("remote-client",
34                cl::desc("Remote execution client (rsh/ssh)"));
35
36   cl::opt<std::string>
37   RemoteHost("remote-host",
38              cl::desc("Remote execution (rsh/ssh) host"));
39
40   cl::opt<std::string>
41   RemotePort("remote-port",
42              cl::desc("Remote execution (rsh/ssh) port"));
43
44   cl::opt<std::string>
45   RemoteUser("remote-user",
46              cl::desc("Remote execution (rsh/ssh) user id"));
47
48   cl::opt<std::string>
49   RemoteExtra("remote-extra-options",
50           cl::desc("Remote execution (rsh/ssh) extra options"));
51 }
52
53 /// RunProgramWithTimeout - This function provides an alternate interface
54 /// to the sys::Program::ExecuteAndWait interface.
55 /// @see sys::Program::ExecuteAndWait
56 static int RunProgramWithTimeout(StringRef ProgramPath,
57                                  const char **Args,
58                                  StringRef StdInFile,
59                                  StringRef StdOutFile,
60                                  StringRef StdErrFile,
61                                  unsigned NumSeconds = 0,
62                                  unsigned MemoryLimit = 0,
63                                  std::string *ErrMsg = 0) {
64   const sys::Path P[3] = { sys::Path(StdInFile), sys::Path(StdOutFile),
65                            sys::Path(StdErrFile) };
66   const sys::Path* redirects[3];
67   for (int I = 0; I < 3; ++I)
68     redirects[I] = &P[I];
69
70 #if 0 // For debug purposes
71   {
72     errs() << "RUN:";
73     for (unsigned i = 0; Args[i]; ++i)
74       errs() << " " << Args[i];
75     errs() << "\n";
76   }
77 #endif
78
79   return sys::ExecuteAndWait(sys::Path(ProgramPath), Args, 0, redirects,
80                              NumSeconds, MemoryLimit, ErrMsg);
81 }
82
83 /// RunProgramRemotelyWithTimeout - This function runs the given program
84 /// remotely using the given remote client and the sys::Program::ExecuteAndWait.
85 /// Returns the remote program exit code or reports a remote client error if it
86 /// fails. Remote client is required to return 255 if it failed or program exit
87 /// code otherwise.
88 /// @see sys::Program::ExecuteAndWait
89 static int RunProgramRemotelyWithTimeout(StringRef RemoteClientPath,
90                                          const char **Args,
91                                          StringRef StdInFile,
92                                          StringRef StdOutFile,
93                                          StringRef StdErrFile,
94                                          unsigned NumSeconds = 0,
95                                          unsigned MemoryLimit = 0) {
96   const sys::Path P[3] = { sys::Path(StdInFile), sys::Path(StdOutFile),
97                            sys::Path(StdErrFile) };
98   const sys::Path* redirects[3];
99   for (int I = 0; I < 3; ++I)
100     redirects[I] = &P[I];
101
102 #if 0 // For debug purposes
103   {
104     errs() << "RUN:";
105     for (unsigned i = 0; Args[i]; ++i)
106       errs() << " " << Args[i];
107     errs() << "\n";
108   }
109 #endif
110
111   // Run the program remotely with the remote client
112   int ReturnCode = sys::ExecuteAndWait(sys::Path(RemoteClientPath), Args, 0,
113                                        redirects, NumSeconds, MemoryLimit);
114
115   // Has the remote client fail?
116   if (255 == ReturnCode) {
117     std::ostringstream OS;
118     OS << "\nError running remote client:\n ";
119     for (const char **Arg = Args; *Arg; ++Arg)
120       OS << " " << *Arg;
121     OS << "\n";
122
123     // The error message is in the output file, let's print it out from there.
124     std::string StdOutFileName = StdOutFile.str();
125     std::ifstream ErrorFile(StdOutFileName.c_str());
126     if (ErrorFile) {
127       std::copy(std::istreambuf_iterator<char>(ErrorFile),
128                 std::istreambuf_iterator<char>(),
129                 std::ostreambuf_iterator<char>(OS));
130       ErrorFile.close();
131     }
132
133     errs() << OS.str();
134   }
135
136   return ReturnCode;
137 }
138
139 static std::string ProcessFailure(StringRef ProgPath, const char** Args,
140                                   unsigned Timeout = 0,
141                                   unsigned MemoryLimit = 0) {
142   std::ostringstream OS;
143   OS << "\nError running tool:\n ";
144   for (const char **Arg = Args; *Arg; ++Arg)
145     OS << " " << *Arg;
146   OS << "\n";
147
148   // Rerun the compiler, capturing any error messages to print them.
149   sys::Path ErrorFilename("bugpoint.program_error_messages");
150   std::string ErrMsg;
151   if (ErrorFilename.makeUnique(true, &ErrMsg)) {
152     errs() << "Error making unique filename: " << ErrMsg << "\n";
153     exit(1);
154   }
155   RunProgramWithTimeout(ProgPath, Args, "", ErrorFilename.str(),
156                         ErrorFilename.str(), Timeout, MemoryLimit);
157   // FIXME: check return code ?
158
159   // Print out the error messages generated by GCC if possible...
160   std::ifstream ErrorFile(ErrorFilename.c_str());
161   if (ErrorFile) {
162     std::copy(std::istreambuf_iterator<char>(ErrorFile),
163               std::istreambuf_iterator<char>(),
164               std::ostreambuf_iterator<char>(OS));
165     ErrorFile.close();
166   }
167
168   ErrorFilename.eraseFromDisk();
169   return OS.str();
170 }
171
172 //===---------------------------------------------------------------------===//
173 // LLI Implementation of AbstractIntepreter interface
174 //
175 namespace {
176   class LLI : public AbstractInterpreter {
177     std::string LLIPath;          // The path to the LLI executable
178     std::vector<std::string> ToolArgs; // Args to pass to LLI
179   public:
180     LLI(const std::string &Path, const std::vector<std::string> *Args)
181       : LLIPath(Path) {
182       ToolArgs.clear ();
183       if (Args) { ToolArgs = *Args; }
184     }
185
186     virtual int ExecuteProgram(const std::string &Bitcode,
187                                const std::vector<std::string> &Args,
188                                const std::string &InputFile,
189                                const std::string &OutputFile,
190                                std::string *Error,
191                                const std::vector<std::string> &GCCArgs,
192                                const std::vector<std::string> &SharedLibs =
193                                std::vector<std::string>(),
194                                unsigned Timeout = 0,
195                                unsigned MemoryLimit = 0);
196   };
197 }
198
199 int LLI::ExecuteProgram(const std::string &Bitcode,
200                         const std::vector<std::string> &Args,
201                         const std::string &InputFile,
202                         const std::string &OutputFile,
203                         std::string *Error,
204                         const std::vector<std::string> &GCCArgs,
205                         const std::vector<std::string> &SharedLibs,
206                         unsigned Timeout,
207                         unsigned MemoryLimit) {
208   std::vector<const char*> LLIArgs;
209   LLIArgs.push_back(LLIPath.c_str());
210   LLIArgs.push_back("-force-interpreter=true");
211
212   for (std::vector<std::string>::const_iterator i = SharedLibs.begin(),
213          e = SharedLibs.end(); i != e; ++i) {
214     LLIArgs.push_back("-load");
215     LLIArgs.push_back((*i).c_str());
216   }
217
218   // Add any extra LLI args.
219   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
220     LLIArgs.push_back(ToolArgs[i].c_str());
221
222   LLIArgs.push_back(Bitcode.c_str());
223   // Add optional parameters to the running program from Argv
224   for (unsigned i=0, e = Args.size(); i != e; ++i)
225     LLIArgs.push_back(Args[i].c_str());
226   LLIArgs.push_back(0);
227
228   outs() << "<lli>"; outs().flush();
229   DEBUG(errs() << "\nAbout to run:\t";
230         for (unsigned i=0, e = LLIArgs.size()-1; i != e; ++i)
231           errs() << " " << LLIArgs[i];
232         errs() << "\n";
233         );
234   return RunProgramWithTimeout(LLIPath, &LLIArgs[0],
235       InputFile, OutputFile, OutputFile,
236       Timeout, MemoryLimit, Error);
237 }
238
239 void AbstractInterpreter::anchor() { }
240
241 // LLI create method - Try to find the LLI executable
242 AbstractInterpreter *AbstractInterpreter::createLLI(const char *Argv0,
243                                                     std::string &Message,
244                                      const std::vector<std::string> *ToolArgs) {
245   std::string LLIPath =
246     PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t)&createLLI).str();
247   if (!LLIPath.empty()) {
248     Message = "Found lli: " + LLIPath + "\n";
249     return new LLI(LLIPath, ToolArgs);
250   }
251
252   Message = "Cannot find `lli' in executable directory!\n";
253   return 0;
254 }
255
256 //===---------------------------------------------------------------------===//
257 // Custom compiler command implementation of AbstractIntepreter interface
258 //
259 // Allows using a custom command for compiling the bitcode, thus allows, for
260 // example, to compile a bitcode fragment without linking or executing, then
261 // using a custom wrapper script to check for compiler errors.
262 namespace {
263   class CustomCompiler : public AbstractInterpreter {
264     std::string CompilerCommand;
265     std::vector<std::string> CompilerArgs;
266   public:
267     CustomCompiler(
268       const std::string &CompilerCmd, std::vector<std::string> CompArgs) :
269       CompilerCommand(CompilerCmd), CompilerArgs(CompArgs) {}
270
271     virtual void compileProgram(const std::string &Bitcode,
272                                 std::string *Error,
273                                 unsigned Timeout = 0,
274                                 unsigned MemoryLimit = 0);
275
276     virtual int ExecuteProgram(const std::string &Bitcode,
277                                const std::vector<std::string> &Args,
278                                const std::string &InputFile,
279                                const std::string &OutputFile,
280                                std::string *Error,
281                                const std::vector<std::string> &GCCArgs =
282                                std::vector<std::string>(),
283                                const std::vector<std::string> &SharedLibs =
284                                std::vector<std::string>(),
285                                unsigned Timeout = 0,
286                                unsigned MemoryLimit = 0) {
287       *Error = "Execution not supported with -compile-custom";
288       return -1;
289     }
290   };
291 }
292
293 void CustomCompiler::compileProgram(const std::string &Bitcode,
294                                     std::string *Error,
295                                     unsigned Timeout,
296                                     unsigned MemoryLimit) {
297
298   std::vector<const char*> ProgramArgs;
299   ProgramArgs.push_back(CompilerCommand.c_str());
300
301   for (std::size_t i = 0; i < CompilerArgs.size(); ++i)
302     ProgramArgs.push_back(CompilerArgs.at(i).c_str());
303   ProgramArgs.push_back(Bitcode.c_str());
304   ProgramArgs.push_back(0);
305
306   // Add optional parameters to the running program from Argv
307   for (unsigned i = 0, e = CompilerArgs.size(); i != e; ++i)
308     ProgramArgs.push_back(CompilerArgs[i].c_str());
309
310   if (RunProgramWithTimeout(CompilerCommand, &ProgramArgs[0],
311                              "", "", "",
312                              Timeout, MemoryLimit, Error))
313     *Error = ProcessFailure(CompilerCommand, &ProgramArgs[0],
314                            Timeout, MemoryLimit);
315 }
316
317 //===---------------------------------------------------------------------===//
318 // Custom execution command implementation of AbstractIntepreter interface
319 //
320 // Allows using a custom command for executing the bitcode, thus allows,
321 // for example, to invoke a cross compiler for code generation followed by
322 // a simulator that executes the generated binary.
323 namespace {
324   class CustomExecutor : public AbstractInterpreter {
325     std::string ExecutionCommand;
326     std::vector<std::string> ExecutorArgs;
327   public:
328     CustomExecutor(
329       const std::string &ExecutionCmd, std::vector<std::string> ExecArgs) :
330       ExecutionCommand(ExecutionCmd), ExecutorArgs(ExecArgs) {}
331
332     virtual int ExecuteProgram(const std::string &Bitcode,
333                                const std::vector<std::string> &Args,
334                                const std::string &InputFile,
335                                const std::string &OutputFile,
336                                std::string *Error,
337                                const std::vector<std::string> &GCCArgs,
338                                const std::vector<std::string> &SharedLibs =
339                                  std::vector<std::string>(),
340                                unsigned Timeout = 0,
341                                unsigned MemoryLimit = 0);
342   };
343 }
344
345 int CustomExecutor::ExecuteProgram(const std::string &Bitcode,
346                         const std::vector<std::string> &Args,
347                         const std::string &InputFile,
348                         const std::string &OutputFile,
349                         std::string *Error,
350                         const std::vector<std::string> &GCCArgs,
351                         const std::vector<std::string> &SharedLibs,
352                         unsigned Timeout,
353                         unsigned MemoryLimit) {
354
355   std::vector<const char*> ProgramArgs;
356   ProgramArgs.push_back(ExecutionCommand.c_str());
357
358   for (std::size_t i = 0; i < ExecutorArgs.size(); ++i)
359     ProgramArgs.push_back(ExecutorArgs.at(i).c_str());
360   ProgramArgs.push_back(Bitcode.c_str());
361   ProgramArgs.push_back(0);
362
363   // Add optional parameters to the running program from Argv
364   for (unsigned i = 0, e = Args.size(); i != e; ++i)
365     ProgramArgs.push_back(Args[i].c_str());
366
367   return RunProgramWithTimeout(
368     ExecutionCommand,
369     &ProgramArgs[0], InputFile, OutputFile,
370     OutputFile, Timeout, MemoryLimit, Error);
371 }
372
373 // Tokenize the CommandLine to the command and the args to allow
374 // defining a full command line as the command instead of just the
375 // executed program. We cannot just pass the whole string after the command
376 // as a single argument because then program sees only a single
377 // command line argument (with spaces in it: "foo bar" instead
378 // of "foo" and "bar").
379 //
380 // code borrowed from:
381 // http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
382 static void lexCommand(std::string &Message, const std::string &CommandLine,
383                        std::string &CmdPath, std::vector<std::string> Args) {
384
385   std::string Command = "";
386   std::string delimiters = " ";
387
388   std::string::size_type lastPos = CommandLine.find_first_not_of(delimiters, 0);
389   std::string::size_type pos = CommandLine.find_first_of(delimiters, lastPos);
390
391   while (std::string::npos != pos || std::string::npos != lastPos) {
392     std::string token = CommandLine.substr(lastPos, pos - lastPos);
393     if (Command == "")
394        Command = token;
395     else
396        Args.push_back(token);
397     // Skip delimiters.  Note the "not_of"
398     lastPos = CommandLine.find_first_not_of(delimiters, pos);
399     // Find next "non-delimiter"
400     pos = CommandLine.find_first_of(delimiters, lastPos);
401   }
402
403   CmdPath = sys::FindProgramByName(Command);
404   if (CmdPath.empty()) {
405     Message =
406       std::string("Cannot find '") + Command +
407       "' in PATH!\n";
408     return;
409   }
410
411   Message = "Found command in: " + CmdPath + "\n";
412 }
413
414 // Custom execution environment create method, takes the execution command
415 // as arguments
416 AbstractInterpreter *AbstractInterpreter::createCustomCompiler(
417                     std::string &Message,
418                     const std::string &CompileCommandLine) {
419
420   std::string CmdPath;
421   std::vector<std::string> Args;
422   lexCommand(Message, CompileCommandLine, CmdPath, Args);
423   if (CmdPath.empty())
424     return 0;
425
426   return new CustomCompiler(CmdPath, Args);
427 }
428
429 // Custom execution environment create method, takes the execution command
430 // as arguments
431 AbstractInterpreter *AbstractInterpreter::createCustomExecutor(
432                     std::string &Message,
433                     const std::string &ExecCommandLine) {
434
435
436   std::string CmdPath;
437   std::vector<std::string> Args;
438   lexCommand(Message, ExecCommandLine, CmdPath, Args);
439   if (CmdPath.empty())
440     return 0;
441
442   return new CustomExecutor(CmdPath, Args);
443 }
444
445 //===----------------------------------------------------------------------===//
446 // LLC Implementation of AbstractIntepreter interface
447 //
448 GCC::FileType LLC::OutputCode(const std::string &Bitcode,
449                               sys::Path &OutputAsmFile, std::string &Error,
450                               unsigned Timeout, unsigned MemoryLimit) {
451   const char *Suffix = (UseIntegratedAssembler ? ".llc.o" : ".llc.s");
452   sys::Path uniqueFile(Bitcode + Suffix);
453   std::string ErrMsg;
454   if (uniqueFile.makeUnique(true, &ErrMsg)) {
455     errs() << "Error making unique filename: " << ErrMsg << "\n";
456     exit(1);
457   }
458   OutputAsmFile = uniqueFile;
459   std::vector<const char *> LLCArgs;
460   LLCArgs.push_back(LLCPath.c_str());
461
462   // Add any extra LLC args.
463   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
464     LLCArgs.push_back(ToolArgs[i].c_str());
465
466   LLCArgs.push_back("-o");
467   LLCArgs.push_back(OutputAsmFile.c_str()); // Output to the Asm file
468   LLCArgs.push_back(Bitcode.c_str());      // This is the input bitcode
469
470   if (UseIntegratedAssembler)
471     LLCArgs.push_back("-filetype=obj");
472
473   LLCArgs.push_back (0);
474
475   outs() << (UseIntegratedAssembler ? "<llc-ia>" : "<llc>");
476   outs().flush();
477   DEBUG(errs() << "\nAbout to run:\t";
478         for (unsigned i = 0, e = LLCArgs.size()-1; i != e; ++i)
479           errs() << " " << LLCArgs[i];
480         errs() << "\n";
481         );
482   if (RunProgramWithTimeout(LLCPath, &LLCArgs[0],
483                             "", "", "",
484                             Timeout, MemoryLimit))
485     Error = ProcessFailure(LLCPath, &LLCArgs[0],
486                            Timeout, MemoryLimit);
487   return UseIntegratedAssembler ? GCC::ObjectFile : GCC::AsmFile;
488 }
489
490 void LLC::compileProgram(const std::string &Bitcode, std::string *Error,
491                          unsigned Timeout, unsigned MemoryLimit) {
492   sys::Path OutputAsmFile;
493   OutputCode(Bitcode, OutputAsmFile, *Error, Timeout, MemoryLimit);
494   OutputAsmFile.eraseFromDisk();
495 }
496
497 int LLC::ExecuteProgram(const std::string &Bitcode,
498                         const std::vector<std::string> &Args,
499                         const std::string &InputFile,
500                         const std::string &OutputFile,
501                         std::string *Error,
502                         const std::vector<std::string> &ArgsForGCC,
503                         const std::vector<std::string> &SharedLibs,
504                         unsigned Timeout,
505                         unsigned MemoryLimit) {
506
507   sys::Path OutputAsmFile;
508   GCC::FileType FileKind = OutputCode(Bitcode, OutputAsmFile, *Error, Timeout,
509                                       MemoryLimit);
510   FileRemover OutFileRemover(OutputAsmFile.str(), !SaveTemps);
511
512   std::vector<std::string> GCCArgs(ArgsForGCC);
513   GCCArgs.insert(GCCArgs.end(), SharedLibs.begin(), SharedLibs.end());
514
515   // Assuming LLC worked, compile the result with GCC and run it.
516   return gcc->ExecuteProgram(OutputAsmFile.str(), Args, FileKind,
517                              InputFile, OutputFile, Error, GCCArgs,
518                              Timeout, MemoryLimit);
519 }
520
521 /// createLLC - Try to find the LLC executable
522 ///
523 LLC *AbstractInterpreter::createLLC(const char *Argv0,
524                                     std::string &Message,
525                                     const std::string &GCCBinary,
526                                     const std::vector<std::string> *Args,
527                                     const std::vector<std::string> *GCCArgs,
528                                     bool UseIntegratedAssembler) {
529   std::string LLCPath =
530     PrependMainExecutablePath("llc", Argv0, (void *)(intptr_t)&createLLC).str();
531   if (LLCPath.empty()) {
532     Message = "Cannot find `llc' in executable directory!\n";
533     return 0;
534   }
535
536   GCC *gcc = GCC::create(Message, GCCBinary, GCCArgs);
537   if (!gcc) {
538     errs() << Message << "\n";
539     exit(1);
540   }
541   Message = "Found llc: " + LLCPath + "\n";
542   return new LLC(LLCPath, gcc, Args, UseIntegratedAssembler);
543 }
544
545 //===---------------------------------------------------------------------===//
546 // JIT Implementation of AbstractIntepreter interface
547 //
548 namespace {
549   class JIT : public AbstractInterpreter {
550     std::string LLIPath;          // The path to the LLI executable
551     std::vector<std::string> ToolArgs; // Args to pass to LLI
552   public:
553     JIT(const std::string &Path, const std::vector<std::string> *Args)
554       : LLIPath(Path) {
555       ToolArgs.clear ();
556       if (Args) { ToolArgs = *Args; }
557     }
558
559     virtual int ExecuteProgram(const std::string &Bitcode,
560                                const std::vector<std::string> &Args,
561                                const std::string &InputFile,
562                                const std::string &OutputFile,
563                                std::string *Error,
564                                const std::vector<std::string> &GCCArgs =
565                                  std::vector<std::string>(),
566                                const std::vector<std::string> &SharedLibs =
567                                  std::vector<std::string>(),
568                                unsigned Timeout = 0,
569                                unsigned MemoryLimit = 0);
570   };
571 }
572
573 int JIT::ExecuteProgram(const std::string &Bitcode,
574                         const std::vector<std::string> &Args,
575                         const std::string &InputFile,
576                         const std::string &OutputFile,
577                         std::string *Error,
578                         const std::vector<std::string> &GCCArgs,
579                         const std::vector<std::string> &SharedLibs,
580                         unsigned Timeout,
581                         unsigned MemoryLimit) {
582   // Construct a vector of parameters, incorporating those from the command-line
583   std::vector<const char*> JITArgs;
584   JITArgs.push_back(LLIPath.c_str());
585   JITArgs.push_back("-force-interpreter=false");
586
587   // Add any extra LLI args.
588   for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
589     JITArgs.push_back(ToolArgs[i].c_str());
590
591   for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i) {
592     JITArgs.push_back("-load");
593     JITArgs.push_back(SharedLibs[i].c_str());
594   }
595   JITArgs.push_back(Bitcode.c_str());
596   // Add optional parameters to the running program from Argv
597   for (unsigned i=0, e = Args.size(); i != e; ++i)
598     JITArgs.push_back(Args[i].c_str());
599   JITArgs.push_back(0);
600
601   outs() << "<jit>"; outs().flush();
602   DEBUG(errs() << "\nAbout to run:\t";
603         for (unsigned i=0, e = JITArgs.size()-1; i != e; ++i)
604           errs() << " " << JITArgs[i];
605         errs() << "\n";
606         );
607   DEBUG(errs() << "\nSending output to " << OutputFile << "\n");
608   return RunProgramWithTimeout(LLIPath, &JITArgs[0],
609       InputFile, OutputFile, OutputFile,
610       Timeout, MemoryLimit, Error);
611 }
612
613 /// createJIT - Try to find the LLI executable
614 ///
615 AbstractInterpreter *AbstractInterpreter::createJIT(const char *Argv0,
616                    std::string &Message, const std::vector<std::string> *Args) {
617   std::string LLIPath =
618     PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t)&createJIT).str();
619   if (!LLIPath.empty()) {
620     Message = "Found lli: " + LLIPath + "\n";
621     return new JIT(LLIPath, Args);
622   }
623
624   Message = "Cannot find `lli' in executable directory!\n";
625   return 0;
626 }
627
628 //===---------------------------------------------------------------------===//
629 // GCC abstraction
630 //
631
632 static bool IsARMArchitecture(std::vector<const char*> Args) {
633   for (std::vector<const char*>::const_iterator
634          I = Args.begin(), E = Args.end(); I != E; ++I) {
635     if (StringRef(*I).equals_lower("-arch")) {
636       ++I;
637       if (I != E && StringRef(*I).substr(0, strlen("arm")).equals_lower("arm"))
638         return true;
639     }
640   }
641
642   return false;
643 }
644
645 int GCC::ExecuteProgram(const std::string &ProgramFile,
646                         const std::vector<std::string> &Args,
647                         FileType fileType,
648                         const std::string &InputFile,
649                         const std::string &OutputFile,
650                         std::string *Error,
651                         const std::vector<std::string> &ArgsForGCC,
652                         unsigned Timeout,
653                         unsigned MemoryLimit) {
654   std::vector<const char*> GCCArgs;
655
656   GCCArgs.push_back(GCCPath.c_str());
657
658   if (TargetTriple.getArch() == Triple::x86)
659     GCCArgs.push_back("-m32");
660
661   for (std::vector<std::string>::const_iterator
662          I = gccArgs.begin(), E = gccArgs.end(); I != E; ++I)
663     GCCArgs.push_back(I->c_str());
664
665   // Specify -x explicitly in case the extension is wonky
666   if (fileType != ObjectFile) {
667     GCCArgs.push_back("-x");
668     if (fileType == CFile) {
669       GCCArgs.push_back("c");
670       GCCArgs.push_back("-fno-strict-aliasing");
671     } else {
672       GCCArgs.push_back("assembler");
673
674       // For ARM architectures we don't want this flag. bugpoint isn't
675       // explicitly told what architecture it is working on, so we get
676       // it from gcc flags
677       if (TargetTriple.isOSDarwin() && !IsARMArchitecture(GCCArgs))
678         GCCArgs.push_back("-force_cpusubtype_ALL");
679     }
680   }
681
682   GCCArgs.push_back(ProgramFile.c_str());  // Specify the input filename.
683
684   GCCArgs.push_back("-x");
685   GCCArgs.push_back("none");
686   GCCArgs.push_back("-o");
687   sys::Path OutputBinary (ProgramFile+".gcc.exe");
688   std::string ErrMsg;
689   if (OutputBinary.makeUnique(true, &ErrMsg)) {
690     errs() << "Error making unique filename: " << ErrMsg << "\n";
691     exit(1);
692   }
693   GCCArgs.push_back(OutputBinary.c_str()); // Output to the right file...
694
695   // Add any arguments intended for GCC. We locate them here because this is
696   // most likely -L and -l options that need to come before other libraries but
697   // after the source. Other options won't be sensitive to placement on the
698   // command line, so this should be safe.
699   for (unsigned i = 0, e = ArgsForGCC.size(); i != e; ++i)
700     GCCArgs.push_back(ArgsForGCC[i].c_str());
701
702   GCCArgs.push_back("-lm");                // Hard-code the math library...
703   GCCArgs.push_back("-O2");                // Optimize the program a bit...
704 #if defined (HAVE_LINK_R)
705   GCCArgs.push_back("-Wl,-R.");            // Search this dir for .so files
706 #endif
707   if (TargetTriple.getArch() == Triple::sparc)
708     GCCArgs.push_back("-mcpu=v9");
709   GCCArgs.push_back(0);                    // NULL terminator
710
711   outs() << "<gcc>"; outs().flush();
712   DEBUG(errs() << "\nAbout to run:\t";
713         for (unsigned i = 0, e = GCCArgs.size()-1; i != e; ++i)
714           errs() << " " << GCCArgs[i];
715         errs() << "\n";
716         );
717   if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], "", "", "")) {
718     *Error = ProcessFailure(GCCPath, &GCCArgs[0]);
719     return -1;
720   }
721
722   std::vector<const char*> ProgramArgs;
723
724   // Declared here so that the destructor only runs after
725   // ProgramArgs is used.
726   std::string Exec;
727
728   if (RemoteClientPath.empty())
729     ProgramArgs.push_back(OutputBinary.c_str());
730   else {
731     ProgramArgs.push_back(RemoteClientPath.c_str());
732     ProgramArgs.push_back(RemoteHost.c_str());
733     if (!RemoteUser.empty()) {
734       ProgramArgs.push_back("-l");
735       ProgramArgs.push_back(RemoteUser.c_str());
736     }
737     if (!RemotePort.empty()) {
738       ProgramArgs.push_back("-p");
739       ProgramArgs.push_back(RemotePort.c_str());
740     }
741     if (!RemoteExtra.empty()) {
742       ProgramArgs.push_back(RemoteExtra.c_str());
743     }
744
745     // Full path to the binary. We need to cd to the exec directory because
746     // there is a dylib there that the exec expects to find in the CWD
747     char* env_pwd = getenv("PWD");
748     Exec = "cd ";
749     Exec += env_pwd;
750     Exec += "; ./";
751     Exec += OutputBinary.c_str();
752     ProgramArgs.push_back(Exec.c_str());
753   }
754
755   // Add optional parameters to the running program from Argv
756   for (unsigned i = 0, e = Args.size(); i != e; ++i)
757     ProgramArgs.push_back(Args[i].c_str());
758   ProgramArgs.push_back(0);                // NULL terminator
759
760   // Now that we have a binary, run it!
761   outs() << "<program>"; outs().flush();
762   DEBUG(errs() << "\nAbout to run:\t";
763         for (unsigned i = 0, e = ProgramArgs.size()-1; i != e; ++i)
764           errs() << " " << ProgramArgs[i];
765         errs() << "\n";
766         );
767
768   FileRemover OutputBinaryRemover(OutputBinary.str(), !SaveTemps);
769
770   if (RemoteClientPath.empty()) {
771     DEBUG(errs() << "<run locally>");
772     int ExitCode = RunProgramWithTimeout(OutputBinary.str(), &ProgramArgs[0],
773                                          InputFile, OutputFile, OutputFile,
774                                          Timeout, MemoryLimit, Error);
775     // Treat a signal (usually SIGSEGV) or timeout as part of the program output
776     // so that crash-causing miscompilation is handled seamlessly.
777     if (ExitCode < -1) {
778       std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
779       outFile << *Error << '\n';
780       outFile.close();
781       Error->clear();
782     }
783     return ExitCode;
784   } else {
785     outs() << "<run remotely>"; outs().flush();
786     return RunProgramRemotelyWithTimeout(RemoteClientPath,
787         &ProgramArgs[0], InputFile, OutputFile,
788         OutputFile, Timeout, MemoryLimit);
789   }
790 }
791
792 int GCC::MakeSharedObject(const std::string &InputFile, FileType fileType,
793                           std::string &OutputFile,
794                           const std::vector<std::string> &ArgsForGCC,
795                           std::string &Error) {
796   sys::Path uniqueFilename(InputFile+LTDL_SHLIB_EXT);
797   std::string ErrMsg;
798   if (uniqueFilename.makeUnique(true, &ErrMsg)) {
799     errs() << "Error making unique filename: " << ErrMsg << "\n";
800     exit(1);
801   }
802   OutputFile = uniqueFilename.str();
803
804   std::vector<const char*> GCCArgs;
805
806   GCCArgs.push_back(GCCPath.c_str());
807
808   if (TargetTriple.getArch() == Triple::x86)
809     GCCArgs.push_back("-m32");
810
811   for (std::vector<std::string>::const_iterator
812          I = gccArgs.begin(), E = gccArgs.end(); I != E; ++I)
813     GCCArgs.push_back(I->c_str());
814
815   // Compile the C/asm file into a shared object
816   if (fileType != ObjectFile) {
817     GCCArgs.push_back("-x");
818     GCCArgs.push_back(fileType == AsmFile ? "assembler" : "c");
819   }
820   GCCArgs.push_back("-fno-strict-aliasing");
821   GCCArgs.push_back(InputFile.c_str());   // Specify the input filename.
822   GCCArgs.push_back("-x");
823   GCCArgs.push_back("none");
824   if (TargetTriple.getArch() == Triple::sparc)
825     GCCArgs.push_back("-G");       // Compile a shared library, `-G' for Sparc
826   else if (TargetTriple.isOSDarwin()) {
827     // link all source files into a single module in data segment, rather than
828     // generating blocks. dynamic_lookup requires that you set
829     // MACOSX_DEPLOYMENT_TARGET=10.3 in your env.  FIXME: it would be better for
830     // bugpoint to just pass that in the environment of GCC.
831     GCCArgs.push_back("-single_module");
832     GCCArgs.push_back("-dynamiclib");   // `-dynamiclib' for MacOS X/PowerPC
833     GCCArgs.push_back("-undefined");
834     GCCArgs.push_back("dynamic_lookup");
835   } else
836     GCCArgs.push_back("-shared");  // `-shared' for Linux/X86, maybe others
837
838   if (TargetTriple.getArch() == Triple::x86_64)
839     GCCArgs.push_back("-fPIC");   // Requires shared objs to contain PIC
840
841   if (TargetTriple.getArch() == Triple::sparc)
842     GCCArgs.push_back("-mcpu=v9");
843
844   GCCArgs.push_back("-o");
845   GCCArgs.push_back(OutputFile.c_str()); // Output to the right filename.
846   GCCArgs.push_back("-O2");              // Optimize the program a bit.
847
848
849
850   // Add any arguments intended for GCC. We locate them here because this is
851   // most likely -L and -l options that need to come before other libraries but
852   // after the source. Other options won't be sensitive to placement on the
853   // command line, so this should be safe.
854   for (unsigned i = 0, e = ArgsForGCC.size(); i != e; ++i)
855     GCCArgs.push_back(ArgsForGCC[i].c_str());
856   GCCArgs.push_back(0);                    // NULL terminator
857
858
859
860   outs() << "<gcc>"; outs().flush();
861   DEBUG(errs() << "\nAbout to run:\t";
862         for (unsigned i = 0, e = GCCArgs.size()-1; i != e; ++i)
863           errs() << " " << GCCArgs[i];
864         errs() << "\n";
865         );
866   if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], "", "", "")) {
867     Error = ProcessFailure(GCCPath, &GCCArgs[0]);
868     return 1;
869   }
870   return 0;
871 }
872
873 /// create - Try to find the `gcc' executable
874 ///
875 GCC *GCC::create(std::string &Message,
876                  const std::string &GCCBinary,
877                  const std::vector<std::string> *Args) {
878   std::string GCCPath = sys::FindProgramByName(GCCBinary);
879   if (GCCPath.empty()) {
880     Message = "Cannot find `"+ GCCBinary +"' in PATH!\n";
881     return 0;
882   }
883
884   std::string RemoteClientPath;
885   if (!RemoteClient.empty())
886     RemoteClientPath = sys::FindProgramByName(RemoteClient);
887
888   Message = "Found gcc: " + GCCPath + "\n";
889   return new GCC(GCCPath, RemoteClientPath, Args);
890 }