1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
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 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/LLVMContext.h"
26 #include "llvm/System/Program.h"
27 #include "llvm/Module.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Bitcode/ReaderWriter.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.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/SystemUtils.h"
38 #include "llvm/System/Signals.h"
39 #include "llvm/Config/config.h"
44 // Input/Output Options
45 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
46 cl::desc("<input bitcode files>"));
48 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
49 cl::desc("Override output filename"),
50 cl::value_desc("filename"));
52 static cl::opt<std::string> BitcodeOutputFilename("b", cl::init(""),
53 cl::desc("Override bitcode output filename"),
54 cl::value_desc("filename"));
56 static cl::opt<bool> Verbose("v",
57 cl::desc("Print information about actions taken"));
59 static cl::list<std::string> LibPaths("L", cl::Prefix,
60 cl::desc("Specify a library search path"),
61 cl::value_desc("directory"));
63 static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
64 cl::desc("Specify a framework search path"),
65 cl::value_desc("directory"));
67 static cl::list<std::string> Libraries("l", cl::Prefix,
68 cl::desc("Specify libraries to link to"),
69 cl::value_desc("library prefix"));
71 static cl::list<std::string> Frameworks("framework",
72 cl::desc("Specify frameworks to link to"),
73 cl::value_desc("framework"));
75 // Options to control the linking, optimization, and code gen processes
76 static cl::opt<bool> LinkAsLibrary("link-as-library",
77 cl::desc("Link the .bc files together as a library, not an executable"));
79 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
80 cl::desc("Alias for -link-as-library"));
82 static cl::opt<bool> Native("native",
83 cl::desc("Generate a native binary instead of a shell script"));
85 static cl::opt<bool>NativeCBE("native-cbe",
86 cl::desc("Generate a native binary with the C backend and GCC"));
88 static cl::list<std::string> PostLinkOpts("post-link-opts",
89 cl::value_desc("path"),
90 cl::desc("Run one or more optimization programs after linking"));
92 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
93 cl::desc("Pass options to the system linker"));
95 // Compatibility options that llvm-ld ignores but are supported for
96 // compatibility with LD
97 static cl::opt<std::string> CO3("soname", cl::Hidden,
98 cl::desc("Compatibility option: ignored"));
100 static cl::opt<std::string> CO4("version-script", cl::Hidden,
101 cl::desc("Compatibility option: ignored"));
103 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
104 cl::desc("Compatibility option: ignored"));
106 static cl::opt<std::string> CO6("h", cl::Hidden,
107 cl::desc("Compatibility option: ignored"));
109 static cl::opt<bool> CO7("start-group", cl::Hidden,
110 cl::desc("Compatibility option: ignored"));
112 static cl::opt<bool> CO8("end-group", cl::Hidden,
113 cl::desc("Compatibility option: ignored"));
115 static cl::opt<std::string> CO9("m", cl::Hidden,
116 cl::desc("Compatibility option: ignored"));
118 /// This is just for convenience so it doesn't have to be passed around
120 static std::string progname;
122 /// PrintAndExit - Prints a message to standard error and exits with error code
125 /// Message - The message to print to standard error.
127 static void PrintAndExit(const std::string &Message, int errcode = 1) {
128 errs() << progname << ": " << Message << "\n";
133 static void PrintCommand(const std::vector<const char*> &args) {
134 std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
137 outs() << "'" << *I << "'" << " ";
138 outs() << "\n"; outs().flush();
141 /// CopyEnv - This function takes an array of environment variables and makes a
142 /// copy of it. This copy can then be manipulated any way the caller likes
143 /// without affecting the process's real environment.
146 /// envp - An array of C strings containing an environment.
149 /// NULL - An error occurred.
151 /// Otherwise, a pointer to a new array of C strings is returned. Every string
152 /// in the array is a duplicate of the one in the original array (i.e. we do
153 /// not copy the char *'s from one array to another).
155 static char ** CopyEnv(char ** const envp) {
156 // Count the number of entries in the old list;
157 unsigned entries; // The number of entries in the old environment list
158 for (entries = 0; envp[entries] != NULL; entries++)
161 // Add one more entry for the NULL pointer that ends the list.
164 // If there are no entries at all, just return NULL.
168 // Allocate a new environment list.
169 char **newenv = new char* [entries];
170 if ((newenv = new char* [entries]) == NULL)
173 // Make a copy of the list. Don't forget the NULL that ends the list.
175 while (envp[entries] != NULL) {
176 newenv[entries] = new char[strlen (envp[entries]) + 1];
177 strcpy (newenv[entries], envp[entries]);
180 newenv[entries] = NULL;
186 /// RemoveEnv - Remove the specified environment variable from the environment
190 /// name - The name of the variable to remove. It cannot be NULL.
191 /// envp - The array of environment variables. It cannot be NULL.
194 /// This is mainly done because functions to remove items from the environment
195 /// are not available across all platforms. In particular, Solaris does not
196 /// seem to have an unsetenv() function or a setenv() function (or they are
197 /// undocumented if they do exist).
199 static void RemoveEnv(const char * name, char ** const envp) {
200 for (unsigned index=0; envp[index] != NULL; index++) {
201 // Find the first equals sign in the array and make it an EOS character.
202 char *p = strchr (envp[index], '=');
208 // Compare the two strings. If they are equal, zap this string.
209 // Otherwise, restore it.
210 if (!strcmp(name, envp[index]))
219 /// GenerateBitcode - generates a bitcode file from the module provided
220 void GenerateBitcode(Module* M, const std::string& FileName) {
223 outs() << "Generating Bitcode To " << FileName << '\n';
225 // Create the output file.
226 std::string ErrorInfo;
227 raw_fd_ostream Out(FileName.c_str(), /*Binary=*/true, /*Force=*/true,
229 if (!ErrorInfo.empty())
230 PrintAndExit(ErrorInfo);
232 // Ensure that the bitcode file gets removed from the disk if we get a
233 // terminating signal.
234 sys::RemoveFileOnSignal(sys::Path(FileName));
237 WriteBitcodeToFile(M, Out);
239 // Close the bitcode file.
243 /// GenerateAssembly - generates a native assembly language source file from the
244 /// specified bitcode file.
247 /// InputFilename - The name of the input bitcode file.
248 /// OutputFilename - The name of the file to generate.
249 /// llc - The pathname to use for LLC.
250 /// envp - The environment to use when running LLC.
252 /// Return non-zero value on error.
254 static int GenerateAssembly(const std::string &OutputFilename,
255 const std::string &InputFilename,
256 const sys::Path &llc,
257 std::string &ErrMsg ) {
258 // Run LLC to convert the bitcode file into assembly code.
259 std::vector<const char*> args;
260 args.push_back(llc.c_str());
261 // We will use GCC to assemble the program so set the assembly syntax to AT&T,
262 // regardless of what the target in the bitcode file is.
263 args.push_back("-x86-asm-syntax=att");
264 args.push_back("-f");
265 args.push_back("-o");
266 args.push_back(OutputFilename.c_str());
267 args.push_back(InputFilename.c_str());
271 outs() << "Generating Assembly With: \n";
275 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
278 /// GenerateCFile - generates a C source file from the specified bitcode file.
279 static int GenerateCFile(const std::string &OutputFile,
280 const std::string &InputFile,
281 const sys::Path &llc,
282 std::string& ErrMsg) {
283 // Run LLC to convert the bitcode file into C.
284 std::vector<const char*> args;
285 args.push_back(llc.c_str());
286 args.push_back("-march=c");
287 args.push_back("-f");
288 args.push_back("-o");
289 args.push_back(OutputFile.c_str());
290 args.push_back(InputFile.c_str());
294 outs() << "Generating C Source With: \n";
298 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
301 /// GenerateNative - generates a native object file from the
302 /// specified bitcode file.
305 /// InputFilename - The name of the input bitcode file.
306 /// OutputFilename - The name of the file to generate.
307 /// NativeLinkItems - The native libraries, files, code with which to link
308 /// LibPaths - The list of directories in which to find libraries.
309 /// FrameworksPaths - The list of directories in which to find frameworks.
310 /// Frameworks - The list of frameworks (dynamic libraries)
311 /// gcc - The pathname to use for GGC.
312 /// envp - A copy of the process's current environment.
317 /// Returns non-zero value on error.
319 static int GenerateNative(const std::string &OutputFilename,
320 const std::string &InputFilename,
321 const Linker::ItemList &LinkItems,
322 const sys::Path &gcc, char ** const envp,
323 std::string& ErrMsg) {
324 // Remove these environment variables from the environment of the
325 // programs that we will execute. It appears that GCC sets these
326 // environment variables so that the programs it uses can configure
327 // themselves identically.
329 // However, when we invoke GCC below, we want it to use its normal
330 // configuration. Hence, we must sanitize its environment.
331 char ** clean_env = CopyEnv(envp);
332 if (clean_env == NULL)
334 RemoveEnv("LIBRARY_PATH", clean_env);
335 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
336 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
337 RemoveEnv("COMPILER_PATH", clean_env);
338 RemoveEnv("COLLECT_GCC", clean_env);
341 // Run GCC to assemble and link the program into native code.
344 // We can't just assemble and link the file with the system assembler
345 // and linker because we don't know where to put the _start symbol.
346 // GCC mysteriously knows how to do it.
347 std::vector<std::string> args;
348 args.push_back(gcc.c_str());
349 args.push_back("-fno-strict-aliasing");
350 args.push_back("-O3");
351 args.push_back("-o");
352 args.push_back(OutputFilename);
353 args.push_back(InputFilename);
355 // Add in the library and framework paths
356 for (unsigned index = 0; index < LibPaths.size(); index++) {
357 args.push_back("-L" + LibPaths[index]);
359 for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
360 args.push_back("-F" + FrameworkPaths[index]);
363 // Add the requested options
364 for (unsigned index = 0; index < XLinker.size(); index++)
365 args.push_back(XLinker[index]);
367 // Add in the libraries to link.
368 for (unsigned index = 0; index < LinkItems.size(); index++)
369 if (LinkItems[index].first != "crtend") {
370 if (LinkItems[index].second)
371 args.push_back("-l" + LinkItems[index].first);
373 args.push_back(LinkItems[index].first);
376 // Add in frameworks to link.
377 for (unsigned index = 0; index < Frameworks.size(); index++) {
378 args.push_back("-framework");
379 args.push_back(Frameworks[index]);
382 // Now that "args" owns all the std::strings for the arguments, call the c_str
383 // method to get the underlying string array. We do this game so that the
384 // std::string array is guaranteed to outlive the const char* array.
385 std::vector<const char *> Args;
386 for (unsigned i = 0, e = args.size(); i != e; ++i)
387 Args.push_back(args[i].c_str());
391 outs() << "Generating Native Executable With:\n";
395 // Run the compiler to assembly and link together the program.
396 int R = sys::Program::ExecuteAndWait(
397 gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
402 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
403 /// bitcode file for the program.
404 static void EmitShellScript(char **argv) {
406 outs() << "Emitting Shell Script\n";
407 #if defined(_WIN32) || defined(__CYGWIN__)
408 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
409 // support windows systems, we copy the llvm-stub.exe executable from the
410 // build tree to the destination file.
412 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
413 if (llvmstub.isEmpty())
414 PrintAndExit("Could not find llvm-stub.exe executable!");
416 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
417 PrintAndExit(ErrMsg);
422 // Output the script to start the program...
423 std::string ErrorInfo;
424 raw_fd_ostream Out2(OutputFilename.c_str(), /*Binary=*/false, /*Force=*/true,
426 if (!ErrorInfo.empty())
427 PrintAndExit(ErrorInfo);
429 Out2 << "#!/bin/sh\n";
430 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
431 Out2 << "lli=${LLVMINTERP-lli}\n";
432 Out2 << "exec $lli \\\n";
433 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
434 LibPaths.push_back("/lib");
435 LibPaths.push_back("/usr/lib");
436 LibPaths.push_back("/usr/X11R6/lib");
437 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
438 // shared object at all! See RH 8: plain text.
439 std::vector<std::string>::iterator libc =
440 std::find(Libraries.begin(), Libraries.end(), "c");
441 if (libc != Libraries.end()) Libraries.erase(libc);
442 // List all the shared object (native) libraries this executable will need
443 // on the command line, so that we don't have to do this manually!
444 for (std::vector<std::string>::iterator i = Libraries.begin(),
445 e = Libraries.end(); i != e; ++i) {
446 // try explicit -L arguments first:
447 sys::Path FullLibraryPath;
448 for (cl::list<std::string>::const_iterator P = LibPaths.begin(),
449 E = LibPaths.end(); P != E; ++P) {
450 FullLibraryPath = *P;
451 FullLibraryPath.appendComponent("lib" + *i);
452 FullLibraryPath.appendSuffix(&(LTDL_SHLIB_EXT[1]));
453 if (!FullLibraryPath.isEmpty()) {
454 if (!FullLibraryPath.isDynamicLibrary()) {
455 // Not a native shared library; mark as invalid
456 FullLibraryPath = sys::Path();
460 if (FullLibraryPath.isEmpty())
461 FullLibraryPath = sys::Path::FindLibrary(*i);
462 if (!FullLibraryPath.isEmpty())
463 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
465 Out2 << " " << BitcodeOutputFilename << " ${1+\"$@\"}\n";
469 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
470 // linker function by combining the Files and Libraries in the order they were
471 // declared on the command line.
472 static void BuildLinkItems(
473 Linker::ItemList& Items,
474 const cl::list<std::string>& Files,
475 const cl::list<std::string>& Libraries) {
477 // Build the list of linkage items for LinkItems.
479 cl::list<std::string>::const_iterator fileIt = Files.begin();
480 cl::list<std::string>::const_iterator libIt = Libraries.begin();
482 int libPos = -1, filePos = -1;
483 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
484 if (libIt != Libraries.end())
485 libPos = Libraries.getPosition(libIt - Libraries.begin());
488 if (fileIt != Files.end())
489 filePos = Files.getPosition(fileIt - Files.begin());
493 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
495 Items.push_back(std::make_pair(*fileIt++, false));
496 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
498 Items.push_back(std::make_pair(*libIt++, true));
503 // Rightly this should go in a header file but it just seems such a waste.
505 extern void Optimize(Module*);
508 int main(int argc, char **argv, char **envp) {
509 // Print a stack trace if we signal out.
510 sys::PrintStackTraceOnErrorSignal();
511 PrettyStackTraceProgram X(argc, argv);
513 LLVMContext &Context = getGlobalContext();
514 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
516 // Initial global variable above for convenience printing of program name.
517 progname = sys::Path(argv[0]).getBasename();
519 // Parse the command line options
520 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
522 // Construct a Linker (now that Verbose is set)
523 Linker TheLinker(progname, OutputFilename, Context, Verbose);
525 // Keep track of the native link items (versus the bitcode items)
526 Linker::ItemList NativeLinkItems;
528 // Add library paths to the linker
529 TheLinker.addPaths(LibPaths);
530 TheLinker.addSystemPaths();
532 // Remove any consecutive duplicates of the same library...
533 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
537 std::vector<sys::Path> Files;
538 for (unsigned i = 0; i < InputFilenames.size(); ++i )
539 Files.push_back(sys::Path(InputFilenames[i]));
540 if (TheLinker.LinkInFiles(Files))
541 return 1; // Error already printed
543 // The libraries aren't linked in but are noted as "dependent" in the
545 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
546 E = Libraries.end(); I != E ; ++I) {
547 TheLinker.getModule()->addLibrary(*I);
550 // Build a list of the items from our command line
551 Linker::ItemList Items;
552 BuildLinkItems(Items, InputFilenames, Libraries);
554 // Link all the items together
555 if (TheLinker.LinkInItems(Items, NativeLinkItems) )
556 return 1; // Error already printed
559 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
561 // Optimize the module
562 Optimize(Composite.get());
564 #if defined(_WIN32) || defined(__CYGWIN__)
565 if (!LinkAsLibrary) {
566 // Default to "a.exe" instead of "a.out".
567 if (OutputFilename.getNumOccurrences() == 0)
568 OutputFilename = "a.exe";
570 // If there is no suffix add an "exe" one.
571 sys::Path ExeFile( OutputFilename );
572 if (ExeFile.getSuffix() == "") {
573 ExeFile.appendSuffix("exe");
574 OutputFilename = ExeFile.toString();
579 // Generate the bitcode for the optimized module.
580 // If -b wasn't specified, use the name specified
581 // with -o to construct BitcodeOutputFilename.
582 if (BitcodeOutputFilename.empty()) {
583 BitcodeOutputFilename = OutputFilename;
584 if (!LinkAsLibrary) BitcodeOutputFilename += ".bc";
587 GenerateBitcode(Composite.get(), BitcodeOutputFilename);
589 // If we are not linking a library, generate either a native executable
590 // or a JIT shell script, depending upon what the user wants.
591 if (!LinkAsLibrary) {
592 // If the user wants to run a post-link optimization, run it now.
593 if (!PostLinkOpts.empty()) {
594 std::vector<std::string> opts = PostLinkOpts;
595 for (std::vector<std::string>::iterator I = opts.begin(),
596 E = opts.end(); I != E; ++I) {
598 if (!prog.canExecute()) {
599 prog = sys::Program::FindProgramByName(*I);
601 PrintAndExit(std::string("Optimization program '") + *I +
602 "' is not found or not executable.");
604 // Get the program arguments
605 sys::Path tmp_output("opt_result");
607 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
608 PrintAndExit(ErrMsg);
611 args[0] = I->c_str();
612 args[1] = BitcodeOutputFilename.c_str();
613 args[2] = tmp_output.c_str();
615 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
616 if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
617 sys::Path target(BitcodeOutputFilename);
618 target.eraseFromDisk();
619 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
620 PrintAndExit(ErrMsg, 2);
622 PrintAndExit("Post-link optimization output is not bitcode");
624 PrintAndExit(ErrMsg);
629 // If the user wants to generate a native executable, compile it from the
632 // Otherwise, create a script that will run the bitcode through the JIT.
634 // Name of the Assembly Language output file
635 sys::Path AssemblyFile ( OutputFilename);
636 AssemblyFile.appendSuffix("s");
638 // Mark the output files for removal if we get an interrupt.
639 sys::RemoveFileOnSignal(AssemblyFile);
640 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
642 // Determine the locations of the llc and gcc programs.
643 sys::Path llc = FindExecutable("llc", argv[0]);
645 PrintAndExit("Failed to find llc");
647 sys::Path gcc = FindExecutable("gcc", argv[0]);
649 PrintAndExit("Failed to find gcc");
651 // Generate an assembly language file for the bitcode.
653 if (0 != GenerateAssembly(AssemblyFile.toString(), BitcodeOutputFilename,
655 PrintAndExit(ErrMsg);
657 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
658 NativeLinkItems, gcc, envp, ErrMsg))
659 PrintAndExit(ErrMsg);
661 // Remove the assembly language file.
662 AssemblyFile.eraseFromDisk();
663 } else if (NativeCBE) {
664 sys::Path CFile (OutputFilename);
665 CFile.appendSuffix("cbe.c");
667 // Mark the output files for removal if we get an interrupt.
668 sys::RemoveFileOnSignal(CFile);
669 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
671 // Determine the locations of the llc and gcc programs.
672 sys::Path llc = FindExecutable("llc", argv[0]);
674 PrintAndExit("Failed to find llc");
676 sys::Path gcc = FindExecutable("gcc", argv[0]);
678 PrintAndExit("Failed to find gcc");
680 // Generate an assembly language file for the bitcode.
682 if (0 != GenerateCFile(
683 CFile.toString(), BitcodeOutputFilename, llc, ErrMsg))
684 PrintAndExit(ErrMsg);
686 if (0 != GenerateNative(OutputFilename, CFile.toString(),
687 NativeLinkItems, gcc, envp, ErrMsg))
688 PrintAndExit(ErrMsg);
690 // Remove the assembly language file.
691 CFile.eraseFromDisk();
694 EmitShellScript(argv);
697 // Make the script executable...
699 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
700 PrintAndExit(ErrMsg);
702 // Make the bitcode file readable and directly executable in LLEE as well
703 if (sys::Path(BitcodeOutputFilename).makeExecutableOnDisk(&ErrMsg))
704 PrintAndExit(ErrMsg);
706 if (sys::Path(BitcodeOutputFilename).makeReadableOnDisk(&ErrMsg))
707 PrintAndExit(ErrMsg);
709 } catch (const std::string& msg) {
712 PrintAndExit("Unexpected unknown exception occurred.", 2);