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/System/Program.h"
25 #include "llvm/Module.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Bytecode/Reader.h"
28 #include "llvm/Bytecode/Writer.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/SystemUtils.h"
35 #include "llvm/System/Signals.h"
42 // Input/Output Options
43 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
44 cl::desc("<input bytecode files>"));
46 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
47 cl::desc("Override output filename"),
48 cl::value_desc("filename"));
50 static cl::opt<bool> Verbose("v",
51 cl::desc("Print information about actions taken"));
53 static cl::list<std::string> LibPaths("L", cl::Prefix,
54 cl::desc("Specify a library search path"),
55 cl::value_desc("directory"));
57 static cl::list<std::string> Libraries("l", cl::Prefix,
58 cl::desc("Specify libraries to link to"),
59 cl::value_desc("library prefix"));
61 static cl::opt<bool> LinkAsLibrary("link-as-library",
62 cl::desc("Link the .bc files together as a library, not an executable"));
64 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
65 cl::desc("Alias for -link-as-library"));
67 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
68 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
70 static cl::opt<bool> Native("native",
71 cl::desc("Generate a native binary instead of a shell script"));
73 static cl::opt<bool>NativeCBE("native-cbe",
74 cl::desc("Generate a native binary with the C backend and GCC"));
76 static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
77 cl::desc("Disable writing of compressed bytecode files"));
79 static cl::list<std::string> PostLinkOpts("post-link-opts",
80 cl::value_desc("path to post-link optimization programs"),
81 cl::desc("Run one or more optimization programs after linking"));
83 // Compatibility options that are ignored but supported by LD
84 static cl::opt<std::string> CO3("soname", cl::Hidden,
85 cl::desc("Compatibility option: ignored"));
87 static cl::opt<std::string> CO4("version-script", cl::Hidden,
88 cl::desc("Compatibility option: ignored"));
90 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
91 cl::desc("Compatibility option: ignored"));
93 static cl::opt<std::string> CO6("h", cl::Hidden,
94 cl::desc("Compatibility option: ignored"));
96 /// This is just for convenience so it doesn't have to be passed around
98 static std::string progname;
100 /// PrintAndReturn - Prints a message to standard error and returns true.
103 /// progname - The name of the program (i.e. argv[0]).
104 /// Message - The message to print to standard error.
106 static int PrintAndReturn(const std::string &Message) {
107 std::cerr << progname << ": " << Message << "\n";
111 /// CopyEnv - This function takes an array of environment variables and makes a
112 /// copy of it. This copy can then be manipulated any way the caller likes
113 /// without affecting the process's real environment.
116 /// envp - An array of C strings containing an environment.
119 /// NULL - An error occurred.
121 /// Otherwise, a pointer to a new array of C strings is returned. Every string
122 /// in the array is a duplicate of the one in the original array (i.e. we do
123 /// not copy the char *'s from one array to another).
125 static char ** CopyEnv(char ** const envp) {
126 // Count the number of entries in the old list;
127 unsigned entries; // The number of entries in the old environment list
128 for (entries = 0; envp[entries] != NULL; entries++)
131 // Add one more entry for the NULL pointer that ends the list.
134 // If there are no entries at all, just return NULL.
138 // Allocate a new environment list.
139 char **newenv = new char* [entries];
140 if ((newenv = new char* [entries]) == NULL)
143 // Make a copy of the list. Don't forget the NULL that ends the list.
145 while (envp[entries] != NULL) {
146 newenv[entries] = new char[strlen (envp[entries]) + 1];
147 strcpy (newenv[entries], envp[entries]);
150 newenv[entries] = NULL;
156 /// RemoveEnv - Remove the specified environment variable from the environment
160 /// name - The name of the variable to remove. It cannot be NULL.
161 /// envp - The array of environment variables. It cannot be NULL.
164 /// This is mainly done because functions to remove items from the environment
165 /// are not available across all platforms. In particular, Solaris does not
166 /// seem to have an unsetenv() function or a setenv() function (or they are
167 /// undocumented if they do exist).
169 static void RemoveEnv(const char * name, char ** const envp) {
170 for (unsigned index=0; envp[index] != NULL; index++) {
171 // Find the first equals sign in the array and make it an EOS character.
172 char *p = strchr (envp[index], '=');
178 // Compare the two strings. If they are equal, zap this string.
179 // Otherwise, restore it.
180 if (!strcmp(name, envp[index]))
189 /// GenerateBytecode - generates a bytecode file from the module provided
190 void GenerateBytecode(Module* M, const std::string& FileName) {
192 // Create the output file.
193 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
195 std::ofstream Out(FileName.c_str(), io_mode);
197 PrintAndReturn("error opening '" + FileName + "' for writing!");
201 // Ensure that the bytecode file gets removed from the disk if we get a
202 // terminating signal.
203 sys::RemoveFileOnSignal(sys::Path(FileName));
206 WriteBytecodeToFile(M, Out, !DisableCompression);
208 // Close the bytecode file.
212 /// GenerateAssembly - generates a native assembly language source file from the
213 /// specified bytecode file.
216 /// InputFilename - The name of the output bytecode file.
217 /// OutputFilename - The name of the file to generate.
218 /// llc - The pathname to use for LLC.
219 /// envp - The environment to use when running LLC.
221 /// Return non-zero value on error.
223 static int GenerateAssembly(const std::string &OutputFilename,
224 const std::string &InputFilename,
225 const sys::Path &llc) {
226 // Run LLC to convert the bytecode file into assembly code.
227 std::vector<const char*> args;
228 args.push_back(llc.c_str());
229 args.push_back("-f");
230 args.push_back("-o");
231 args.push_back(OutputFilename.c_str());
232 args.push_back(InputFilename.c_str());
235 return sys::Program::ExecuteAndWait(llc,&args[0]);
238 /// GenerateAssembly - generates a native assembly language source file from the
239 /// specified bytecode file.
240 static int GenerateCFile(const std::string &OutputFile,
241 const std::string &InputFile,
242 const sys::Path &llc) {
243 // Run LLC to convert the bytecode file into C.
244 std::vector<const char*> args;
245 args.push_back(llc.c_str());
246 args.push_back("-march=c");
247 args.push_back("-f");
248 args.push_back("-o");
249 args.push_back(OutputFile.c_str());
250 args.push_back(InputFile.c_str());
252 return sys::Program::ExecuteAndWait(llc, &args[0]);
255 /// GenerateNative - generates a native assembly language source file from the
256 /// specified assembly source file.
259 /// InputFilename - The name of the output bytecode file.
260 /// OutputFilename - The name of the file to generate.
261 /// Libraries - The list of libraries with which to link.
262 /// LibPaths - The list of directories in which to find libraries.
263 /// gcc - The pathname to use for GGC.
264 /// envp - A copy of the process's current environment.
269 /// Returns non-zero value on error.
271 static int GenerateNative(const std::string &OutputFilename,
272 const std::string &InputFilename,
273 const std::vector<std::string> &Libraries,
274 const sys::Path &gcc, char ** const envp) {
275 // Remove these environment variables from the environment of the
276 // programs that we will execute. It appears that GCC sets these
277 // environment variables so that the programs it uses can configure
278 // themselves identically.
280 // However, when we invoke GCC below, we want it to use its normal
281 // configuration. Hence, we must sanitize its environment.
282 char ** clean_env = CopyEnv(envp);
283 if (clean_env == NULL)
285 RemoveEnv("LIBRARY_PATH", clean_env);
286 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
287 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
288 RemoveEnv("COMPILER_PATH", clean_env);
289 RemoveEnv("COLLECT_GCC", clean_env);
292 // Run GCC to assemble and link the program into native code.
295 // We can't just assemble and link the file with the system assembler
296 // and linker because we don't know where to put the _start symbol.
297 // GCC mysteriously knows how to do it.
298 std::vector<const char*> args;
299 args.push_back(gcc.c_str());
300 args.push_back("-fno-strict-aliasing");
301 args.push_back("-O3");
302 args.push_back("-o");
303 args.push_back(OutputFilename.c_str());
304 args.push_back(InputFilename.c_str());
306 // Add in the libraries to link.
307 for (unsigned index = 0; index < Libraries.size(); index++)
308 if (Libraries[index] != "crtend") {
309 args.push_back("-l");
310 args.push_back(Libraries[index].c_str());
314 // Run the compiler to assembly and link together the program.
315 int R = sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
320 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
321 /// bytecode file for the program.
322 static void EmitShellScript(char **argv) {
323 #if defined(_WIN32) || defined(__CYGWIN__)
324 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
325 // support windows systems, we copy the llvm-stub.exe executable from the
326 // build tree to the destination file.
327 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
328 if (llvmstub.isEmpty()) {
329 std::cerr << "Could not find llvm-stub.exe executable!\n";
332 sys::CopyFile(sys::Path(OutputFilename), llvmstub);
336 // Output the script to start the program...
337 std::ofstream Out2(OutputFilename.c_str());
339 exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
341 Out2 << "#!/bin/sh\n";
342 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
343 Out2 << "lli=${LLVMINTERP-lli}\n";
344 Out2 << "exec $lli \\\n";
345 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
346 LibPaths.push_back("/lib");
347 LibPaths.push_back("/usr/lib");
348 LibPaths.push_back("/usr/X11R6/lib");
349 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
350 // shared object at all! See RH 8: plain text.
351 std::vector<std::string>::iterator libc =
352 std::find(Libraries.begin(), Libraries.end(), "c");
353 if (libc != Libraries.end()) Libraries.erase(libc);
354 // List all the shared object (native) libraries this executable will need
355 // on the command line, so that we don't have to do this manually!
356 for (std::vector<std::string>::iterator i = Libraries.begin(),
357 e = Libraries.end(); i != e; ++i) {
358 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
359 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
360 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
362 Out2 << " $0.bc ${1+\"$@\"}\n";
366 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
367 // linker function by combining the Files and Libraries in the order they were
368 // declared on the command line.
369 static void BuildLinkItems(
370 Linker::ItemList& Items,
371 const cl::list<std::string>& Files,
372 const cl::list<std::string>& Libraries) {
374 // Build the list of linkage items for LinkItems.
376 cl::list<std::string>::const_iterator fileIt = Files.begin();
377 cl::list<std::string>::const_iterator libIt = Libraries.begin();
379 int libPos = -1, filePos = -1;
380 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
381 if (libIt != Libraries.end())
382 libPos = Libraries.getPosition(libIt - Libraries.begin());
385 if (fileIt != Files.end())
386 filePos = Files.getPosition(fileIt - Files.begin());
390 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
392 Items.push_back(std::make_pair(*fileIt++, false));
393 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
395 Items.push_back(std::make_pair(*libIt++, true));
400 // Rightly this should go in a header file but it just seems such a waste.
402 extern void Optimize(Module*);
405 int main(int argc, char **argv, char **envp) {
407 // Initial global variable above for convenience printing of program name.
408 progname = sys::Path(argv[0]).getBasename();
409 Linker TheLinker(progname, OutputFilename, Verbose);
411 // Parse the command line options
412 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
413 sys::PrintStackTraceOnErrorSignal();
415 // Set up the library paths for the Linker
416 TheLinker.addPaths(LibPaths);
417 TheLinker.addSystemPaths();
419 // Remove any consecutive duplicates of the same library...
420 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
424 std::vector<sys::Path> Files;
425 for (unsigned i = 0; i < InputFilenames.size(); ++i )
426 Files.push_back(sys::Path(InputFilenames[i]));
427 if (TheLinker.LinkInFiles(Files))
428 return 1; // Error already printed
430 // The libraries aren't linked in but are noted as "dependent" in the
432 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
433 E = Libraries.end(); I != E ; ++I) {
434 TheLinker.getModule()->addLibrary(*I);
437 // Build a list of the items from our command line
438 Linker::ItemList Items;
439 Linker::ItemList NativeItems;
440 BuildLinkItems(Items, InputFilenames, Libraries);
442 // Link all the items together
443 if (TheLinker.LinkInItems(Items,NativeItems) )
447 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
449 // Optimize the module
450 Optimize(Composite.get());
452 // Generate the bytecode for the optimized module.
453 std::string RealBytecodeOutput = OutputFilename;
454 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
455 GenerateBytecode(Composite.get(), RealBytecodeOutput);
457 // If we are not linking a library, generate either a native executable
458 // or a JIT shell script, depending upon what the user wants.
459 if (!LinkAsLibrary) {
460 // If the user wants to run a post-link optimization, run it now.
461 if (!PostLinkOpts.empty()) {
462 std::vector<std::string> opts = PostLinkOpts;
463 for (std::vector<std::string>::iterator I = opts.begin(),
464 E = opts.end(); I != E; ++I) {
466 if (!prog.canExecute()) {
467 prog = sys::Program::FindProgramByName(*I);
469 return PrintAndReturn(std::string("Optimization program '") + *I +
470 "' is not found or not executable.");
472 // Get the program arguments
473 sys::Path tmp_output("opt_result");
474 if (!tmp_output.createTemporaryFileOnDisk()) {
475 return PrintAndReturn(
476 "Can't create temporary file for post-link optimization");
479 args[0] = I->c_str();
480 args[1] = RealBytecodeOutput.c_str();
481 args[2] = tmp_output.c_str();
483 if (0 == sys::Program::ExecuteAndWait(prog, args)) {
484 if (tmp_output.isBytecodeFile()) {
485 sys::Path target(RealBytecodeOutput);
486 target.eraseFromDisk();
487 tmp_output.renamePathOnDisk(target);
489 return PrintAndReturn(
490 "Post-link optimization output is not bytecode");
495 // If the user wants to generate a native executable, compile it from the
498 // Otherwise, create a script that will run the bytecode through the JIT.
500 // Name of the Assembly Language output file
501 sys::Path AssemblyFile ( OutputFilename);
502 AssemblyFile.appendSuffix("s");
504 // Mark the output files for removal if we get an interrupt.
505 sys::RemoveFileOnSignal(AssemblyFile);
506 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
508 // Determine the locations of the llc and gcc programs.
509 sys::Path llc = FindExecutable("llc", argv[0]);
511 return PrintAndReturn("Failed to find llc");
513 sys::Path gcc = FindExecutable("gcc", argv[0]);
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 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
520 if (Verbose) std::cout << "Generating Native Code\n";
521 GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
524 // Remove the assembly language file.
525 AssemblyFile.eraseFromDisk();
526 } else if (NativeCBE) {
527 sys::Path CFile (OutputFilename);
528 CFile.appendSuffix("cbe.c");
530 // Mark the output files for removal if we get an interrupt.
531 sys::RemoveFileOnSignal(CFile);
532 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
534 // Determine the locations of the llc and gcc programs.
535 sys::Path llc = FindExecutable("llc", argv[0]);
537 return PrintAndReturn("Failed to find llc");
539 sys::Path gcc = FindExecutable("gcc", argv[0]);
541 return PrintAndReturn("Failed to find gcc");
543 // Generate an assembly language file for the bytecode.
544 if (Verbose) std::cout << "Generating Assembly Code\n";
545 GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
546 if (Verbose) std::cout << "Generating Native Code\n";
547 GenerateNative(OutputFilename, CFile.toString(), Libraries, gcc, envp);
549 // Remove the assembly language file.
550 CFile.eraseFromDisk();
553 EmitShellScript(argv);
556 // Make the script executable...
557 sys::Path(OutputFilename).makeExecutableOnDisk();
559 // Make the bytecode file readable and directly executable in LLEE as well
560 sys::Path(RealBytecodeOutput).makeExecutableOnDisk();
561 sys::Path(RealBytecodeOutput).makeReadableOnDisk();
565 } catch (const std::string& msg) {
566 std::cerr << argv[0] << ": " << msg << "\n";
568 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";