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.
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/Support/raw_ostream.h"
39 #include "llvm/System/Signals.h"
40 #include "llvm/Config/config.h"
45 // Rightly this should go in a header file but it just seems such a waste.
47 extern void Optimize(Module*);
50 // Input/Output Options
51 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
52 cl::desc("<input bitcode files>"));
54 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
55 cl::desc("Override output filename"),
56 cl::value_desc("filename"));
58 static cl::opt<std::string> BitcodeOutputFilename("b", cl::init(""),
59 cl::desc("Override bitcode output filename"),
60 cl::value_desc("filename"));
62 static cl::opt<bool> Verbose("v",
63 cl::desc("Print information about actions taken"));
65 static cl::list<std::string> LibPaths("L", cl::Prefix,
66 cl::desc("Specify a library search path"),
67 cl::value_desc("directory"));
69 static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
70 cl::desc("Specify a framework search path"),
71 cl::value_desc("directory"));
73 static cl::list<std::string> Libraries("l", cl::Prefix,
74 cl::desc("Specify libraries to link to"),
75 cl::value_desc("library prefix"));
77 static cl::list<std::string> Frameworks("framework",
78 cl::desc("Specify frameworks to link to"),
79 cl::value_desc("framework"));
81 // Options to control the linking, optimization, and code gen processes
82 static cl::opt<bool> LinkAsLibrary("link-as-library",
83 cl::desc("Link the .bc files together as a library, not an executable"));
85 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
86 cl::desc("Alias for -link-as-library"));
88 static cl::opt<bool> Native("native",
89 cl::desc("Generate a native binary instead of a shell script"));
91 static cl::opt<bool>NativeCBE("native-cbe",
92 cl::desc("Generate a native binary with the C backend and GCC"));
94 static cl::list<std::string> PostLinkOpts("post-link-opts",
95 cl::value_desc("path"),
96 cl::desc("Run one or more optimization programs after linking"));
98 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
99 cl::desc("Pass options to the system linker"));
101 // Compatibility options that llvm-ld ignores but are supported for
102 // compatibility with LD
103 static cl::opt<std::string> CO3("soname", cl::Hidden,
104 cl::desc("Compatibility option: ignored"));
106 static cl::opt<std::string> CO4("version-script", cl::Hidden,
107 cl::desc("Compatibility option: ignored"));
109 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
110 cl::desc("Compatibility option: ignored"));
112 static cl::opt<std::string> CO6("h", cl::Hidden,
113 cl::desc("Compatibility option: ignored"));
115 static cl::opt<bool> CO7("start-group", cl::Hidden,
116 cl::desc("Compatibility option: ignored"));
118 static cl::opt<bool> CO8("end-group", cl::Hidden,
119 cl::desc("Compatibility option: ignored"));
121 static cl::opt<std::string> CO9("m", cl::Hidden,
122 cl::desc("Compatibility option: ignored"));
124 /// This is just for convenience so it doesn't have to be passed around
126 static std::string progname;
128 /// PrintAndExit - Prints a message to standard error and exits with error code
131 /// Message - The message to print to standard error.
133 static void PrintAndExit(const std::string &Message, int errcode = 1) {
134 errs() << progname << ": " << Message << "\n";
139 static void PrintCommand(const std::vector<const char*> &args) {
140 std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
143 outs() << "'" << *I << "'" << " ";
144 outs() << "\n"; outs().flush();
147 /// CopyEnv - This function takes an array of environment variables and makes a
148 /// copy of it. This copy can then be manipulated any way the caller likes
149 /// without affecting the process's real environment.
152 /// envp - An array of C strings containing an environment.
155 /// NULL - An error occurred.
157 /// Otherwise, a pointer to a new array of C strings is returned. Every string
158 /// in the array is a duplicate of the one in the original array (i.e. we do
159 /// not copy the char *'s from one array to another).
161 static char ** CopyEnv(char ** const envp) {
162 // Count the number of entries in the old list;
163 unsigned entries; // The number of entries in the old environment list
164 for (entries = 0; envp[entries] != NULL; entries++)
167 // Add one more entry for the NULL pointer that ends the list.
170 // If there are no entries at all, just return NULL.
174 // Allocate a new environment list.
175 char **newenv = new char* [entries];
176 if ((newenv = new char* [entries]) == NULL)
179 // Make a copy of the list. Don't forget the NULL that ends the list.
181 while (envp[entries] != NULL) {
182 size_t len = strlen(envp[entries]) + 1;
183 newenv[entries] = new char[len];
184 memcpy(newenv[entries], envp[entries], len);
187 newenv[entries] = NULL;
193 /// RemoveEnv - Remove the specified environment variable from the environment
197 /// name - The name of the variable to remove. It cannot be NULL.
198 /// envp - The array of environment variables. It cannot be NULL.
201 /// This is mainly done because functions to remove items from the environment
202 /// are not available across all platforms. In particular, Solaris does not
203 /// seem to have an unsetenv() function or a setenv() function (or they are
204 /// undocumented if they do exist).
206 static void RemoveEnv(const char * name, char ** const envp) {
207 for (unsigned index=0; envp[index] != NULL; index++) {
208 // Find the first equals sign in the array and make it an EOS character.
209 char *p = strchr (envp[index], '=');
215 // Compare the two strings. If they are equal, zap this string.
216 // Otherwise, restore it.
217 if (!strcmp(name, envp[index]))
226 /// GenerateBitcode - generates a bitcode file from the module provided
227 void GenerateBitcode(Module* M, const std::string& FileName) {
230 outs() << "Generating Bitcode To " << FileName << '\n';
232 // Create the output file.
233 std::string ErrorInfo;
234 raw_fd_ostream Out(FileName.c_str(), ErrorInfo,
235 raw_fd_ostream::F_Binary);
236 if (!ErrorInfo.empty())
237 PrintAndExit(ErrorInfo);
239 // Ensure that the bitcode file gets removed from the disk if we get a
240 // terminating signal.
241 sys::RemoveFileOnSignal(sys::Path(FileName));
244 WriteBitcodeToFile(M, Out);
246 // Close the bitcode file.
250 /// GenerateAssembly - generates a native assembly language source file from the
251 /// specified bitcode file.
254 /// InputFilename - The name of the input bitcode file.
255 /// OutputFilename - The name of the file to generate.
256 /// llc - The pathname to use for LLC.
257 /// envp - The environment to use when running LLC.
259 /// Return non-zero value on error.
261 static int GenerateAssembly(const std::string &OutputFilename,
262 const std::string &InputFilename,
263 const sys::Path &llc,
264 std::string &ErrMsg ) {
265 // Run LLC to convert the bitcode file into assembly code.
266 std::vector<const char*> args;
267 args.push_back(llc.c_str());
268 // We will use GCC to assemble the program so set the assembly syntax to AT&T,
269 // regardless of what the target in the bitcode file is.
270 args.push_back("-x86-asm-syntax=att");
271 args.push_back("-f");
272 args.push_back("-o");
273 args.push_back(OutputFilename.c_str());
274 args.push_back(InputFilename.c_str());
278 outs() << "Generating Assembly With: \n";
282 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
285 /// GenerateCFile - generates a C source file from the specified bitcode file.
286 static int GenerateCFile(const std::string &OutputFile,
287 const std::string &InputFile,
288 const sys::Path &llc,
289 std::string& ErrMsg) {
290 // Run LLC to convert the bitcode file into C.
291 std::vector<const char*> args;
292 args.push_back(llc.c_str());
293 args.push_back("-march=c");
294 args.push_back("-f");
295 args.push_back("-o");
296 args.push_back(OutputFile.c_str());
297 args.push_back(InputFile.c_str());
301 outs() << "Generating C Source With: \n";
305 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
308 /// GenerateNative - generates a native object file from the
309 /// specified bitcode file.
312 /// InputFilename - The name of the input bitcode file.
313 /// OutputFilename - The name of the file to generate.
314 /// NativeLinkItems - The native libraries, files, code with which to link
315 /// LibPaths - The list of directories in which to find libraries.
316 /// FrameworksPaths - The list of directories in which to find frameworks.
317 /// Frameworks - The list of frameworks (dynamic libraries)
318 /// gcc - The pathname to use for GGC.
319 /// envp - A copy of the process's current environment.
324 /// Returns non-zero value on error.
326 static int GenerateNative(const std::string &OutputFilename,
327 const std::string &InputFilename,
328 const Linker::ItemList &LinkItems,
329 const sys::Path &gcc, char ** const envp,
330 std::string& ErrMsg) {
331 // Remove these environment variables from the environment of the
332 // programs that we will execute. It appears that GCC sets these
333 // environment variables so that the programs it uses can configure
334 // themselves identically.
336 // However, when we invoke GCC below, we want it to use its normal
337 // configuration. Hence, we must sanitize its environment.
338 char ** clean_env = CopyEnv(envp);
339 if (clean_env == NULL)
341 RemoveEnv("LIBRARY_PATH", clean_env);
342 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
343 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
344 RemoveEnv("COMPILER_PATH", clean_env);
345 RemoveEnv("COLLECT_GCC", clean_env);
348 // Run GCC to assemble and link the program into native code.
351 // We can't just assemble and link the file with the system assembler
352 // and linker because we don't know where to put the _start symbol.
353 // GCC mysteriously knows how to do it.
354 std::vector<std::string> args;
355 args.push_back(gcc.c_str());
356 args.push_back("-fno-strict-aliasing");
357 args.push_back("-O3");
358 args.push_back("-o");
359 args.push_back(OutputFilename);
360 args.push_back(InputFilename);
362 // Add in the library and framework paths
363 for (unsigned index = 0; index < LibPaths.size(); index++) {
364 args.push_back("-L" + LibPaths[index]);
366 for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
367 args.push_back("-F" + FrameworkPaths[index]);
370 // Add the requested options
371 for (unsigned index = 0; index < XLinker.size(); index++)
372 args.push_back(XLinker[index]);
374 // Add in the libraries to link.
375 for (unsigned index = 0; index < LinkItems.size(); index++)
376 if (LinkItems[index].first != "crtend") {
377 if (LinkItems[index].second)
378 args.push_back("-l" + LinkItems[index].first);
380 args.push_back(LinkItems[index].first);
383 // Add in frameworks to link.
384 for (unsigned index = 0; index < Frameworks.size(); index++) {
385 args.push_back("-framework");
386 args.push_back(Frameworks[index]);
389 // Now that "args" owns all the std::strings for the arguments, call the c_str
390 // method to get the underlying string array. We do this game so that the
391 // std::string array is guaranteed to outlive the const char* array.
392 std::vector<const char *> Args;
393 for (unsigned i = 0, e = args.size(); i != e; ++i)
394 Args.push_back(args[i].c_str());
398 outs() << "Generating Native Executable With:\n";
402 // Run the compiler to assembly and link together the program.
403 int R = sys::Program::ExecuteAndWait(
404 gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
409 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
410 /// bitcode file for the program.
411 static void EmitShellScript(char **argv) {
413 outs() << "Emitting Shell Script\n";
414 #if defined(_WIN32) || defined(__CYGWIN__)
415 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
416 // support windows systems, we copy the llvm-stub.exe executable from the
417 // build tree to the destination file.
419 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0],
420 (void *)(intptr_t)&Optimize);
421 if (llvmstub.isEmpty())
422 PrintAndExit("Could not find llvm-stub.exe executable!");
424 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
425 PrintAndExit(ErrMsg);
430 // Output the script to start the program...
431 std::string ErrorInfo;
432 raw_fd_ostream Out2(OutputFilename.c_str(), ErrorInfo);
433 if (!ErrorInfo.empty())
434 PrintAndExit(ErrorInfo);
436 Out2 << "#!/bin/sh\n";
437 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
438 Out2 << "lli=${LLVMINTERP-lli}\n";
439 Out2 << "exec $lli \\\n";
440 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
441 LibPaths.push_back("/lib");
442 LibPaths.push_back("/usr/lib");
443 LibPaths.push_back("/usr/X11R6/lib");
444 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
445 // shared object at all! See RH 8: plain text.
446 std::vector<std::string>::iterator libc =
447 std::find(Libraries.begin(), Libraries.end(), "c");
448 if (libc != Libraries.end()) Libraries.erase(libc);
449 // List all the shared object (native) libraries this executable will need
450 // on the command line, so that we don't have to do this manually!
451 for (std::vector<std::string>::iterator i = Libraries.begin(),
452 e = Libraries.end(); i != e; ++i) {
453 // try explicit -L arguments first:
454 sys::Path FullLibraryPath;
455 for (cl::list<std::string>::const_iterator P = LibPaths.begin(),
456 E = LibPaths.end(); P != E; ++P) {
457 FullLibraryPath = *P;
458 FullLibraryPath.appendComponent("lib" + *i);
459 FullLibraryPath.appendSuffix(&(LTDL_SHLIB_EXT[1]));
460 if (!FullLibraryPath.isEmpty()) {
461 if (!FullLibraryPath.isDynamicLibrary()) {
462 // Not a native shared library; mark as invalid
463 FullLibraryPath = sys::Path();
467 if (FullLibraryPath.isEmpty())
468 FullLibraryPath = sys::Path::FindLibrary(*i);
469 if (!FullLibraryPath.isEmpty())
470 Out2 << " -load=" << FullLibraryPath.str() << " \\\n";
472 Out2 << " " << BitcodeOutputFilename << " ${1+\"$@\"}\n";
476 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
477 // linker function by combining the Files and Libraries in the order they were
478 // declared on the command line.
479 static void BuildLinkItems(
480 Linker::ItemList& Items,
481 const cl::list<std::string>& Files,
482 const cl::list<std::string>& Libraries) {
484 // Build the list of linkage items for LinkItems.
486 cl::list<std::string>::const_iterator fileIt = Files.begin();
487 cl::list<std::string>::const_iterator libIt = Libraries.begin();
489 int libPos = -1, filePos = -1;
490 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
491 if (libIt != Libraries.end())
492 libPos = Libraries.getPosition(libIt - Libraries.begin());
495 if (fileIt != Files.end())
496 filePos = Files.getPosition(fileIt - Files.begin());
500 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
502 Items.push_back(std::make_pair(*fileIt++, false));
503 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
505 Items.push_back(std::make_pair(*libIt++, true));
510 int main(int argc, char **argv, char **envp) {
511 // Print a stack trace if we signal out.
512 sys::PrintStackTraceOnErrorSignal();
513 PrettyStackTraceProgram X(argc, argv);
515 LLVMContext &Context = getGlobalContext();
516 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
518 // Initial global variable above for convenience printing of program name.
519 progname = sys::Path(argv[0]).getBasename();
521 // Parse the command line options
522 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
524 // Construct a Linker (now that Verbose is set)
525 Linker TheLinker(progname, OutputFilename, Context, Verbose);
527 // Keep track of the native link items (versus the bitcode items)
528 Linker::ItemList NativeLinkItems;
530 // Add library paths to the linker
531 TheLinker.addPaths(LibPaths);
532 TheLinker.addSystemPaths();
534 // Remove any consecutive duplicates of the same library...
535 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
539 std::vector<sys::Path> Files;
540 for (unsigned i = 0; i < InputFilenames.size(); ++i )
541 Files.push_back(sys::Path(InputFilenames[i]));
542 if (TheLinker.LinkInFiles(Files))
543 return 1; // Error already printed
545 // The libraries aren't linked in but are noted as "dependent" in the
547 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
548 E = Libraries.end(); I != E ; ++I) {
549 TheLinker.getModule()->addLibrary(*I);
552 // Build a list of the items from our command line
553 Linker::ItemList Items;
554 BuildLinkItems(Items, InputFilenames, Libraries);
556 // Link all the items together
557 if (TheLinker.LinkInItems(Items, NativeLinkItems) )
558 return 1; // Error already printed
561 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
563 // Optimize the module
564 Optimize(Composite.get());
566 #if defined(_WIN32) || defined(__CYGWIN__)
567 if (!LinkAsLibrary) {
568 // Default to "a.exe" instead of "a.out".
569 if (OutputFilename.getNumOccurrences() == 0)
570 OutputFilename = "a.exe";
572 // If there is no suffix add an "exe" one.
573 sys::Path ExeFile( OutputFilename );
574 if (ExeFile.getSuffix() == "") {
575 ExeFile.appendSuffix("exe");
576 OutputFilename = ExeFile.str();
581 // Generate the bitcode for the optimized module.
582 // If -b wasn't specified, use the name specified
583 // with -o to construct BitcodeOutputFilename.
584 if (BitcodeOutputFilename.empty()) {
585 BitcodeOutputFilename = OutputFilename;
586 if (!LinkAsLibrary) BitcodeOutputFilename += ".bc";
589 GenerateBitcode(Composite.get(), BitcodeOutputFilename);
591 // If we are not linking a library, generate either a native executable
592 // or a JIT shell script, depending upon what the user wants.
593 if (!LinkAsLibrary) {
594 // If the user wants to run a post-link optimization, run it now.
595 if (!PostLinkOpts.empty()) {
596 std::vector<std::string> opts = PostLinkOpts;
597 for (std::vector<std::string>::iterator I = opts.begin(),
598 E = opts.end(); I != E; ++I) {
600 if (!prog.canExecute()) {
601 prog = sys::Program::FindProgramByName(*I);
603 PrintAndExit(std::string("Optimization program '") + *I +
604 "' is not found or not executable.");
606 // Get the program arguments
607 sys::Path tmp_output("opt_result");
609 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
610 PrintAndExit(ErrMsg);
613 args[0] = I->c_str();
614 args[1] = BitcodeOutputFilename.c_str();
615 args[2] = tmp_output.c_str();
617 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
618 if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
619 sys::Path target(BitcodeOutputFilename);
620 target.eraseFromDisk();
621 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
622 PrintAndExit(ErrMsg, 2);
624 PrintAndExit("Post-link optimization output is not bitcode");
626 PrintAndExit(ErrMsg);
631 // If the user wants to generate a native executable, compile it from the
634 // Otherwise, create a script that will run the bitcode through the JIT.
636 // Name of the Assembly Language output file
637 sys::Path AssemblyFile ( OutputFilename);
638 AssemblyFile.appendSuffix("s");
640 // Mark the output files for removal if we get an interrupt.
641 sys::RemoveFileOnSignal(AssemblyFile);
642 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
644 // Determine the locations of the llc and gcc programs.
645 sys::Path llc = FindExecutable("llc", argv[0],
646 (void *)(intptr_t)&Optimize);
648 PrintAndExit("Failed to find llc");
650 sys::Path gcc = sys::Program::FindProgramByName("gcc");
652 PrintAndExit("Failed to find gcc");
654 // Generate an assembly language file for the bitcode.
656 if (0 != GenerateAssembly(AssemblyFile.str(), BitcodeOutputFilename,
658 PrintAndExit(ErrMsg);
660 if (0 != GenerateNative(OutputFilename, AssemblyFile.str(),
661 NativeLinkItems, gcc, envp, ErrMsg))
662 PrintAndExit(ErrMsg);
664 // Remove the assembly language file.
665 AssemblyFile.eraseFromDisk();
666 } else if (NativeCBE) {
667 sys::Path CFile (OutputFilename);
668 CFile.appendSuffix("cbe.c");
670 // Mark the output files for removal if we get an interrupt.
671 sys::RemoveFileOnSignal(CFile);
672 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
674 // Determine the locations of the llc and gcc programs.
675 sys::Path llc = FindExecutable("llc", argv[0],
676 (void *)(intptr_t)&Optimize);
678 PrintAndExit("Failed to find llc");
680 sys::Path gcc = sys::Program::FindProgramByName("gcc");
682 PrintAndExit("Failed to find gcc");
684 // Generate an assembly language file for the bitcode.
686 if (GenerateCFile(CFile.str(), BitcodeOutputFilename, llc, ErrMsg))
687 PrintAndExit(ErrMsg);
689 if (GenerateNative(OutputFilename, CFile.str(),
690 NativeLinkItems, gcc, envp, ErrMsg))
691 PrintAndExit(ErrMsg);
693 // Remove the assembly language file.
694 CFile.eraseFromDisk();
697 EmitShellScript(argv);
700 // Make the script executable...
702 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
703 PrintAndExit(ErrMsg);
705 // Make the bitcode file readable and directly executable in LLEE as well
706 if (sys::Path(BitcodeOutputFilename).makeExecutableOnDisk(&ErrMsg))
707 PrintAndExit(ErrMsg);
709 if (sys::Path(BitcodeOutputFilename).makeReadableOnDisk(&ErrMsg))
710 PrintAndExit(ErrMsg);