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 #define DEBUG_TYPE "toolrunner"
15 #include "ToolRunner.h"
16 #include "llvm/Support/Program.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Config/config.h" // for HAVE_LINK_R
28 SaveTemps("save-temps", cl::init(false), cl::desc("Save temporary files"));
33 RemoteClient("remote-client",
34 cl::desc("Remote execution client (rsh/ssh)"));
37 RemoteHost("remote-host",
38 cl::desc("Remote execution (rsh/ssh) host"));
41 RemotePort("remote-port",
42 cl::desc("Remote execution (rsh/ssh) port"));
45 RemoteUser("remote-user",
46 cl::desc("Remote execution (rsh/ssh) user id"));
49 RemoteExtra("remote-extra-options",
50 cl::desc("Remote execution (rsh/ssh) extra options"));
53 // Add a prefix to ErrMsg if the program is terminated by a signal to
54 // distinguish compiled program crashes from other execution
55 // failures. Miscompilation likely results in SIGSEGV.
56 static const char *SignalPrefix = "Signal - ";
58 /// RunProgramWithTimeout - This function provides an alternate interface
59 /// to the sys::Program::ExecuteAndWait interface.
60 /// @see sys::Program::ExecuteAndWait
61 static int RunProgramWithTimeout(const sys::Path &ProgramPath,
63 const sys::Path &StdInFile,
64 const sys::Path &StdOutFile,
65 const sys::Path &StdErrFile,
66 unsigned NumSeconds = 0,
67 unsigned MemoryLimit = 0,
68 std::string *ErrMsg = 0) {
69 const sys::Path* redirects[3];
70 redirects[0] = &StdInFile;
71 redirects[1] = &StdOutFile;
72 redirects[2] = &StdErrFile;
74 #if 0 // For debug purposes
77 for (unsigned i = 0; Args[i]; ++i)
78 errs() << " " << Args[i];
84 sys::Program::ExecuteAndWait(ProgramPath, Args, 0, redirects,
85 NumSeconds, MemoryLimit, ErrMsg, SignalPrefix);
88 /// RunProgramRemotelyWithTimeout - This function runs the given program
89 /// remotely using the given remote client and the sys::Program::ExecuteAndWait.
90 /// Returns the remote program exit code or reports a remote client error if it
91 /// fails. Remote client is required to return 255 if it failed or program exit
93 /// @see sys::Program::ExecuteAndWait
94 static int RunProgramRemotelyWithTimeout(const sys::Path &RemoteClientPath,
96 const sys::Path &StdInFile,
97 const sys::Path &StdOutFile,
98 const sys::Path &StdErrFile,
99 unsigned NumSeconds = 0,
100 unsigned MemoryLimit = 0) {
101 const sys::Path* redirects[3];
102 redirects[0] = &StdInFile;
103 redirects[1] = &StdOutFile;
104 redirects[2] = &StdErrFile;
106 #if 0 // For debug purposes
109 for (unsigned i = 0; Args[i]; ++i)
110 errs() << " " << Args[i];
115 // Run the program remotely with the remote client
116 int ReturnCode = sys::Program::ExecuteAndWait(RemoteClientPath, Args,
117 0, redirects, NumSeconds, MemoryLimit);
119 // Has the remote client fail?
120 if (255 == ReturnCode) {
121 std::ostringstream OS;
122 OS << "\nError running remote client:\n ";
123 for (const char **Arg = Args; *Arg; ++Arg)
127 // The error message is in the output file, let's print it out from there.
128 std::ifstream ErrorFile(StdOutFile.c_str());
130 std::copy(std::istreambuf_iterator<char>(ErrorFile),
131 std::istreambuf_iterator<char>(),
132 std::ostreambuf_iterator<char>(OS));
142 static std::string ProcessFailure(sys::Path ProgPath, const char** Args,
143 unsigned Timeout = 0,
144 unsigned MemoryLimit = 0) {
145 std::ostringstream OS;
146 OS << "\nError running tool:\n ";
147 for (const char **Arg = Args; *Arg; ++Arg)
151 // Rerun the compiler, capturing any error messages to print them.
152 sys::Path ErrorFilename("bugpoint.program_error_messages");
154 if (ErrorFilename.makeUnique(true, &ErrMsg)) {
155 errs() << "Error making unique filename: " << ErrMsg << "\n";
158 RunProgramWithTimeout(ProgPath, Args, sys::Path(""), ErrorFilename,
159 ErrorFilename, Timeout, MemoryLimit);
160 // FIXME: check return code ?
162 // Print out the error messages generated by GCC if possible...
163 std::ifstream ErrorFile(ErrorFilename.c_str());
165 std::copy(std::istreambuf_iterator<char>(ErrorFile),
166 std::istreambuf_iterator<char>(),
167 std::ostreambuf_iterator<char>(OS));
171 ErrorFilename.eraseFromDisk();
175 //===---------------------------------------------------------------------===//
176 // LLI Implementation of AbstractIntepreter interface
179 class LLI : public AbstractInterpreter {
180 std::string LLIPath; // The path to the LLI executable
181 std::vector<std::string> ToolArgs; // Args to pass to LLI
183 LLI(const std::string &Path, const std::vector<std::string> *Args)
186 if (Args) { ToolArgs = *Args; }
189 virtual int ExecuteProgram(const std::string &Bitcode,
190 const std::vector<std::string> &Args,
191 const std::string &InputFile,
192 const std::string &OutputFile,
194 const std::vector<std::string> &GCCArgs,
195 const std::vector<std::string> &SharedLibs =
196 std::vector<std::string>(),
197 unsigned Timeout = 0,
198 unsigned MemoryLimit = 0);
202 int LLI::ExecuteProgram(const std::string &Bitcode,
203 const std::vector<std::string> &Args,
204 const std::string &InputFile,
205 const std::string &OutputFile,
207 const std::vector<std::string> &GCCArgs,
208 const std::vector<std::string> &SharedLibs,
210 unsigned MemoryLimit) {
211 std::vector<const char*> LLIArgs;
212 LLIArgs.push_back(LLIPath.c_str());
213 LLIArgs.push_back("-force-interpreter=true");
215 for (std::vector<std::string>::const_iterator i = SharedLibs.begin(),
216 e = SharedLibs.end(); i != e; ++i) {
217 LLIArgs.push_back("-load");
218 LLIArgs.push_back((*i).c_str());
221 // Add any extra LLI args.
222 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
223 LLIArgs.push_back(ToolArgs[i].c_str());
225 LLIArgs.push_back(Bitcode.c_str());
226 // Add optional parameters to the running program from Argv
227 for (unsigned i=0, e = Args.size(); i != e; ++i)
228 LLIArgs.push_back(Args[i].c_str());
229 LLIArgs.push_back(0);
231 outs() << "<lli>"; outs().flush();
232 DEBUG(errs() << "\nAbout to run:\t";
233 for (unsigned i=0, e = LLIArgs.size()-1; i != e; ++i)
234 errs() << " " << LLIArgs[i];
237 return RunProgramWithTimeout(sys::Path(LLIPath), &LLIArgs[0],
238 sys::Path(InputFile), sys::Path(OutputFile), sys::Path(OutputFile),
239 Timeout, MemoryLimit, Error);
242 // LLI create method - Try to find the LLI executable
243 AbstractInterpreter *AbstractInterpreter::createLLI(const char *Argv0,
244 std::string &Message,
245 const std::vector<std::string> *ToolArgs) {
246 std::string LLIPath =
247 PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t)&createLLI).str();
248 if (!LLIPath.empty()) {
249 Message = "Found lli: " + LLIPath + "\n";
250 return new LLI(LLIPath, ToolArgs);
253 Message = "Cannot find `lli' in executable directory!\n";
257 //===---------------------------------------------------------------------===//
258 // Custom compiler command implementation of AbstractIntepreter interface
260 // Allows using a custom command for compiling the bitcode, thus allows, for
261 // example, to compile a bitcode fragment without linking or executing, then
262 // using a custom wrapper script to check for compiler errors.
264 class CustomCompiler : public AbstractInterpreter {
265 std::string CompilerCommand;
266 std::vector<std::string> CompilerArgs;
269 const std::string &CompilerCmd, std::vector<std::string> CompArgs) :
270 CompilerCommand(CompilerCmd), CompilerArgs(CompArgs) {}
272 virtual void compileProgram(const std::string &Bitcode,
274 unsigned Timeout = 0,
275 unsigned MemoryLimit = 0);
277 virtual int ExecuteProgram(const std::string &Bitcode,
278 const std::vector<std::string> &Args,
279 const std::string &InputFile,
280 const std::string &OutputFile,
282 const std::vector<std::string> &GCCArgs =
283 std::vector<std::string>(),
284 const std::vector<std::string> &SharedLibs =
285 std::vector<std::string>(),
286 unsigned Timeout = 0,
287 unsigned MemoryLimit = 0) {
288 *Error = "Execution not supported with -compile-custom";
294 void CustomCompiler::compileProgram(const std::string &Bitcode,
297 unsigned MemoryLimit) {
299 std::vector<const char*> ProgramArgs;
300 ProgramArgs.push_back(CompilerCommand.c_str());
302 for (std::size_t i = 0; i < CompilerArgs.size(); ++i)
303 ProgramArgs.push_back(CompilerArgs.at(i).c_str());
304 ProgramArgs.push_back(Bitcode.c_str());
305 ProgramArgs.push_back(0);
307 // Add optional parameters to the running program from Argv
308 for (unsigned i = 0, e = CompilerArgs.size(); i != e; ++i)
309 ProgramArgs.push_back(CompilerArgs[i].c_str());
311 if (RunProgramWithTimeout( sys::Path(CompilerCommand), &ProgramArgs[0],
312 sys::Path(), sys::Path(), sys::Path(),
313 Timeout, MemoryLimit, Error))
314 *Error = ProcessFailure(sys::Path(CompilerCommand), &ProgramArgs[0],
315 Timeout, MemoryLimit);
318 //===---------------------------------------------------------------------===//
319 // Custom execution command implementation of AbstractIntepreter interface
321 // Allows using a custom command for executing the bitcode, thus allows,
322 // for example, to invoke a cross compiler for code generation followed by
323 // a simulator that executes the generated binary.
325 class CustomExecutor : public AbstractInterpreter {
326 std::string ExecutionCommand;
327 std::vector<std::string> ExecutorArgs;
330 const std::string &ExecutionCmd, std::vector<std::string> ExecArgs) :
331 ExecutionCommand(ExecutionCmd), ExecutorArgs(ExecArgs) {}
333 virtual int ExecuteProgram(const std::string &Bitcode,
334 const std::vector<std::string> &Args,
335 const std::string &InputFile,
336 const std::string &OutputFile,
338 const std::vector<std::string> &GCCArgs,
339 const std::vector<std::string> &SharedLibs =
340 std::vector<std::string>(),
341 unsigned Timeout = 0,
342 unsigned MemoryLimit = 0);
346 int CustomExecutor::ExecuteProgram(const std::string &Bitcode,
347 const std::vector<std::string> &Args,
348 const std::string &InputFile,
349 const std::string &OutputFile,
351 const std::vector<std::string> &GCCArgs,
352 const std::vector<std::string> &SharedLibs,
354 unsigned MemoryLimit) {
356 std::vector<const char*> ProgramArgs;
357 ProgramArgs.push_back(ExecutionCommand.c_str());
359 for (std::size_t i = 0; i < ExecutorArgs.size(); ++i)
360 ProgramArgs.push_back(ExecutorArgs.at(i).c_str());
361 ProgramArgs.push_back(Bitcode.c_str());
362 ProgramArgs.push_back(0);
364 // Add optional parameters to the running program from Argv
365 for (unsigned i = 0, e = Args.size(); i != e; ++i)
366 ProgramArgs.push_back(Args[i].c_str());
368 return RunProgramWithTimeout(
369 sys::Path(ExecutionCommand),
370 &ProgramArgs[0], sys::Path(InputFile), sys::Path(OutputFile),
371 sys::Path(OutputFile), Timeout, MemoryLimit, Error);
374 // Tokenize the CommandLine to the command and the args to allow
375 // defining a full command line as the command instead of just the
376 // executed program. We cannot just pass the whole string after the command
377 // as a single argument because then program sees only a single
378 // command line argument (with spaces in it: "foo bar" instead
379 // of "foo" and "bar").
381 // code borrowed from:
382 // http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
383 static void lexCommand(std::string &Message, const std::string &CommandLine,
384 std::string &CmdPath, std::vector<std::string> Args) {
386 std::string Command = "";
387 std::string delimiters = " ";
389 std::string::size_type lastPos = CommandLine.find_first_not_of(delimiters, 0);
390 std::string::size_type pos = CommandLine.find_first_of(delimiters, lastPos);
392 while (std::string::npos != pos || std::string::npos != lastPos) {
393 std::string token = CommandLine.substr(lastPos, pos - lastPos);
397 Args.push_back(token);
398 // Skip delimiters. Note the "not_of"
399 lastPos = CommandLine.find_first_not_of(delimiters, pos);
400 // Find next "non-delimiter"
401 pos = CommandLine.find_first_of(delimiters, lastPos);
404 CmdPath = sys::Program::FindProgramByName(Command).str();
405 if (CmdPath.empty()) {
407 std::string("Cannot find '") + Command +
412 Message = "Found command in: " + CmdPath + "\n";
415 // Custom execution environment create method, takes the execution command
417 AbstractInterpreter *AbstractInterpreter::createCustomCompiler(
418 std::string &Message,
419 const std::string &CompileCommandLine) {
422 std::vector<std::string> Args;
423 lexCommand(Message, CompileCommandLine, CmdPath, Args);
427 return new CustomCompiler(CmdPath, Args);
430 // Custom execution environment create method, takes the execution command
432 AbstractInterpreter *AbstractInterpreter::createCustomExecutor(
433 std::string &Message,
434 const std::string &ExecCommandLine) {
438 std::vector<std::string> Args;
439 lexCommand(Message, ExecCommandLine, CmdPath, Args);
443 return new CustomExecutor(CmdPath, Args);
446 //===----------------------------------------------------------------------===//
447 // LLC Implementation of AbstractIntepreter interface
449 GCC::FileType LLC::OutputCode(const std::string &Bitcode,
450 sys::Path &OutputAsmFile, std::string &Error,
451 unsigned Timeout, unsigned MemoryLimit) {
452 const char *Suffix = (UseIntegratedAssembler ? ".llc.o" : ".llc.s");
453 sys::Path uniqueFile(Bitcode + Suffix);
455 if (uniqueFile.makeUnique(true, &ErrMsg)) {
456 errs() << "Error making unique filename: " << ErrMsg << "\n";
459 OutputAsmFile = uniqueFile;
460 std::vector<const char *> LLCArgs;
461 LLCArgs.push_back(LLCPath.c_str());
463 // Add any extra LLC args.
464 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
465 LLCArgs.push_back(ToolArgs[i].c_str());
467 LLCArgs.push_back("-o");
468 LLCArgs.push_back(OutputAsmFile.c_str()); // Output to the Asm file
469 LLCArgs.push_back(Bitcode.c_str()); // This is the input bitcode
471 if (UseIntegratedAssembler)
472 LLCArgs.push_back("-filetype=obj");
474 LLCArgs.push_back (0);
476 outs() << (UseIntegratedAssembler ? "<llc-ia>" : "<llc>");
478 DEBUG(errs() << "\nAbout to run:\t";
479 for (unsigned i = 0, e = LLCArgs.size()-1; i != e; ++i)
480 errs() << " " << LLCArgs[i];
483 if (RunProgramWithTimeout(sys::Path(LLCPath), &LLCArgs[0],
484 sys::Path(), sys::Path(), sys::Path(),
485 Timeout, MemoryLimit))
486 Error = ProcessFailure(sys::Path(LLCPath), &LLCArgs[0],
487 Timeout, MemoryLimit);
488 return UseIntegratedAssembler ? GCC::ObjectFile : GCC::AsmFile;
491 void LLC::compileProgram(const std::string &Bitcode, std::string *Error,
492 unsigned Timeout, unsigned MemoryLimit) {
493 sys::Path OutputAsmFile;
494 OutputCode(Bitcode, OutputAsmFile, *Error, Timeout, MemoryLimit);
495 OutputAsmFile.eraseFromDisk();
498 int LLC::ExecuteProgram(const std::string &Bitcode,
499 const std::vector<std::string> &Args,
500 const std::string &InputFile,
501 const std::string &OutputFile,
503 const std::vector<std::string> &ArgsForGCC,
504 const std::vector<std::string> &SharedLibs,
506 unsigned MemoryLimit) {
508 sys::Path OutputAsmFile;
509 GCC::FileType FileKind = OutputCode(Bitcode, OutputAsmFile, *Error, Timeout,
511 FileRemover OutFileRemover(OutputAsmFile.str(), !SaveTemps);
513 std::vector<std::string> GCCArgs(ArgsForGCC);
514 GCCArgs.insert(GCCArgs.end(), SharedLibs.begin(), SharedLibs.end());
516 // Assuming LLC worked, compile the result with GCC and run it.
517 return gcc->ExecuteProgram(OutputAsmFile.str(), Args, FileKind,
518 InputFile, OutputFile, Error, GCCArgs,
519 Timeout, MemoryLimit);
522 /// createLLC - Try to find the LLC executable
524 LLC *AbstractInterpreter::createLLC(const char *Argv0,
525 std::string &Message,
526 const std::string &GCCBinary,
527 const std::vector<std::string> *Args,
528 const std::vector<std::string> *GCCArgs,
529 bool UseIntegratedAssembler) {
530 std::string LLCPath =
531 PrependMainExecutablePath("llc", Argv0, (void *)(intptr_t)&createLLC).str();
532 if (LLCPath.empty()) {
533 Message = "Cannot find `llc' in executable directory!\n";
537 Message = "Found llc: " + LLCPath + "\n";
538 GCC *gcc = GCC::create(Message, GCCBinary, GCCArgs);
540 errs() << Message << "\n";
543 return new LLC(LLCPath, gcc, Args, UseIntegratedAssembler);
546 //===---------------------------------------------------------------------===//
547 // JIT Implementation of AbstractIntepreter interface
550 class JIT : public AbstractInterpreter {
551 std::string LLIPath; // The path to the LLI executable
552 std::vector<std::string> ToolArgs; // Args to pass to LLI
554 JIT(const std::string &Path, const std::vector<std::string> *Args)
557 if (Args) { ToolArgs = *Args; }
560 virtual int ExecuteProgram(const std::string &Bitcode,
561 const std::vector<std::string> &Args,
562 const std::string &InputFile,
563 const std::string &OutputFile,
565 const std::vector<std::string> &GCCArgs =
566 std::vector<std::string>(),
567 const std::vector<std::string> &SharedLibs =
568 std::vector<std::string>(),
569 unsigned Timeout = 0,
570 unsigned MemoryLimit = 0);
574 int JIT::ExecuteProgram(const std::string &Bitcode,
575 const std::vector<std::string> &Args,
576 const std::string &InputFile,
577 const std::string &OutputFile,
579 const std::vector<std::string> &GCCArgs,
580 const std::vector<std::string> &SharedLibs,
582 unsigned MemoryLimit) {
583 // Construct a vector of parameters, incorporating those from the command-line
584 std::vector<const char*> JITArgs;
585 JITArgs.push_back(LLIPath.c_str());
586 JITArgs.push_back("-force-interpreter=false");
588 // Add any extra LLI args.
589 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
590 JITArgs.push_back(ToolArgs[i].c_str());
592 for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i) {
593 JITArgs.push_back("-load");
594 JITArgs.push_back(SharedLibs[i].c_str());
596 JITArgs.push_back(Bitcode.c_str());
597 // Add optional parameters to the running program from Argv
598 for (unsigned i=0, e = Args.size(); i != e; ++i)
599 JITArgs.push_back(Args[i].c_str());
600 JITArgs.push_back(0);
602 outs() << "<jit>"; outs().flush();
603 DEBUG(errs() << "\nAbout to run:\t";
604 for (unsigned i=0, e = JITArgs.size()-1; i != e; ++i)
605 errs() << " " << JITArgs[i];
608 DEBUG(errs() << "\nSending output to " << OutputFile << "\n");
609 return RunProgramWithTimeout(sys::Path(LLIPath), &JITArgs[0],
610 sys::Path(InputFile), sys::Path(OutputFile), sys::Path(OutputFile),
611 Timeout, MemoryLimit, Error);
614 /// createJIT - Try to find the LLI executable
616 AbstractInterpreter *AbstractInterpreter::createJIT(const char *Argv0,
617 std::string &Message, const std::vector<std::string> *Args) {
618 std::string LLIPath =
619 PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t)&createJIT).str();
620 if (!LLIPath.empty()) {
621 Message = "Found lli: " + LLIPath + "\n";
622 return new JIT(LLIPath, Args);
625 Message = "Cannot find `lli' in executable directory!\n";
629 GCC::FileType CBE::OutputCode(const std::string &Bitcode,
630 sys::Path &OutputCFile, std::string &Error,
631 unsigned Timeout, unsigned MemoryLimit) {
632 sys::Path uniqueFile(Bitcode+".cbe.c");
634 if (uniqueFile.makeUnique(true, &ErrMsg)) {
635 errs() << "Error making unique filename: " << ErrMsg << "\n";
638 OutputCFile = uniqueFile;
639 std::vector<const char *> LLCArgs;
640 LLCArgs.push_back(LLCPath.c_str());
642 // Add any extra LLC args.
643 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
644 LLCArgs.push_back(ToolArgs[i].c_str());
646 LLCArgs.push_back("-o");
647 LLCArgs.push_back(OutputCFile.c_str()); // Output to the C file
648 LLCArgs.push_back("-march=c"); // Output C language
649 LLCArgs.push_back(Bitcode.c_str()); // This is the input bitcode
650 LLCArgs.push_back(0);
652 outs() << "<cbe>"; outs().flush();
653 DEBUG(errs() << "\nAbout to run:\t";
654 for (unsigned i = 0, e = LLCArgs.size()-1; i != e; ++i)
655 errs() << " " << LLCArgs[i];
658 if (RunProgramWithTimeout(LLCPath, &LLCArgs[0], sys::Path(), sys::Path(),
659 sys::Path(), Timeout, MemoryLimit))
660 Error = ProcessFailure(LLCPath, &LLCArgs[0], Timeout, MemoryLimit);
664 void CBE::compileProgram(const std::string &Bitcode, std::string *Error,
665 unsigned Timeout, unsigned MemoryLimit) {
666 sys::Path OutputCFile;
667 OutputCode(Bitcode, OutputCFile, *Error, Timeout, MemoryLimit);
668 OutputCFile.eraseFromDisk();
671 int CBE::ExecuteProgram(const std::string &Bitcode,
672 const std::vector<std::string> &Args,
673 const std::string &InputFile,
674 const std::string &OutputFile,
676 const std::vector<std::string> &ArgsForGCC,
677 const std::vector<std::string> &SharedLibs,
679 unsigned MemoryLimit) {
680 sys::Path OutputCFile;
681 OutputCode(Bitcode, OutputCFile, *Error, Timeout, MemoryLimit);
683 FileRemover CFileRemove(OutputCFile.str(), !SaveTemps);
685 std::vector<std::string> GCCArgs(ArgsForGCC);
686 GCCArgs.insert(GCCArgs.end(), SharedLibs.begin(), SharedLibs.end());
688 return gcc->ExecuteProgram(OutputCFile.str(), Args, GCC::CFile,
689 InputFile, OutputFile, Error, GCCArgs,
690 Timeout, MemoryLimit);
693 /// createCBE - Try to find the 'llc' executable
695 CBE *AbstractInterpreter::createCBE(const char *Argv0,
696 std::string &Message,
697 const std::string &GCCBinary,
698 const std::vector<std::string> *Args,
699 const std::vector<std::string> *GCCArgs) {
701 PrependMainExecutablePath("llc", Argv0, (void *)(intptr_t)&createCBE);
702 if (LLCPath.isEmpty()) {
704 "Cannot find `llc' in executable directory!\n";
708 Message = "Found llc: " + LLCPath.str() + "\n";
709 GCC *gcc = GCC::create(Message, GCCBinary, GCCArgs);
711 errs() << Message << "\n";
714 return new CBE(LLCPath, gcc, Args);
717 //===---------------------------------------------------------------------===//
721 static bool IsARMArchitecture(std::vector<const char*> Args) {
722 for (std::vector<const char*>::const_iterator
723 I = Args.begin(), E = Args.end(); I != E; ++I) {
724 if (StringRef(*I).equals_lower("-arch")) {
726 if (I != E && StringRef(*I).substr(0, strlen("arm")).equals_lower("arm"))
734 int GCC::ExecuteProgram(const std::string &ProgramFile,
735 const std::vector<std::string> &Args,
737 const std::string &InputFile,
738 const std::string &OutputFile,
740 const std::vector<std::string> &ArgsForGCC,
742 unsigned MemoryLimit) {
743 std::vector<const char*> GCCArgs;
745 GCCArgs.push_back(GCCPath.c_str());
747 if (TargetTriple.getArch() == Triple::x86)
748 GCCArgs.push_back("-m32");
750 for (std::vector<std::string>::const_iterator
751 I = gccArgs.begin(), E = gccArgs.end(); I != E; ++I)
752 GCCArgs.push_back(I->c_str());
754 // Specify -x explicitly in case the extension is wonky
755 if (fileType != ObjectFile) {
756 GCCArgs.push_back("-x");
757 if (fileType == CFile) {
758 GCCArgs.push_back("c");
759 GCCArgs.push_back("-fno-strict-aliasing");
761 GCCArgs.push_back("assembler");
763 // For ARM architectures we don't want this flag. bugpoint isn't
764 // explicitly told what architecture it is working on, so we get
766 if (TargetTriple.isOSDarwin() && !IsARMArchitecture(GCCArgs))
767 GCCArgs.push_back("-force_cpusubtype_ALL");
771 GCCArgs.push_back(ProgramFile.c_str()); // Specify the input filename.
773 GCCArgs.push_back("-x");
774 GCCArgs.push_back("none");
775 GCCArgs.push_back("-o");
776 sys::Path OutputBinary (ProgramFile+".gcc.exe");
778 if (OutputBinary.makeUnique(true, &ErrMsg)) {
779 errs() << "Error making unique filename: " << ErrMsg << "\n";
782 GCCArgs.push_back(OutputBinary.c_str()); // Output to the right file...
784 // Add any arguments intended for GCC. We locate them here because this is
785 // most likely -L and -l options that need to come before other libraries but
786 // after the source. Other options won't be sensitive to placement on the
787 // command line, so this should be safe.
788 for (unsigned i = 0, e = ArgsForGCC.size(); i != e; ++i)
789 GCCArgs.push_back(ArgsForGCC[i].c_str());
791 GCCArgs.push_back("-lm"); // Hard-code the math library...
792 GCCArgs.push_back("-O2"); // Optimize the program a bit...
793 #if defined (HAVE_LINK_R)
794 GCCArgs.push_back("-Wl,-R."); // Search this dir for .so files
796 if (TargetTriple.getArch() == Triple::sparc)
797 GCCArgs.push_back("-mcpu=v9");
798 GCCArgs.push_back(0); // NULL terminator
800 outs() << "<gcc>"; outs().flush();
801 DEBUG(errs() << "\nAbout to run:\t";
802 for (unsigned i = 0, e = GCCArgs.size()-1; i != e; ++i)
803 errs() << " " << GCCArgs[i];
806 if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], sys::Path(), sys::Path(),
808 *Error = ProcessFailure(GCCPath, &GCCArgs[0]);
812 std::vector<const char*> ProgramArgs;
814 // Declared here so that the destructor only runs after
815 // ProgramArgs is used.
818 if (RemoteClientPath.isEmpty())
819 ProgramArgs.push_back(OutputBinary.c_str());
821 ProgramArgs.push_back(RemoteClientPath.c_str());
822 ProgramArgs.push_back(RemoteHost.c_str());
823 if (!RemoteUser.empty()) {
824 ProgramArgs.push_back("-l");
825 ProgramArgs.push_back(RemoteUser.c_str());
827 if (!RemotePort.empty()) {
828 ProgramArgs.push_back("-p");
829 ProgramArgs.push_back(RemotePort.c_str());
831 if (!RemoteExtra.empty()) {
832 ProgramArgs.push_back(RemoteExtra.c_str());
835 // Full path to the binary. We need to cd to the exec directory because
836 // there is a dylib there that the exec expects to find in the CWD
837 char* env_pwd = getenv("PWD");
841 Exec += OutputBinary.c_str();
842 ProgramArgs.push_back(Exec.c_str());
845 // Add optional parameters to the running program from Argv
846 for (unsigned i = 0, e = Args.size(); i != e; ++i)
847 ProgramArgs.push_back(Args[i].c_str());
848 ProgramArgs.push_back(0); // NULL terminator
850 // Now that we have a binary, run it!
851 outs() << "<program>"; outs().flush();
852 DEBUG(errs() << "\nAbout to run:\t";
853 for (unsigned i = 0, e = ProgramArgs.size()-1; i != e; ++i)
854 errs() << " " << ProgramArgs[i];
858 FileRemover OutputBinaryRemover(OutputBinary.str(), !SaveTemps);
860 if (RemoteClientPath.isEmpty()) {
861 DEBUG(errs() << "<run locally>");
862 int ExitCode = RunProgramWithTimeout(OutputBinary, &ProgramArgs[0],
863 sys::Path(InputFile), sys::Path(OutputFile), sys::Path(OutputFile),
864 Timeout, MemoryLimit, Error);
865 // Treat a signal (usually SIGSEGV) as part of the program output so that
866 // crash-causing miscompilation is handled seamlessly.
867 if (Error->find(SignalPrefix) == 0) {
868 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
869 outFile << *Error << '\n';
875 outs() << "<run remotely>"; outs().flush();
876 return RunProgramRemotelyWithTimeout(sys::Path(RemoteClientPath),
877 &ProgramArgs[0], sys::Path(InputFile), sys::Path(OutputFile),
878 sys::Path(OutputFile), Timeout, MemoryLimit);
882 int GCC::MakeSharedObject(const std::string &InputFile, FileType fileType,
883 std::string &OutputFile,
884 const std::vector<std::string> &ArgsForGCC,
885 std::string &Error) {
886 sys::Path uniqueFilename(InputFile+LTDL_SHLIB_EXT);
888 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
889 errs() << "Error making unique filename: " << ErrMsg << "\n";
892 OutputFile = uniqueFilename.str();
894 std::vector<const char*> GCCArgs;
896 GCCArgs.push_back(GCCPath.c_str());
898 if (TargetTriple.getArch() == Triple::x86)
899 GCCArgs.push_back("-m32");
901 for (std::vector<std::string>::const_iterator
902 I = gccArgs.begin(), E = gccArgs.end(); I != E; ++I)
903 GCCArgs.push_back(I->c_str());
905 // Compile the C/asm file into a shared object
906 if (fileType != ObjectFile) {
907 GCCArgs.push_back("-x");
908 GCCArgs.push_back(fileType == AsmFile ? "assembler" : "c");
910 GCCArgs.push_back("-fno-strict-aliasing");
911 GCCArgs.push_back(InputFile.c_str()); // Specify the input filename.
912 GCCArgs.push_back("-x");
913 GCCArgs.push_back("none");
914 if (TargetTriple.getArch() == Triple::sparc)
915 GCCArgs.push_back("-G"); // Compile a shared library, `-G' for Sparc
916 else if (TargetTriple.isOSDarwin()) {
917 // link all source files into a single module in data segment, rather than
918 // generating blocks. dynamic_lookup requires that you set
919 // MACOSX_DEPLOYMENT_TARGET=10.3 in your env. FIXME: it would be better for
920 // bugpoint to just pass that in the environment of GCC.
921 GCCArgs.push_back("-single_module");
922 GCCArgs.push_back("-dynamiclib"); // `-dynamiclib' for MacOS X/PowerPC
923 GCCArgs.push_back("-undefined");
924 GCCArgs.push_back("dynamic_lookup");
926 GCCArgs.push_back("-shared"); // `-shared' for Linux/X86, maybe others
928 if ((TargetTriple.getArch() == Triple::alpha) ||
929 (TargetTriple.getArch() == Triple::x86_64))
930 GCCArgs.push_back("-fPIC"); // Requires shared objs to contain PIC
932 if (TargetTriple.getArch() == Triple::sparc)
933 GCCArgs.push_back("-mcpu=v9");
935 GCCArgs.push_back("-o");
936 GCCArgs.push_back(OutputFile.c_str()); // Output to the right filename.
937 GCCArgs.push_back("-O2"); // Optimize the program a bit.
941 // Add any arguments intended for GCC. We locate them here because this is
942 // most likely -L and -l options that need to come before other libraries but
943 // after the source. Other options won't be sensitive to placement on the
944 // command line, so this should be safe.
945 for (unsigned i = 0, e = ArgsForGCC.size(); i != e; ++i)
946 GCCArgs.push_back(ArgsForGCC[i].c_str());
947 GCCArgs.push_back(0); // NULL terminator
951 outs() << "<gcc>"; outs().flush();
952 DEBUG(errs() << "\nAbout to run:\t";
953 for (unsigned i = 0, e = GCCArgs.size()-1; i != e; ++i)
954 errs() << " " << GCCArgs[i];
957 if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], sys::Path(), sys::Path(),
959 Error = ProcessFailure(GCCPath, &GCCArgs[0]);
965 /// create - Try to find the `gcc' executable
967 GCC *GCC::create(std::string &Message,
968 const std::string &GCCBinary,
969 const std::vector<std::string> *Args) {
970 sys::Path GCCPath = sys::Program::FindProgramByName(GCCBinary);
971 if (GCCPath.isEmpty()) {
972 Message = "Cannot find `"+ GCCBinary +"' in PATH!\n";
976 sys::Path RemoteClientPath;
977 if (!RemoteClient.empty())
978 RemoteClientPath = sys::Program::FindProgramByName(RemoteClient);
980 Message = "Found gcc: " + GCCPath.str() + "\n";
981 return new GCC(GCCPath, RemoteClientPath, Args);