Merge branch 'master' into msp430
[llvm/msp430.git] / tools / llvm-ld / llvm-ld.cpp
blobfd2e0f7cac2501dc2b4c55cf88c6e2d8ce6621ea
1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
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 utility is intended to be compatible with GCC, and follows standard
11 // system 'ld' conventions. As such, the default output file is ./a.out.
12 // Additionally, this program outputs a shell script that is used to invoke LLI
13 // to execute the program. In this manner, the generated executable (a.out for
14 // example), is directly executable, whereas the bitcode file actually lives in
15 // the a.out.bc file generated by this program. Also, Force is on by default.
17 // Note that if someone (or a script) deletes the executable program generated,
18 // the .bc file will be left around. Considering that this is a temporary hack,
19 // I'm not too worried about this.
21 //===----------------------------------------------------------------------===//
23 #include "llvm/LinkAllVMCore.h"
24 #include "llvm/Linker.h"
25 #include "llvm/System/Program.h"
26 #include "llvm/Module.h"
27 #include "llvm/PassManager.h"
28 #include "llvm/Bitcode/ReaderWriter.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetMachineRegistry.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Streams.h"
38 #include "llvm/Support/SystemUtils.h"
39 #include "llvm/System/Signals.h"
40 #include "llvm/Config/config.h"
41 #include <fstream>
42 #include <memory>
43 #include <cstring>
44 using namespace llvm;
46 // Input/Output Options
47 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
48 cl::desc("<input bitcode files>"));
50 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
51 cl::desc("Override output filename"),
52 cl::value_desc("filename"));
54 static cl::opt<bool> Verbose("v",
55 cl::desc("Print information about actions taken"));
57 static cl::list<std::string> LibPaths("L", cl::Prefix,
58 cl::desc("Specify a library search path"),
59 cl::value_desc("directory"));
61 static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
62 cl::desc("Specify a framework search path"),
63 cl::value_desc("directory"));
65 static cl::list<std::string> Libraries("l", cl::Prefix,
66 cl::desc("Specify libraries to link to"),
67 cl::value_desc("library prefix"));
69 static cl::list<std::string> Frameworks("framework",
70 cl::desc("Specify frameworks to link to"),
71 cl::value_desc("framework"));
73 // Options to control the linking, optimization, and code gen processes
74 static cl::opt<bool> LinkAsLibrary("link-as-library",
75 cl::desc("Link the .bc files together as a library, not an executable"));
77 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
78 cl::desc("Alias for -link-as-library"));
80 static cl::opt<bool> Native("native",
81 cl::desc("Generate a native binary instead of a shell script"));
83 static cl::opt<bool>NativeCBE("native-cbe",
84 cl::desc("Generate a native binary with the C backend and GCC"));
86 static cl::list<std::string> PostLinkOpts("post-link-opts",
87 cl::value_desc("path"),
88 cl::desc("Run one or more optimization programs after linking"));
90 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
91 cl::desc("Pass options to the system linker"));
93 // Compatibility options that llvm-ld ignores but are supported for
94 // compatibility with LD
95 static cl::opt<std::string> CO3("soname", cl::Hidden,
96 cl::desc("Compatibility option: ignored"));
98 static cl::opt<std::string> CO4("version-script", cl::Hidden,
99 cl::desc("Compatibility option: ignored"));
101 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
102 cl::desc("Compatibility option: ignored"));
104 static cl::opt<std::string> CO6("h", cl::Hidden,
105 cl::desc("Compatibility option: ignored"));
107 static cl::opt<bool> CO7("start-group", cl::Hidden,
108 cl::desc("Compatibility option: ignored"));
110 static cl::opt<bool> CO8("end-group", cl::Hidden,
111 cl::desc("Compatibility option: ignored"));
113 static cl::opt<std::string> CO9("m", cl::Hidden,
114 cl::desc("Compatibility option: ignored"));
116 /// This is just for convenience so it doesn't have to be passed around
117 /// everywhere.
118 static std::string progname;
120 /// PrintAndExit - Prints a message to standard error and exits with error code
122 /// Inputs:
123 /// Message - The message to print to standard error.
125 static void PrintAndExit(const std::string &Message, int errcode = 1) {
126 cerr << progname << ": " << Message << "\n";
127 llvm_shutdown();
128 exit(errcode);
131 static void PrintCommand(const std::vector<const char*> &args) {
132 std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
133 for (; I != E; ++I)
134 if (*I)
135 cout << "'" << *I << "'" << " ";
136 cout << "\n" << std::flush;
139 /// CopyEnv - This function takes an array of environment variables and makes a
140 /// copy of it. This copy can then be manipulated any way the caller likes
141 /// without affecting the process's real environment.
143 /// Inputs:
144 /// envp - An array of C strings containing an environment.
146 /// Return value:
147 /// NULL - An error occurred.
149 /// Otherwise, a pointer to a new array of C strings is returned. Every string
150 /// in the array is a duplicate of the one in the original array (i.e. we do
151 /// not copy the char *'s from one array to another).
153 static char ** CopyEnv(char ** const envp) {
154 // Count the number of entries in the old list;
155 unsigned entries; // The number of entries in the old environment list
156 for (entries = 0; envp[entries] != NULL; entries++)
157 /*empty*/;
159 // Add one more entry for the NULL pointer that ends the list.
160 ++entries;
162 // If there are no entries at all, just return NULL.
163 if (entries == 0)
164 return NULL;
166 // Allocate a new environment list.
167 char **newenv = new char* [entries];
168 if ((newenv = new char* [entries]) == NULL)
169 return NULL;
171 // Make a copy of the list. Don't forget the NULL that ends the list.
172 entries = 0;
173 while (envp[entries] != NULL) {
174 newenv[entries] = new char[strlen (envp[entries]) + 1];
175 strcpy (newenv[entries], envp[entries]);
176 ++entries;
178 newenv[entries] = NULL;
180 return newenv;
184 /// RemoveEnv - Remove the specified environment variable from the environment
185 /// array.
187 /// Inputs:
188 /// name - The name of the variable to remove. It cannot be NULL.
189 /// envp - The array of environment variables. It cannot be NULL.
191 /// Notes:
192 /// This is mainly done because functions to remove items from the environment
193 /// are not available across all platforms. In particular, Solaris does not
194 /// seem to have an unsetenv() function or a setenv() function (or they are
195 /// undocumented if they do exist).
197 static void RemoveEnv(const char * name, char ** const envp) {
198 for (unsigned index=0; envp[index] != NULL; index++) {
199 // Find the first equals sign in the array and make it an EOS character.
200 char *p = strchr (envp[index], '=');
201 if (p == NULL)
202 continue;
203 else
204 *p = '\0';
206 // Compare the two strings. If they are equal, zap this string.
207 // Otherwise, restore it.
208 if (!strcmp(name, envp[index]))
209 *envp[index] = '\0';
210 else
211 *p = '=';
214 return;
217 /// GenerateBitcode - generates a bitcode file from the module provided
218 void GenerateBitcode(Module* M, const std::string& FileName) {
220 if (Verbose)
221 cout << "Generating Bitcode To " << FileName << '\n';
223 // Create the output file.
224 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
225 std::ios::binary;
226 std::ofstream Out(FileName.c_str(), io_mode);
227 if (!Out.good())
228 PrintAndExit("error opening '" + FileName + "' for writing!");
230 // Ensure that the bitcode file gets removed from the disk if we get a
231 // terminating signal.
232 sys::RemoveFileOnSignal(sys::Path(FileName));
234 // Write it out
235 WriteBitcodeToFile(M, Out);
237 // Close the bitcode file.
238 Out.close();
241 /// GenerateAssembly - generates a native assembly language source file from the
242 /// specified bitcode file.
244 /// Inputs:
245 /// InputFilename - The name of the input bitcode file.
246 /// OutputFilename - The name of the file to generate.
247 /// llc - The pathname to use for LLC.
248 /// envp - The environment to use when running LLC.
250 /// Return non-zero value on error.
252 static int GenerateAssembly(const std::string &OutputFilename,
253 const std::string &InputFilename,
254 const sys::Path &llc,
255 std::string &ErrMsg ) {
256 // Run LLC to convert the bitcode file into assembly code.
257 std::vector<const char*> args;
258 args.push_back(llc.c_str());
259 // We will use GCC to assemble the program so set the assembly syntax to AT&T,
260 // regardless of what the target in the bitcode file is.
261 args.push_back("-x86-asm-syntax=att");
262 args.push_back("-f");
263 args.push_back("-o");
264 args.push_back(OutputFilename.c_str());
265 args.push_back(InputFilename.c_str());
266 args.push_back(0);
268 if (Verbose) {
269 cout << "Generating Assembly With: \n";
270 PrintCommand(args);
273 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
276 /// GenerateCFile - generates a C source file from the specified bitcode file.
277 static int GenerateCFile(const std::string &OutputFile,
278 const std::string &InputFile,
279 const sys::Path &llc,
280 std::string& ErrMsg) {
281 // Run LLC to convert the bitcode file into C.
282 std::vector<const char*> args;
283 args.push_back(llc.c_str());
284 args.push_back("-march=c");
285 args.push_back("-f");
286 args.push_back("-o");
287 args.push_back(OutputFile.c_str());
288 args.push_back(InputFile.c_str());
289 args.push_back(0);
291 if (Verbose) {
292 cout << "Generating C Source With: \n";
293 PrintCommand(args);
296 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
299 /// GenerateNative - generates a native object file from the
300 /// specified bitcode file.
302 /// Inputs:
303 /// InputFilename - The name of the input bitcode file.
304 /// OutputFilename - The name of the file to generate.
305 /// NativeLinkItems - The native libraries, files, code with which to link
306 /// LibPaths - The list of directories in which to find libraries.
307 /// FrameworksPaths - The list of directories in which to find frameworks.
308 /// Frameworks - The list of frameworks (dynamic libraries)
309 /// gcc - The pathname to use for GGC.
310 /// envp - A copy of the process's current environment.
312 /// Outputs:
313 /// None.
315 /// Returns non-zero value on error.
317 static int GenerateNative(const std::string &OutputFilename,
318 const std::string &InputFilename,
319 const Linker::ItemList &LinkItems,
320 const sys::Path &gcc, char ** const envp,
321 std::string& ErrMsg) {
322 // Remove these environment variables from the environment of the
323 // programs that we will execute. It appears that GCC sets these
324 // environment variables so that the programs it uses can configure
325 // themselves identically.
327 // However, when we invoke GCC below, we want it to use its normal
328 // configuration. Hence, we must sanitize its environment.
329 char ** clean_env = CopyEnv(envp);
330 if (clean_env == NULL)
331 return 1;
332 RemoveEnv("LIBRARY_PATH", clean_env);
333 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
334 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
335 RemoveEnv("COMPILER_PATH", clean_env);
336 RemoveEnv("COLLECT_GCC", clean_env);
339 // Run GCC to assemble and link the program into native code.
341 // Note:
342 // We can't just assemble and link the file with the system assembler
343 // and linker because we don't know where to put the _start symbol.
344 // GCC mysteriously knows how to do it.
345 std::vector<std::string> args;
346 args.push_back(gcc.c_str());
347 args.push_back("-fno-strict-aliasing");
348 args.push_back("-O3");
349 args.push_back("-o");
350 args.push_back(OutputFilename);
351 args.push_back(InputFilename);
353 // Add in the library and framework paths
354 for (unsigned index = 0; index < LibPaths.size(); index++) {
355 args.push_back("-L" + LibPaths[index]);
357 for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
358 args.push_back("-F" + FrameworkPaths[index]);
361 // Add the requested options
362 for (unsigned index = 0; index < XLinker.size(); index++)
363 args.push_back(XLinker[index]);
365 // Add in the libraries to link.
366 for (unsigned index = 0; index < LinkItems.size(); index++)
367 if (LinkItems[index].first != "crtend") {
368 if (LinkItems[index].second)
369 args.push_back("-l" + LinkItems[index].first);
370 else
371 args.push_back(LinkItems[index].first);
374 // Add in frameworks to link.
375 for (unsigned index = 0; index < Frameworks.size(); index++) {
376 args.push_back("-framework");
377 args.push_back(Frameworks[index]);
380 // Now that "args" owns all the std::strings for the arguments, call the c_str
381 // method to get the underlying string array. We do this game so that the
382 // std::string array is guaranteed to outlive the const char* array.
383 std::vector<const char *> Args;
384 for (unsigned i = 0, e = args.size(); i != e; ++i)
385 Args.push_back(args[i].c_str());
386 Args.push_back(0);
388 if (Verbose) {
389 cout << "Generating Native Executable With:\n";
390 PrintCommand(Args);
393 // Run the compiler to assembly and link together the program.
394 int R = sys::Program::ExecuteAndWait(
395 gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
396 delete [] clean_env;
397 return R;
400 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
401 /// bitcode file for the program.
402 static void EmitShellScript(char **argv) {
403 if (Verbose)
404 cout << "Emitting Shell Script\n";
405 #if defined(_WIN32) || defined(__CYGWIN__)
406 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
407 // support windows systems, we copy the llvm-stub.exe executable from the
408 // build tree to the destination file.
409 std::string ErrMsg;
410 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
411 if (llvmstub.isEmpty())
412 PrintAndExit("Could not find llvm-stub.exe executable!");
414 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
415 PrintAndExit(ErrMsg);
417 return;
418 #endif
420 // Output the script to start the program...
421 std::ofstream Out2(OutputFilename.c_str());
422 if (!Out2.good())
423 PrintAndExit("error opening '" + OutputFilename + "' for writing!");
425 Out2 << "#!/bin/sh\n";
426 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
427 Out2 << "lli=${LLVMINTERP-lli}\n";
428 Out2 << "exec $lli \\\n";
429 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
430 LibPaths.push_back("/lib");
431 LibPaths.push_back("/usr/lib");
432 LibPaths.push_back("/usr/X11R6/lib");
433 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
434 // shared object at all! See RH 8: plain text.
435 std::vector<std::string>::iterator libc =
436 std::find(Libraries.begin(), Libraries.end(), "c");
437 if (libc != Libraries.end()) Libraries.erase(libc);
438 // List all the shared object (native) libraries this executable will need
439 // on the command line, so that we don't have to do this manually!
440 for (std::vector<std::string>::iterator i = Libraries.begin(),
441 e = Libraries.end(); i != e; ++i) {
442 // try explicit -L arguments first:
443 sys::Path FullLibraryPath;
444 for (cl::list<std::string>::const_iterator P = LibPaths.begin(),
445 E = LibPaths.end(); P != E; ++P) {
446 FullLibraryPath = *P;
447 FullLibraryPath.appendComponent("lib" + *i);
448 FullLibraryPath.appendSuffix(&(LTDL_SHLIB_EXT[1]));
449 if (!FullLibraryPath.isEmpty()) {
450 if (!FullLibraryPath.isDynamicLibrary()) {
451 // Not a native shared library; mark as invalid
452 FullLibraryPath = sys::Path();
453 } else break;
456 if (FullLibraryPath.isEmpty())
457 FullLibraryPath = sys::Path::FindLibrary(*i);
458 if (!FullLibraryPath.isEmpty())
459 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
461 Out2 << " $0.bc ${1+\"$@\"}\n";
462 Out2.close();
465 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
466 // linker function by combining the Files and Libraries in the order they were
467 // declared on the command line.
468 static void BuildLinkItems(
469 Linker::ItemList& Items,
470 const cl::list<std::string>& Files,
471 const cl::list<std::string>& Libraries) {
473 // Build the list of linkage items for LinkItems.
475 cl::list<std::string>::const_iterator fileIt = Files.begin();
476 cl::list<std::string>::const_iterator libIt = Libraries.begin();
478 int libPos = -1, filePos = -1;
479 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
480 if (libIt != Libraries.end())
481 libPos = Libraries.getPosition(libIt - Libraries.begin());
482 else
483 libPos = -1;
484 if (fileIt != Files.end())
485 filePos = Files.getPosition(fileIt - Files.begin());
486 else
487 filePos = -1;
489 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
490 // Add a source file
491 Items.push_back(std::make_pair(*fileIt++, false));
492 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
493 // Add a library
494 Items.push_back(std::make_pair(*libIt++, true));
499 // Rightly this should go in a header file but it just seems such a waste.
500 namespace llvm {
501 extern void Optimize(Module*);
504 int main(int argc, char **argv, char **envp) {
505 // Print a stack trace if we signal out.
506 sys::PrintStackTraceOnErrorSignal();
507 PrettyStackTraceProgram X(argc, argv);
509 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
510 try {
511 // Initial global variable above for convenience printing of program name.
512 progname = sys::Path(argv[0]).getBasename();
514 // Parse the command line options
515 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
517 // Construct a Linker (now that Verbose is set)
518 Linker TheLinker(progname, OutputFilename, Verbose);
520 // Keep track of the native link items (versus the bitcode items)
521 Linker::ItemList NativeLinkItems;
523 // Add library paths to the linker
524 TheLinker.addPaths(LibPaths);
525 TheLinker.addSystemPaths();
527 // Remove any consecutive duplicates of the same library...
528 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
529 Libraries.end());
531 if (LinkAsLibrary) {
532 std::vector<sys::Path> Files;
533 for (unsigned i = 0; i < InputFilenames.size(); ++i )
534 Files.push_back(sys::Path(InputFilenames[i]));
535 if (TheLinker.LinkInFiles(Files))
536 return 1; // Error already printed
538 // The libraries aren't linked in but are noted as "dependent" in the
539 // module.
540 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
541 E = Libraries.end(); I != E ; ++I) {
542 TheLinker.getModule()->addLibrary(*I);
544 } else {
545 // Build a list of the items from our command line
546 Linker::ItemList Items;
547 BuildLinkItems(Items, InputFilenames, Libraries);
549 // Link all the items together
550 if (TheLinker.LinkInItems(Items, NativeLinkItems) )
551 return 1; // Error already printed
554 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
556 // Optimize the module
557 Optimize(Composite.get());
559 #if defined(_WIN32) || defined(__CYGWIN__)
560 if (!LinkAsLibrary) {
561 // Default to "a.exe" instead of "a.out".
562 if (OutputFilename.getNumOccurrences() == 0)
563 OutputFilename = "a.exe";
565 // If there is no suffix add an "exe" one.
566 sys::Path ExeFile( OutputFilename );
567 if (ExeFile.getSuffix() == "") {
568 ExeFile.appendSuffix("exe");
569 OutputFilename = ExeFile.toString();
572 #endif
574 // Generate the bitcode for the optimized module.
575 std::string RealBitcodeOutput = OutputFilename;
577 if (!LinkAsLibrary) RealBitcodeOutput += ".bc";
578 GenerateBitcode(Composite.get(), RealBitcodeOutput);
580 // If we are not linking a library, generate either a native executable
581 // or a JIT shell script, depending upon what the user wants.
582 if (!LinkAsLibrary) {
583 // If the user wants to run a post-link optimization, run it now.
584 if (!PostLinkOpts.empty()) {
585 std::vector<std::string> opts = PostLinkOpts;
586 for (std::vector<std::string>::iterator I = opts.begin(),
587 E = opts.end(); I != E; ++I) {
588 sys::Path prog(*I);
589 if (!prog.canExecute()) {
590 prog = sys::Program::FindProgramByName(*I);
591 if (prog.isEmpty())
592 PrintAndExit(std::string("Optimization program '") + *I +
593 "' is not found or not executable.");
595 // Get the program arguments
596 sys::Path tmp_output("opt_result");
597 std::string ErrMsg;
598 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
599 PrintAndExit(ErrMsg);
601 const char* args[4];
602 args[0] = I->c_str();
603 args[1] = RealBitcodeOutput.c_str();
604 args[2] = tmp_output.c_str();
605 args[3] = 0;
606 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
607 if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
608 sys::Path target(RealBitcodeOutput);
609 target.eraseFromDisk();
610 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
611 PrintAndExit(ErrMsg, 2);
612 } else
613 PrintAndExit("Post-link optimization output is not bitcode");
614 } else {
615 PrintAndExit(ErrMsg);
620 // If the user wants to generate a native executable, compile it from the
621 // bitcode file.
623 // Otherwise, create a script that will run the bitcode through the JIT.
624 if (Native) {
625 // Name of the Assembly Language output file
626 sys::Path AssemblyFile ( OutputFilename);
627 AssemblyFile.appendSuffix("s");
629 // Mark the output files for removal if we get an interrupt.
630 sys::RemoveFileOnSignal(AssemblyFile);
631 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
633 // Determine the locations of the llc and gcc programs.
634 sys::Path llc = FindExecutable("llc", argv[0]);
635 if (llc.isEmpty())
636 PrintAndExit("Failed to find llc");
638 sys::Path gcc = FindExecutable("gcc", argv[0]);
639 if (gcc.isEmpty())
640 PrintAndExit("Failed to find gcc");
642 // Generate an assembly language file for the bitcode.
643 std::string ErrMsg;
644 if (0 != GenerateAssembly(AssemblyFile.toString(), RealBitcodeOutput,
645 llc, ErrMsg))
646 PrintAndExit(ErrMsg);
648 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
649 NativeLinkItems, gcc, envp, ErrMsg))
650 PrintAndExit(ErrMsg);
652 // Remove the assembly language file.
653 AssemblyFile.eraseFromDisk();
654 } else if (NativeCBE) {
655 sys::Path CFile (OutputFilename);
656 CFile.appendSuffix("cbe.c");
658 // Mark the output files for removal if we get an interrupt.
659 sys::RemoveFileOnSignal(CFile);
660 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
662 // Determine the locations of the llc and gcc programs.
663 sys::Path llc = FindExecutable("llc", argv[0]);
664 if (llc.isEmpty())
665 PrintAndExit("Failed to find llc");
667 sys::Path gcc = FindExecutable("gcc", argv[0]);
668 if (gcc.isEmpty())
669 PrintAndExit("Failed to find gcc");
671 // Generate an assembly language file for the bitcode.
672 std::string ErrMsg;
673 if (0 != GenerateCFile(
674 CFile.toString(), RealBitcodeOutput, llc, ErrMsg))
675 PrintAndExit(ErrMsg);
677 if (0 != GenerateNative(OutputFilename, CFile.toString(),
678 NativeLinkItems, gcc, envp, ErrMsg))
679 PrintAndExit(ErrMsg);
681 // Remove the assembly language file.
682 CFile.eraseFromDisk();
684 } else {
685 EmitShellScript(argv);
688 // Make the script executable...
689 std::string ErrMsg;
690 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
691 PrintAndExit(ErrMsg);
693 // Make the bitcode file readable and directly executable in LLEE as well
694 if (sys::Path(RealBitcodeOutput).makeExecutableOnDisk(&ErrMsg))
695 PrintAndExit(ErrMsg);
697 if (sys::Path(RealBitcodeOutput).makeReadableOnDisk(&ErrMsg))
698 PrintAndExit(ErrMsg);
700 } catch (const std::string& msg) {
701 PrintAndExit(msg,2);
702 } catch (...) {
703 PrintAndExit("Unexpected unknown exception occurred.", 2);
706 // Graceful exit
707 return 0;