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/Linker.h"
24 #include "llvm/Module.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/Bytecode/Reader.h"
27 #include "llvm/Bytecode/Writer.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetMachineRegistry.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/SystemUtils.h"
34 #include "llvm/System/Signals.h"
41 // Input/Output Options
42 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
43 cl::desc("<input bytecode files>"));
45 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
46 cl::desc("Override output filename"),
47 cl::value_desc("filename"));
49 static cl::opt<bool> Verbose("v",
50 cl::desc("Print information about actions taken"));
52 static cl::list<std::string> LibPaths("L", cl::Prefix,
53 cl::desc("Specify a library search path"),
54 cl::value_desc("directory"));
56 static cl::list<std::string> Libraries("l", cl::Prefix,
57 cl::desc("Specify libraries to link to"),
58 cl::value_desc("library prefix"));
60 static cl::opt<bool> LinkAsLibrary("link-as-library",
61 cl::desc("Link the .bc files together as a library, not an executable"));
63 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
64 cl::desc("Alias for -link-as-library"));
66 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
67 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
69 static cl::opt<bool> Native("native",
70 cl::desc("Generate a native binary instead of a shell script"));
72 static cl::opt<bool>NativeCBE("native-cbe",
73 cl::desc("Generate a native binary with the C backend and GCC"));
75 static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
76 cl::desc("Disable writing of compressed bytecode files"));
78 // Compatibility options that are ignored but supported by LD
79 static cl::opt<std::string> CO3("soname", cl::Hidden,
80 cl::desc("Compatibility option: ignored"));
82 static cl::opt<std::string> CO4("version-script", cl::Hidden,
83 cl::desc("Compatibility option: ignored"));
85 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
86 cl::desc("Compatibility option: ignored"));
88 static cl::opt<std::string> CO6("h", cl::Hidden,
89 cl::desc("Compatibility option: ignored"));
91 /// This is just for convenience so it doesn't have to be passed around
93 static std::string progname;
95 /// PrintAndReturn - Prints a message to standard error and returns true.
98 /// progname - The name of the program (i.e. argv[0]).
99 /// Message - The message to print to standard error.
101 static int PrintAndReturn(const std::string &Message) {
102 std::cerr << progname << ": " << Message << "\n";
106 /// CopyEnv - This function takes an array of environment variables and makes a
107 /// copy of it. This copy can then be manipulated any way the caller likes
108 /// without affecting the process's real environment.
111 /// envp - An array of C strings containing an environment.
114 /// NULL - An error occurred.
116 /// Otherwise, a pointer to a new array of C strings is returned. Every string
117 /// in the array is a duplicate of the one in the original array (i.e. we do
118 /// not copy the char *'s from one array to another).
120 static char ** CopyEnv(char ** const envp) {
121 // Count the number of entries in the old list;
122 unsigned entries; // The number of entries in the old environment list
123 for (entries = 0; envp[entries] != NULL; entries++)
126 // Add one more entry for the NULL pointer that ends the list.
129 // If there are no entries at all, just return NULL.
133 // Allocate a new environment list.
134 char **newenv = new char* [entries];
135 if ((newenv = new char* [entries]) == NULL)
138 // Make a copy of the list. Don't forget the NULL that ends the list.
140 while (envp[entries] != NULL) {
141 newenv[entries] = new char[strlen (envp[entries]) + 1];
142 strcpy (newenv[entries], envp[entries]);
145 newenv[entries] = NULL;
151 /// RemoveEnv - Remove the specified environment variable from the environment
155 /// name - The name of the variable to remove. It cannot be NULL.
156 /// envp - The array of environment variables. It cannot be NULL.
159 /// This is mainly done because functions to remove items from the environment
160 /// are not available across all platforms. In particular, Solaris does not
161 /// seem to have an unsetenv() function or a setenv() function (or they are
162 /// undocumented if they do exist).
164 static void RemoveEnv(const char * name, char ** const envp) {
165 for (unsigned index=0; envp[index] != NULL; index++) {
166 // Find the first equals sign in the array and make it an EOS character.
167 char *p = strchr (envp[index], '=');
173 // Compare the two strings. If they are equal, zap this string.
174 // Otherwise, restore it.
175 if (!strcmp(name, envp[index]))
184 /// GenerateBytecode - generates a bytecode file from the module provided
185 void GenerateBytecode(Module* M, const std::string& FileName) {
187 // Create the output file.
188 std::ofstream Out(FileName.c_str());
190 PrintAndReturn("error opening '" + FileName + "' for writing!");
194 // Ensure that the bytecode file gets removed from the disk if we get a
195 // terminating signal.
196 sys::RemoveFileOnSignal(sys::Path(FileName));
199 WriteBytecodeToFile(M, Out, !DisableCompression);
201 // Close the bytecode file.
205 /// GenerateAssembly - generates a native assembly language source file from the
206 /// specified bytecode file.
209 /// InputFilename - The name of the output bytecode file.
210 /// OutputFilename - The name of the file to generate.
211 /// llc - The pathname to use for LLC.
212 /// envp - The environment to use when running LLC.
214 /// Return non-zero value on error.
216 static int GenerateAssembly(const std::string &OutputFilename,
217 const std::string &InputFilename,
218 const std::string &llc,
219 char ** const envp) {
220 // Run LLC to convert the bytecode file into assembly code.
222 cmd[0] = llc.c_str();
225 cmd[3] = OutputFilename.c_str();
226 cmd[4] = InputFilename.c_str();
229 return ExecWait(cmd, envp);
232 /// GenerateAssembly - generates a native assembly language source file from the
233 /// specified bytecode file.
234 static int GenerateCFile(const std::string &OutputFile,
235 const std::string &InputFile,
236 const std::string &llc, char ** const envp) {
237 // Run LLC to convert the bytecode file into C.
240 cmd[0] = llc.c_str();
244 cmd[4] = OutputFile.c_str();
245 cmd[5] = InputFile.c_str();
247 return ExecWait(cmd, envp);
250 /// GenerateNative - generates a native assembly language source file from the
251 /// specified assembly source file.
254 /// InputFilename - The name of the output bytecode file.
255 /// OutputFilename - The name of the file to generate.
256 /// Libraries - The list of libraries with which to link.
257 /// LibPaths - The list of directories in which to find libraries.
258 /// gcc - The pathname to use for GGC.
259 /// envp - A copy of the process's current environment.
264 /// Returns non-zero value on error.
266 static int GenerateNative(const std::string &OutputFilename,
267 const std::string &InputFilename,
268 const std::vector<std::string> &Libraries,
269 const std::vector<std::string> &LibPaths,
270 const std::string &gcc, char ** const envp) {
271 // Remove these environment variables from the environment of the
272 // programs that we will execute. It appears that GCC sets these
273 // environment variables so that the programs it uses can configure
274 // themselves identically.
276 // However, when we invoke GCC below, we want it to use its normal
277 // configuration. Hence, we must sanitize its environment.
278 char ** clean_env = CopyEnv(envp);
279 if (clean_env == NULL)
281 RemoveEnv("LIBRARY_PATH", clean_env);
282 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
283 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
284 RemoveEnv("COMPILER_PATH", clean_env);
285 RemoveEnv("COLLECT_GCC", clean_env);
287 std::vector<const char *> cmd;
289 // Run GCC to assemble and link the program into native code.
292 // We can't just assemble and link the file with the system assembler
293 // and linker because we don't know where to put the _start symbol.
294 // GCC mysteriously knows how to do it.
295 cmd.push_back(gcc.c_str());
296 cmd.push_back("-fno-strict-aliasing");
297 cmd.push_back("-O3");
299 cmd.push_back(OutputFilename.c_str());
300 cmd.push_back(InputFilename.c_str());
302 // Adding the library paths creates a problem for native generation. If we
303 // include the search paths from llvmgcc, then we'll be telling normal gcc
304 // to look inside of llvmgcc's library directories for libraries. This is
305 // bad because those libraries hold only bytecode files (not native object
306 // files). In the end, we attempt to link the bytecode libgcc into a native
309 // Add in the library path options.
310 for (unsigned index=0; index < LibPaths.size(); index++) {
312 cmd.push_back(LibPaths[index].c_str());
316 // Add in the libraries to link.
317 std::vector<std::string> Libs(Libraries);
318 for (unsigned index = 0; index < Libs.size(); index++) {
319 if (Libs[index] != "crtend") {
320 Libs[index] = "-l" + Libs[index];
321 cmd.push_back(Libs[index].c_str());
326 // Run the compiler to assembly and link together the program.
327 return ExecWait(&(cmd[0]), clean_env);
330 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
331 /// bytecode file for the program.
332 static void EmitShellScript(char **argv) {
333 #if defined(_WIN32) || defined(__CYGWIN__)
334 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
335 // support windows systems, we copy the llvm-stub.exe executable from the
336 // build tree to the destination file.
337 std::string llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
338 if (llvmstub.empty()) {
339 std::cerr << "Could not find llvm-stub.exe executable!\n";
342 if (CopyFile(OutputFilename, llvmstub)) {
343 std::cerr << "Could not copy the llvm-stub.exe executable!\n";
349 // Output the script to start the program...
350 std::ofstream Out2(OutputFilename.c_str());
352 exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
354 Out2 << "#!/bin/sh\n";
355 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
356 Out2 << "lli=${LLVMINTERP-lli}\n";
357 Out2 << "exec $lli \\\n";
358 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
359 LibPaths.push_back("/lib");
360 LibPaths.push_back("/usr/lib");
361 LibPaths.push_back("/usr/X11R6/lib");
362 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
363 // shared object at all! See RH 8: plain text.
364 std::vector<std::string>::iterator libc =
365 std::find(Libraries.begin(), Libraries.end(), "c");
366 if (libc != Libraries.end()) Libraries.erase(libc);
367 // List all the shared object (native) libraries this executable will need
368 // on the command line, so that we don't have to do this manually!
369 for (std::vector<std::string>::iterator i = Libraries.begin(),
370 e = Libraries.end(); i != e; ++i) {
371 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
372 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
373 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
375 Out2 << " $0.bc ${1+\"$@\"}\n";
379 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
380 // linker function by combining the Files and Libraries in the order they were
381 // declared on the command line.
382 static void BuildLinkItems(
383 Linker::ItemList& Items,
384 const cl::list<std::string>& Files,
385 const cl::list<std::string>& Libraries) {
387 // Build the list of linkage items for LinkItems.
389 cl::list<std::string>::const_iterator fileIt = Files.begin();
390 cl::list<std::string>::const_iterator libIt = Libraries.begin();
392 int libPos = -1, filePos = -1;
393 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
394 if (libIt != Libraries.end())
395 libPos = Libraries.getPosition(libIt - Libraries.begin());
398 if (fileIt != Files.end())
399 filePos = Files.getPosition(fileIt - Files.begin());
403 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
405 Items.push_back(std::make_pair(*fileIt++, false));
406 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
408 Items.push_back(std::make_pair(*libIt++, true));
413 // Rightly this should go in a header file but it just seems such a waste.
415 extern void Optimize(Module*);
418 int main(int argc, char **argv, char **envp) {
419 // Initial global variable above for convenience printing of program name.
420 progname = sys::Path(argv[0]).getBasename();
421 Linker TheLinker(progname, Verbose);
423 // Set up the library paths for the Linker
424 TheLinker.addPaths(LibPaths);
425 TheLinker.addSystemPaths();
427 // Parse the command line options
428 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
429 sys::PrintStackTraceOnErrorSignal();
431 // Remove any consecutive duplicates of the same library...
432 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
436 std::vector<sys::Path> Files;
437 for (unsigned i = 0; i < InputFilenames.size(); ++i )
438 Files.push_back(sys::Path(InputFilenames[i]));
439 if (TheLinker.LinkInFiles(Files))
440 return 1; // Error already printed
442 // The libraries aren't linked in but are noted as "dependent" in the
444 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
445 E = Libraries.end(); I != E ; ++I) {
446 TheLinker.getModule()->addLibrary(*I);
449 // Build a list of the items from our command line
450 Linker::ItemList Items;
451 BuildLinkItems(Items, InputFilenames, Libraries);
453 // Link all the items together
454 if (TheLinker.LinkInItems(Items) )
458 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
460 // Optimize the module
461 Optimize(Composite.get());
463 // Generate the bytecode for the optimized module.
464 std::string RealBytecodeOutput = OutputFilename;
465 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
466 GenerateBytecode(Composite.get(), RealBytecodeOutput);
468 // If we are not linking a library, generate either a native executable
469 // or a JIT shell script, depending upon what the user wants.
470 if (!LinkAsLibrary) {
471 // If the user wants to generate a native executable, compile it from the
474 // Otherwise, create a script that will run the bytecode through the JIT.
476 // Name of the Assembly Language output file
477 std::string AssemblyFile = OutputFilename + ".s";
479 // Mark the output files for removal if we get an interrupt.
480 sys::RemoveFileOnSignal(sys::Path(AssemblyFile));
481 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
483 // Determine the locations of the llc and gcc programs.
484 std::string llc = FindExecutable("llc", argv[0]).toString();
486 return PrintAndReturn("Failed to find llc");
488 std::string gcc = FindExecutable("gcc", argv[0]).toString();
490 return PrintAndReturn("Failed to find gcc");
492 // Generate an assembly language file for the bytecode.
493 if (Verbose) std::cout << "Generating Assembly Code\n";
494 GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
495 if (Verbose) std::cout << "Generating Native Code\n";
496 GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
499 // Remove the assembly language file.
500 removeFile (AssemblyFile);
501 } else if (NativeCBE) {
502 std::string CFile = OutputFilename + ".cbe.c";
504 // Mark the output files for removal if we get an interrupt.
505 sys::RemoveFileOnSignal(sys::Path(CFile));
506 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
508 // Determine the locations of the llc and gcc programs.
509 std::string llc = FindExecutable("llc", argv[0]).toString();
511 return PrintAndReturn("Failed to find llc");
513 std::string gcc = FindExecutable("gcc", argv[0]).toString();
515 return PrintAndReturn("Failed to find gcc");
517 // Generate an assembly language file for the bytecode.
518 if (Verbose) std::cout << "Generating Assembly Code\n";
519 GenerateCFile(CFile, RealBytecodeOutput, llc, envp);
520 if (Verbose) std::cout << "Generating Native Code\n";
521 GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp);
523 // Remove the assembly language file.
527 EmitShellScript(argv);
530 // Make the script executable...
531 sys::Path(OutputFilename).makeExecutable();
533 // Make the bytecode file readable and directly executable in LLEE as well
534 sys::Path(RealBytecodeOutput).makeExecutable();
535 sys::Path(RealBytecodeOutput).makeReadable();