1 //===-- ToolRunner.cpp ----------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the interfaces described in the ToolRunner.h file.
12 //===----------------------------------------------------------------------===//
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"
26 #define DEBUG_TYPE "toolrunner"
30 SaveTemps("save-temps", cl::init(false), cl::desc("Save temporary files"));
35 RemoteClient("remote-client",
36 cl::desc("Remote execution client (rsh/ssh)"));
39 RemoteHost("remote-host",
40 cl::desc("Remote execution (rsh/ssh) host"));
43 RemotePort("remote-port",
44 cl::desc("Remote execution (rsh/ssh) port"));
47 RemoteUser("remote-user",
48 cl::desc("Remote execution (rsh/ssh) user id"));
51 RemoteExtra("remote-extra-options",
52 cl::desc("Remote execution (rsh/ssh) extra options"));
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,
63 unsigned NumSeconds = 0,
64 unsigned MemoryLimit = 0,
65 std::string *ErrMsg = nullptr) {
66 const StringRef *Redirects[3] = { &StdInFile, &StdOutFile, &StdErrFile };
68 #if 0 // For debug purposes
71 for (unsigned i = 0; Args[i]; ++i)
72 errs() << " " << Args[i];
77 return sys::ExecuteAndWait(ProgramPath, Args, nullptr, Redirects,
78 NumSeconds, MemoryLimit, ErrMsg);
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
86 /// @see sys::Program::ExecuteAndWait
87 static int RunProgramRemotelyWithTimeout(StringRef RemoteClientPath,
92 unsigned NumSeconds = 0,
93 unsigned MemoryLimit = 0) {
94 const StringRef *Redirects[3] = { &StdInFile, &StdOutFile, &StdErrFile };
96 #if 0 // For debug purposes
99 for (unsigned i = 0; Args[i]; ++i)
100 errs() << " " << Args[i];
105 // Run the program remotely with the remote client
106 int ReturnCode = sys::ExecuteAndWait(RemoteClientPath, Args, nullptr,
107 Redirects, NumSeconds, MemoryLimit);
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)
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());
121 std::copy(std::istreambuf_iterator<char>(ErrorFile),
122 std::istreambuf_iterator<char>(),
123 std::ostreambuf_iterator<char>(OS));
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)
142 // Rerun the compiler, capturing any error messages to print them.
143 SmallString<128> ErrorFilename;
145 std::error_code EC = sys::fs::createTemporaryFile(
146 "bugpoint.program_error_messages", "", ErrorFD, ErrorFilename);
148 errs() << "Error making unique filename: " << EC.message() << "\n";
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
156 delete new raw_fd_ostream(ErrorFD, true);
159 RunProgramWithTimeout(ProgPath, Args, "", ErrorFilename.str(),
160 ErrorFilename.str(), Timeout, MemoryLimit);
161 // FIXME: check return code ?
163 // Print out the error messages generated by GCC if possible...
164 std::ifstream ErrorFile(ErrorFilename.c_str());
166 std::copy(std::istreambuf_iterator<char>(ErrorFile),
167 std::istreambuf_iterator<char>(),
168 std::ostreambuf_iterator<char>(OS));
172 sys::fs::remove(ErrorFilename.c_str());
176 //===---------------------------------------------------------------------===//
177 // LLI Implementation of AbstractIntepreter interface
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
184 LLI(const std::string &Path, const std::vector<std::string> *Args)
187 if (Args) { ToolArgs = *Args; }
190 int ExecuteProgram(const std::string &Bitcode,
191 const std::vector<std::string> &Args,
192 const std::string &InputFile,
193 const std::string &OutputFile,
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;
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,
208 const std::vector<std::string> &GCCArgs,
209 const std::vector<std::string> &SharedLibs,
211 unsigned MemoryLimit) {
212 std::vector<const char*> LLIArgs;
213 LLIArgs.push_back(LLIPath.c_str());
214 LLIArgs.push_back("-force-interpreter=true");
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());
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());
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);
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];
238 return RunProgramWithTimeout(LLIPath, &LLIArgs[0],
239 InputFile, OutputFile, OutputFile,
240 Timeout, MemoryLimit, Error);
243 void AbstractInterpreter::anchor() { }
245 #if defined(LLVM_ON_UNIX)
246 const char EXESuffix[] = "";
247 #elif defined (LLVM_ON_WIN32)
248 const char EXESuffix[] = "exe";
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,
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);
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();
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);
287 Message = "Cannot find `lli' in executable directory!\n";
291 //===---------------------------------------------------------------------===//
292 // Custom compiler command implementation of AbstractIntepreter interface
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.
298 class CustomCompiler : public AbstractInterpreter {
299 std::string CompilerCommand;
300 std::vector<std::string> CompilerArgs;
303 const std::string &CompilerCmd, std::vector<std::string> CompArgs) :
304 CompilerCommand(CompilerCmd), CompilerArgs(CompArgs) {}
306 void compileProgram(const std::string &Bitcode,
308 unsigned Timeout = 0,
309 unsigned MemoryLimit = 0) override;
311 int ExecuteProgram(const std::string &Bitcode,
312 const std::vector<std::string> &Args,
313 const std::string &InputFile,
314 const std::string &OutputFile,
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";
328 void CustomCompiler::compileProgram(const std::string &Bitcode,
331 unsigned MemoryLimit) {
333 std::vector<const char*> ProgramArgs;
334 ProgramArgs.push_back(CompilerCommand.c_str());
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);
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());
345 if (RunProgramWithTimeout(CompilerCommand, &ProgramArgs[0],
347 Timeout, MemoryLimit, Error))
348 *Error = ProcessFailure(CompilerCommand, &ProgramArgs[0],
349 Timeout, MemoryLimit);
352 //===---------------------------------------------------------------------===//
353 // Custom execution command implementation of AbstractIntepreter interface
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.
359 class CustomExecutor : public AbstractInterpreter {
360 std::string ExecutionCommand;
361 std::vector<std::string> ExecutorArgs;
364 const std::string &ExecutionCmd, std::vector<std::string> ExecArgs) :
365 ExecutionCommand(ExecutionCmd), ExecutorArgs(ExecArgs) {}
367 int ExecuteProgram(const std::string &Bitcode,
368 const std::vector<std::string> &Args,
369 const std::string &InputFile,
370 const std::string &OutputFile,
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;
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,
385 const std::vector<std::string> &GCCArgs,
386 const std::vector<std::string> &SharedLibs,
388 unsigned MemoryLimit) {
390 std::vector<const char*> ProgramArgs;
391 ProgramArgs.push_back(ExecutionCommand.c_str());
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);
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());
402 return RunProgramWithTimeout(
404 &ProgramArgs[0], InputFile, OutputFile,
405 OutputFile, Timeout, MemoryLimit, Error);
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").
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) {
420 std::string Command = "";
421 std::string delimiters = " ";
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);
426 while (std::string::npos != pos || std::string::npos != lastPos) {
427 std::string token = CommandLine.substr(lastPos, pos - lastPos);
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);
438 CmdPath = sys::FindProgramByName(Command);
439 if (CmdPath.empty()) {
441 std::string("Cannot find '") + Command +
446 Message = "Found command in: " + CmdPath + "\n";
449 // Custom execution environment create method, takes the execution command
451 AbstractInterpreter *AbstractInterpreter::createCustomCompiler(
452 std::string &Message,
453 const std::string &CompileCommandLine) {
456 std::vector<std::string> Args;
457 lexCommand(Message, CompileCommandLine, CmdPath, Args);
461 return new CustomCompiler(CmdPath, Args);
464 // Custom execution environment create method, takes the execution command
466 AbstractInterpreter *AbstractInterpreter::createCustomExecutor(
467 std::string &Message,
468 const std::string &ExecCommandLine) {
472 std::vector<std::string> Args;
473 lexCommand(Message, ExecCommandLine, CmdPath, Args);
477 return new CustomExecutor(CmdPath, Args);
480 //===----------------------------------------------------------------------===//
481 // LLC Implementation of AbstractIntepreter interface
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");
488 SmallString<128> UniqueFile;
490 sys::fs::createUniqueFile(Bitcode + "-%%%%%%%" + Suffix, UniqueFile);
492 errs() << "Error making unique filename: " << EC.message() << "\n";
495 OutputAsmFile = UniqueFile.str();
496 std::vector<const char *> LLCArgs;
497 LLCArgs.push_back(LLCPath.c_str());
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());
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
507 if (UseIntegratedAssembler)
508 LLCArgs.push_back("-filetype=obj");
510 LLCArgs.push_back (nullptr);
512 outs() << (UseIntegratedAssembler ? "<llc-ia>" : "<llc>");
514 DEBUG(errs() << "\nAbout to run:\t";
515 for (unsigned i = 0, e = LLCArgs.size()-1; i != e; ++i)
516 errs() << " " << LLCArgs[i];
519 if (RunProgramWithTimeout(LLCPath, &LLCArgs[0],
521 Timeout, MemoryLimit))
522 Error = ProcessFailure(LLCPath, &LLCArgs[0],
523 Timeout, MemoryLimit);
524 return UseIntegratedAssembler ? GCC::ObjectFile : GCC::AsmFile;
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);
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,
539 const std::vector<std::string> &ArgsForGCC,
540 const std::vector<std::string> &SharedLibs,
542 unsigned MemoryLimit) {
544 std::string OutputAsmFile;
545 GCC::FileType FileKind = OutputCode(Bitcode, OutputAsmFile, *Error, Timeout,
547 FileRemover OutFileRemover(OutputAsmFile, !SaveTemps);
549 std::vector<std::string> GCCArgs(ArgsForGCC);
550 GCCArgs.insert(GCCArgs.end(), SharedLibs.begin(), SharedLibs.end());
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);
558 /// createLLC - Try to find the LLC executable
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";
573 GCC *gcc = GCC::create(Message, GCCBinary, GCCArgs);
575 errs() << Message << "\n";
578 Message = "Found llc: " + LLCPath + "\n";
579 return new LLC(LLCPath, gcc, Args, UseIntegratedAssembler);
582 //===---------------------------------------------------------------------===//
583 // JIT Implementation of AbstractIntepreter interface
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
590 JIT(const std::string &Path, const std::vector<std::string> *Args)
593 if (Args) { ToolArgs = *Args; }
596 int ExecuteProgram(const std::string &Bitcode,
597 const std::vector<std::string> &Args,
598 const std::string &InputFile,
599 const std::string &OutputFile,
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;
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,
615 const std::vector<std::string> &GCCArgs,
616 const std::vector<std::string> &SharedLibs,
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");
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());
628 for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i) {
629 JITArgs.push_back("-load");
630 JITArgs.push_back(SharedLibs[i].c_str());
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);
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];
644 DEBUG(errs() << "\nSending output to " << OutputFile << "\n");
645 return RunProgramWithTimeout(LLIPath, &JITArgs[0],
646 InputFile, OutputFile, OutputFile,
647 Timeout, MemoryLimit, Error);
650 /// createJIT - Try to find the LLI executable
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);
661 Message = "Cannot find `lli' in executable directory!\n";
665 //===---------------------------------------------------------------------===//
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")) {
674 if (I != E && StringRef(*I).startswith_lower("arm"))
682 int GCC::ExecuteProgram(const std::string &ProgramFile,
683 const std::vector<std::string> &Args,
685 const std::string &InputFile,
686 const std::string &OutputFile,
688 const std::vector<std::string> &ArgsForGCC,
690 unsigned MemoryLimit) {
691 std::vector<const char*> GCCArgs;
693 GCCArgs.push_back(GCCPath.c_str());
695 if (TargetTriple.getArch() == Triple::x86)
696 GCCArgs.push_back("-m32");
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());
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");
709 GCCArgs.push_back("assembler");
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
714 if (TargetTriple.isOSDarwin() && !IsARMArchitecture(GCCArgs))
715 GCCArgs.push_back("-force_cpusubtype_ALL");
719 GCCArgs.push_back(ProgramFile.c_str()); // Specify the input filename.
721 GCCArgs.push_back("-x");
722 GCCArgs.push_back("none");
723 GCCArgs.push_back("-o");
725 SmallString<128> OutputBinary;
727 sys::fs::createUniqueFile(ProgramFile + "-%%%%%%%.gcc.exe", OutputBinary);
729 errs() << "Error making unique filename: " << EC.message() << "\n";
732 GCCArgs.push_back(OutputBinary.c_str()); // Output to the right file...
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());
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
746 if (TargetTriple.getArch() == Triple::sparc)
747 GCCArgs.push_back("-mcpu=v9");
748 GCCArgs.push_back(nullptr); // NULL terminator
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];
756 if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], "", "", "")) {
757 *Error = ProcessFailure(GCCPath, &GCCArgs[0]);
761 std::vector<const char*> ProgramArgs;
763 // Declared here so that the destructor only runs after
764 // ProgramArgs is used.
767 if (RemoteClientPath.empty())
768 ProgramArgs.push_back(OutputBinary.c_str());
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());
776 if (!RemotePort.empty()) {
777 ProgramArgs.push_back("-p");
778 ProgramArgs.push_back(RemotePort.c_str());
780 if (!RemoteExtra.empty()) {
781 ProgramArgs.push_back(RemoteExtra.c_str());
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");
790 Exec += OutputBinary.c_str();
791 ProgramArgs.push_back(Exec.c_str());
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
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];
807 FileRemover OutputBinaryRemover(OutputBinary.str(), !SaveTemps);
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.
817 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
818 outFile << *Error << '\n';
824 outs() << "<run remotely>"; outs().flush();
825 return RunProgramRemotelyWithTimeout(RemoteClientPath,
826 &ProgramArgs[0], InputFile, OutputFile,
827 OutputFile, Timeout, MemoryLimit);
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);
839 errs() << "Error making unique filename: " << EC.message() << "\n";
842 OutputFile = UniqueFilename.str();
844 std::vector<const char*> GCCArgs;
846 GCCArgs.push_back(GCCPath.c_str());
848 if (TargetTriple.getArch() == Triple::x86)
849 GCCArgs.push_back("-m32");
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());
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");
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");
876 GCCArgs.push_back("-shared"); // `-shared' for Linux/X86, maybe others
878 if (TargetTriple.getArch() == Triple::x86_64)
879 GCCArgs.push_back("-fPIC"); // Requires shared objs to contain PIC
881 if (TargetTriple.getArch() == Triple::sparc)
882 GCCArgs.push_back("-mcpu=v9");
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.
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
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];
906 if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], "", "", "")) {
907 Error = ProcessFailure(GCCPath, &GCCArgs[0]);
913 /// create - Try to find the `gcc' executable
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";
924 std::string RemoteClientPath;
925 if (!RemoteClient.empty())
926 RemoteClientPath = sys::FindProgramByName(RemoteClient);
928 Message = "Found gcc: " + GCCPath + "\n";
929 return new GCC(GCCPath, RemoteClientPath, Args);