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