1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 bytecode 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/Bytecode/Reader.h"
29 #include "llvm/Bytecode/Writer.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetMachineRegistry.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileUtilities.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/Streams.h"
37 #include "llvm/Support/SystemUtils.h"
38 #include "llvm/System/Signals.h"
43 // Input/Output Options
44 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
45 cl::desc("<input bytecode files>"));
47 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
48 cl::desc("Override output filename"),
49 cl::value_desc("filename"));
51 static cl::opt<bool> Verbose("v",
52 cl::desc("Print information about actions taken"));
54 static cl::list<std::string> LibPaths("L", cl::Prefix,
55 cl::desc("Specify a library search path"),
56 cl::value_desc("directory"));
58 static cl::list<std::string> Libraries("l", cl::Prefix,
59 cl::desc("Specify libraries to link to"),
60 cl::value_desc("library prefix"));
62 // Options to control the linking, optimization, and code gen processes
63 static cl::opt<bool> LinkAsLibrary("link-as-library",
64 cl::desc("Link the .bc files together as a library, not an executable"));
66 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
67 cl::desc("Alias for -link-as-library"));
69 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
70 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
72 static cl::opt<bool> Native("native",
73 cl::desc("Generate a native binary instead of a shell script"));
75 static cl::opt<bool>NativeCBE("native-cbe",
76 cl::desc("Generate a native binary with the C backend and GCC"));
78 static cl::opt<bool>DisableCompression("disable-compression", cl::init(true),
79 cl::desc("Disable writing of compressed bytecode files"));
81 static cl::list<std::string> PostLinkOpts("post-link-opts",
82 cl::value_desc("path"),
83 cl::desc("Run one or more optimization programs after linking"));
85 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
86 cl::desc("Pass options to the system linker"));
88 // Compatibility options that llvm-ld ignores but are supported for
89 // compatibility with LD
90 static cl::opt<std::string> CO3("soname", cl::Hidden,
91 cl::desc("Compatibility option: ignored"));
93 static cl::opt<std::string> CO4("version-script", cl::Hidden,
94 cl::desc("Compatibility option: ignored"));
96 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
97 cl::desc("Compatibility option: ignored"));
99 static cl::opt<std::string> CO6("h", cl::Hidden,
100 cl::desc("Compatibility option: ignored"));
102 static cl::opt<bool> CO7("start-group", cl::Hidden,
103 cl::desc("Compatibility option: ignored"));
105 static cl::opt<bool> CO8("end-group", cl::Hidden,
106 cl::desc("Compatibility option: ignored"));
108 /// This is just for convenience so it doesn't have to be passed around
110 static std::string progname;
112 /// PrintAndExit - Prints a message to standard error and exits with error code
115 /// Message - The message to print to standard error.
117 static void PrintAndExit(const std::string &Message, int errcode = 1) {
118 cerr << progname << ": " << Message << "\n";
123 /// CopyEnv - This function takes an array of environment variables and makes a
124 /// copy of it. This copy can then be manipulated any way the caller likes
125 /// without affecting the process's real environment.
128 /// envp - An array of C strings containing an environment.
131 /// NULL - An error occurred.
133 /// Otherwise, a pointer to a new array of C strings is returned. Every string
134 /// in the array is a duplicate of the one in the original array (i.e. we do
135 /// not copy the char *'s from one array to another).
137 static char ** CopyEnv(char ** const envp) {
138 // Count the number of entries in the old list;
139 unsigned entries; // The number of entries in the old environment list
140 for (entries = 0; envp[entries] != NULL; entries++)
143 // Add one more entry for the NULL pointer that ends the list.
146 // If there are no entries at all, just return NULL.
150 // Allocate a new environment list.
151 char **newenv = new char* [entries];
152 if ((newenv = new char* [entries]) == NULL)
155 // Make a copy of the list. Don't forget the NULL that ends the list.
157 while (envp[entries] != NULL) {
158 newenv[entries] = new char[strlen (envp[entries]) + 1];
159 strcpy (newenv[entries], envp[entries]);
162 newenv[entries] = NULL;
168 /// RemoveEnv - Remove the specified environment variable from the environment
172 /// name - The name of the variable to remove. It cannot be NULL.
173 /// envp - The array of environment variables. It cannot be NULL.
176 /// This is mainly done because functions to remove items from the environment
177 /// are not available across all platforms. In particular, Solaris does not
178 /// seem to have an unsetenv() function or a setenv() function (or they are
179 /// undocumented if they do exist).
181 static void RemoveEnv(const char * name, char ** const envp) {
182 for (unsigned index=0; envp[index] != NULL; index++) {
183 // Find the first equals sign in the array and make it an EOS character.
184 char *p = strchr (envp[index], '=');
190 // Compare the two strings. If they are equal, zap this string.
191 // Otherwise, restore it.
192 if (!strcmp(name, envp[index]))
201 /// GenerateBytecode - generates a bytecode file from the module provided
202 void GenerateBytecode(Module* M, const std::string& FileName) {
204 // Create the output file.
205 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
207 std::ofstream Out(FileName.c_str(), io_mode);
209 PrintAndExit("error opening '" + FileName + "' for writing!");
211 // Ensure that the bytecode file gets removed from the disk if we get a
212 // terminating signal.
213 sys::RemoveFileOnSignal(sys::Path(FileName));
217 WriteBytecodeToFile(M, L, !DisableCompression);
219 // Close the bytecode file.
223 /// GenerateAssembly - generates a native assembly language source file from the
224 /// specified bytecode file.
227 /// InputFilename - The name of the input bytecode file.
228 /// OutputFilename - The name of the file to generate.
229 /// llc - The pathname to use for LLC.
230 /// envp - The environment to use when running LLC.
232 /// Return non-zero value on error.
234 static int GenerateAssembly(const std::string &OutputFilename,
235 const std::string &InputFilename,
236 const sys::Path &llc,
237 std::string &ErrMsg ) {
238 // Run LLC to convert the bytecode file into assembly code.
239 std::vector<const char*> args;
240 args.push_back(llc.c_str());
241 args.push_back("-f");
242 args.push_back("-o");
243 args.push_back(OutputFilename.c_str());
244 args.push_back(InputFilename.c_str());
247 return sys::Program::ExecuteAndWait(llc,&args[0],0,0,0,&ErrMsg);
250 /// GenerateCFile - generates a C source file from the specified bytecode file.
251 static int GenerateCFile(const std::string &OutputFile,
252 const std::string &InputFile,
253 const sys::Path &llc,
254 std::string& ErrMsg) {
255 // Run LLC to convert the bytecode file into C.
256 std::vector<const char*> args;
257 args.push_back(llc.c_str());
258 args.push_back("-march=c");
259 args.push_back("-f");
260 args.push_back("-o");
261 args.push_back(OutputFile.c_str());
262 args.push_back(InputFile.c_str());
264 return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
267 /// GenerateNative - generates a native object file from the
268 /// specified bytecode file.
271 /// InputFilename - The name of the input bytecode file.
272 /// OutputFilename - The name of the file to generate.
273 /// LinkItems - The native libraries, files, code with which to link
274 /// LibPaths - The list of directories in which to find libraries.
275 /// gcc - The pathname to use for GGC.
276 /// envp - A copy of the process's current environment.
281 /// Returns non-zero value on error.
283 static int GenerateNative(const std::string &OutputFilename,
284 const std::string &InputFilename,
285 const Linker::ItemList &LinkItems,
286 const sys::Path &gcc, char ** const envp,
287 std::string& ErrMsg) {
288 // Remove these environment variables from the environment of the
289 // programs that we will execute. It appears that GCC sets these
290 // environment variables so that the programs it uses can configure
291 // themselves identically.
293 // However, when we invoke GCC below, we want it to use its normal
294 // configuration. Hence, we must sanitize its environment.
295 char ** clean_env = CopyEnv(envp);
296 if (clean_env == NULL)
298 RemoveEnv("LIBRARY_PATH", clean_env);
299 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
300 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
301 RemoveEnv("COMPILER_PATH", clean_env);
302 RemoveEnv("COLLECT_GCC", clean_env);
305 // Run GCC to assemble and link the program into native code.
308 // We can't just assemble and link the file with the system assembler
309 // and linker because we don't know where to put the _start symbol.
310 // GCC mysteriously knows how to do it.
311 std::vector<const char*> args;
312 args.push_back(gcc.c_str());
313 args.push_back("-fno-strict-aliasing");
314 args.push_back("-O3");
315 args.push_back("-o");
316 args.push_back(OutputFilename.c_str());
317 args.push_back(InputFilename.c_str());
319 // Add in the library paths
320 for (unsigned index = 0; index < LibPaths.size(); index++) {
321 args.push_back("-L");
322 args.push_back(LibPaths[index].c_str());
325 // Add the requested options
326 for (unsigned index = 0; index < XLinker.size(); index++) {
327 args.push_back(XLinker[index].c_str());
328 args.push_back(Libraries[index].c_str());
331 // Add in the libraries to link.
332 for (unsigned index = 0; index < LinkItems.size(); index++)
333 if (LinkItems[index].first != "crtend") {
334 if (LinkItems[index].second) {
335 std::string lib_name = "-l" + LinkItems[index].first;
336 args.push_back(lib_name.c_str());
338 args.push_back(LinkItems[index].first.c_str());
343 // Run the compiler to assembly and link together the program.
344 int R = sys::Program::ExecuteAndWait(
345 gcc, &args[0], (const char**)clean_env,0,0,&ErrMsg);
350 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
351 /// bytecode file for the program.
352 static void EmitShellScript(char **argv) {
353 #if defined(_WIN32) || defined(__CYGWIN__)
354 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
355 // support windows systems, we copy the llvm-stub.exe executable from the
356 // build tree to the destination file.
358 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
359 if (llvmstub.isEmpty())
360 PrintAndExit("Could not find llvm-stub.exe executable!");
362 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
363 PrintAndExit(ErrMsg);
368 // Output the script to start the program...
369 std::ofstream Out2(OutputFilename.c_str());
371 PrintAndExit("error opening '" + OutputFilename + "' for writing!");
373 Out2 << "#!/bin/sh\n";
374 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
375 Out2 << "lli=${LLVMINTERP-lli}\n";
376 Out2 << "exec $lli \\\n";
377 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
378 LibPaths.push_back("/lib");
379 LibPaths.push_back("/usr/lib");
380 LibPaths.push_back("/usr/X11R6/lib");
381 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
382 // shared object at all! See RH 8: plain text.
383 std::vector<std::string>::iterator libc =
384 std::find(Libraries.begin(), Libraries.end(), "c");
385 if (libc != Libraries.end()) Libraries.erase(libc);
386 // List all the shared object (native) libraries this executable will need
387 // on the command line, so that we don't have to do this manually!
388 for (std::vector<std::string>::iterator i = Libraries.begin(),
389 e = Libraries.end(); i != e; ++i) {
390 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
391 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
392 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
394 Out2 << " $0.bc ${1+\"$@\"}\n";
398 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
399 // linker function by combining the Files and Libraries in the order they were
400 // declared on the command line.
401 static void BuildLinkItems(
402 Linker::ItemList& Items,
403 const cl::list<std::string>& Files,
404 const cl::list<std::string>& Libraries) {
406 // Build the list of linkage items for LinkItems.
408 cl::list<std::string>::const_iterator fileIt = Files.begin();
409 cl::list<std::string>::const_iterator libIt = Libraries.begin();
411 int libPos = -1, filePos = -1;
412 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
413 if (libIt != Libraries.end())
414 libPos = Libraries.getPosition(libIt - Libraries.begin());
417 if (fileIt != Files.end())
418 filePos = Files.getPosition(fileIt - Files.begin());
422 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
424 Items.push_back(std::make_pair(*fileIt++, false));
425 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
427 Items.push_back(std::make_pair(*libIt++, true));
432 // Rightly this should go in a header file but it just seems such a waste.
434 extern void Optimize(Module*);
437 int main(int argc, char **argv, char **envp) {
438 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
440 // Initial global variable above for convenience printing of program name.
441 progname = sys::Path(argv[0]).getBasename();
443 // Parse the command line options
444 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
445 sys::PrintStackTraceOnErrorSignal();
447 // Construct a Linker (now that Verbose is set)
448 Linker TheLinker(progname, OutputFilename, Verbose);
449 // Keep track of the native link items (vice the bytecode items)
450 Linker::ItemList LinkItems;
452 // Add library paths to the linker
453 TheLinker.addPaths(LibPaths);
454 TheLinker.addSystemPaths();
456 // Remove any consecutive duplicates of the same library...
457 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
461 std::vector<sys::Path> Files;
462 for (unsigned i = 0; i < InputFilenames.size(); ++i )
463 Files.push_back(sys::Path(InputFilenames[i]));
464 if (TheLinker.LinkInFiles(Files))
465 return 1; // Error already printed
467 // The libraries aren't linked in but are noted as "dependent" in the
469 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
470 E = Libraries.end(); I != E ; ++I) {
471 TheLinker.getModule()->addLibrary(*I);
474 // Build a list of the items from our command line
475 Linker::ItemList Items;
476 BuildLinkItems(Items, InputFilenames, Libraries);
478 // Link all the items together
479 if (TheLinker.LinkInItems(Items,LinkItems) )
480 return 1; // Error already printed
483 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
485 // Optimize the module
486 Optimize(Composite.get());
488 // Generate the bytecode for the optimized module.
489 std::string RealBytecodeOutput = OutputFilename;
490 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
491 GenerateBytecode(Composite.get(), RealBytecodeOutput);
493 // If we are not linking a library, generate either a native executable
494 // or a JIT shell script, depending upon what the user wants.
495 if (!LinkAsLibrary) {
496 // If the user wants to run a post-link optimization, run it now.
497 if (!PostLinkOpts.empty()) {
498 std::vector<std::string> opts = PostLinkOpts;
499 for (std::vector<std::string>::iterator I = opts.begin(),
500 E = opts.end(); I != E; ++I) {
502 if (!prog.canExecute()) {
503 prog = sys::Program::FindProgramByName(*I);
505 PrintAndExit(std::string("Optimization program '") + *I +
506 "' is not found or not executable.");
508 // Get the program arguments
509 sys::Path tmp_output("opt_result");
511 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
512 PrintAndExit(ErrMsg);
515 args[0] = I->c_str();
516 args[1] = RealBytecodeOutput.c_str();
517 args[2] = tmp_output.c_str();
519 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0, &ErrMsg)) {
520 if (tmp_output.isBytecodeFile()) {
521 sys::Path target(RealBytecodeOutput);
522 target.eraseFromDisk();
523 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
524 PrintAndExit(ErrMsg, 2);
526 PrintAndExit("Post-link optimization output is not bytecode");
528 PrintAndExit(ErrMsg);
533 // If the user wants to generate a native executable, compile it from the
536 // Otherwise, create a script that will run the bytecode through the JIT.
538 // Name of the Assembly Language output file
539 sys::Path AssemblyFile ( OutputFilename);
540 AssemblyFile.appendSuffix("s");
542 // Mark the output files for removal if we get an interrupt.
543 sys::RemoveFileOnSignal(AssemblyFile);
544 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
546 // Determine the locations of the llc and gcc programs.
547 sys::Path llc = FindExecutable("llc", argv[0]);
549 PrintAndExit("Failed to find llc");
551 sys::Path gcc = FindExecutable("gcc", argv[0]);
553 PrintAndExit("Failed to find gcc");
555 // Generate an assembly language file for the bytecode.
557 cout << "Generating Assembly Code\n";
559 if (0 != GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput,
561 PrintAndExit(ErrMsg);
564 cout << "Generating Native Code\n";
565 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
566 LinkItems,gcc,envp,ErrMsg))
567 PrintAndExit(ErrMsg);
569 // Remove the assembly language file.
570 AssemblyFile.eraseFromDisk();
571 } else if (NativeCBE) {
572 sys::Path CFile (OutputFilename);
573 CFile.appendSuffix("cbe.c");
575 // Mark the output files for removal if we get an interrupt.
576 sys::RemoveFileOnSignal(CFile);
577 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
579 // Determine the locations of the llc and gcc programs.
580 sys::Path llc = FindExecutable("llc", argv[0]);
582 PrintAndExit("Failed to find llc");
584 sys::Path gcc = FindExecutable("gcc", argv[0]);
586 PrintAndExit("Failed to find gcc");
588 // Generate an assembly language file for the bytecode.
590 cout << "Generating Assembly Code\n";
592 if (0 != GenerateCFile(
593 CFile.toString(), RealBytecodeOutput, llc, ErrMsg))
594 PrintAndExit(ErrMsg);
597 cout << "Generating Native Code\n";
598 if (0 != GenerateNative(OutputFilename, CFile.toString(), LinkItems,
600 PrintAndExit(ErrMsg);
602 // Remove the assembly language file.
603 CFile.eraseFromDisk();
606 EmitShellScript(argv);
609 // Make the script executable...
611 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
612 PrintAndExit(ErrMsg);
614 // Make the bytecode file readable and directly executable in LLEE as well
615 if (sys::Path(RealBytecodeOutput).makeExecutableOnDisk(&ErrMsg))
616 PrintAndExit(ErrMsg);
618 if (sys::Path(RealBytecodeOutput).makeReadableOnDisk(&ErrMsg))
619 PrintAndExit(ErrMsg);
621 } catch (const std::string& msg) {
624 PrintAndExit("Unexpected unknown exception occurred.", 2);