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