9b56bdd1f0e8c456a4a4393a533d4d627e123670
[oota-llvm.git] / tools / llvm-ld / llvm-ld.cpp
1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
16 //
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.
20 //
21 //===----------------------------------------------------------------------===//
22
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/SystemUtils.h"
36 #include "llvm/System/Signals.h"
37 #include <fstream>
38 #include <iostream>
39 #include <memory>
40
41 using namespace llvm;
42
43 // Input/Output Options
44 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
45   cl::desc("<input bytecode files>"));
46
47 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
48   cl::desc("Override output filename"),
49   cl::value_desc("filename"));
50
51 static cl::opt<bool> Verbose("v",
52   cl::desc("Print information about actions taken"));
53
54 static cl::list<std::string> LibPaths("L", cl::Prefix,
55   cl::desc("Specify a library search path"),
56   cl::value_desc("directory"));
57
58 static cl::list<std::string> Libraries("l", cl::Prefix,
59   cl::desc("Specify libraries to link to"),
60   cl::value_desc("library prefix"));
61
62 static cl::opt<bool> LinkAsLibrary("link-as-library",
63   cl::desc("Link the .bc files together as a library, not an executable"));
64
65 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
66   cl::desc("Alias for -link-as-library"));
67
68 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
69   MachineArch("march", cl::desc("Architecture to generate assembly for:"));
70
71 static cl::opt<bool> Native("native",
72   cl::desc("Generate a native binary instead of a shell script"));
73
74 static cl::opt<bool>NativeCBE("native-cbe",
75   cl::desc("Generate a native binary with the C backend and GCC"));
76
77 static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
78   cl::desc("Disable writing of compressed bytecode files"));
79
80 static cl::list<std::string> PostLinkOpts("post-link-opts",
81   cl::value_desc("path"),
82   cl::desc("Run one or more optimization programs after linking"));
83
84 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
85   cl::desc("Pass options to the system linker"));
86
87 // Compatibility options that are ignored but supported by LD
88 static cl::opt<std::string> CO3("soname", cl::Hidden,
89   cl::desc("Compatibility option: ignored"));
90
91 static cl::opt<std::string> CO4("version-script", cl::Hidden,
92   cl::desc("Compatibility option: ignored"));
93
94 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
95   cl::desc("Compatibility option: ignored"));
96
97 static  cl::opt<std::string> CO6("h", cl::Hidden,
98   cl::desc("Compatibility option: ignored"));
99
100
101 /// This is just for convenience so it doesn't have to be passed around
102 /// everywhere.
103 static std::string progname;
104
105 /// PrintAndReturn - Prints a message to standard error and returns true.
106 ///
107 /// Inputs:
108 ///  progname - The name of the program (i.e. argv[0]).
109 ///  Message  - The message to print to standard error.
110 ///
111 static int PrintAndReturn(const std::string &Message) {
112   std::cerr << progname << ": " << Message << "\n";
113   return 1;
114 }
115
116 /// CopyEnv - This function takes an array of environment variables and makes a
117 /// copy of it.  This copy can then be manipulated any way the caller likes
118 /// without affecting the process's real environment.
119 ///
120 /// Inputs:
121 ///  envp - An array of C strings containing an environment.
122 ///
123 /// Return value:
124 ///  NULL - An error occurred.
125 ///
126 ///  Otherwise, a pointer to a new array of C strings is returned.  Every string
127 ///  in the array is a duplicate of the one in the original array (i.e. we do
128 ///  not copy the char *'s from one array to another).
129 ///
130 static char ** CopyEnv(char ** const envp) {
131   // Count the number of entries in the old list;
132   unsigned entries;   // The number of entries in the old environment list
133   for (entries = 0; envp[entries] != NULL; entries++)
134     /*empty*/;
135
136   // Add one more entry for the NULL pointer that ends the list.
137   ++entries;
138
139   // If there are no entries at all, just return NULL.
140   if (entries == 0)
141     return NULL;
142
143   // Allocate a new environment list.
144   char **newenv = new char* [entries];
145   if ((newenv = new char* [entries]) == NULL)
146     return NULL;
147
148   // Make a copy of the list.  Don't forget the NULL that ends the list.
149   entries = 0;
150   while (envp[entries] != NULL) {
151     newenv[entries] = new char[strlen (envp[entries]) + 1];
152     strcpy (newenv[entries], envp[entries]);
153     ++entries;
154   }
155   newenv[entries] = NULL;
156
157   return newenv;
158 }
159
160
161 /// RemoveEnv - Remove the specified environment variable from the environment
162 /// array.
163 ///
164 /// Inputs:
165 ///  name - The name of the variable to remove.  It cannot be NULL.
166 ///  envp - The array of environment variables.  It cannot be NULL.
167 ///
168 /// Notes:
169 ///  This is mainly done because functions to remove items from the environment
170 ///  are not available across all platforms.  In particular, Solaris does not
171 ///  seem to have an unsetenv() function or a setenv() function (or they are
172 ///  undocumented if they do exist).
173 ///
174 static void RemoveEnv(const char * name, char ** const envp) {
175   for (unsigned index=0; envp[index] != NULL; index++) {
176     // Find the first equals sign in the array and make it an EOS character.
177     char *p = strchr (envp[index], '=');
178     if (p == NULL)
179       continue;
180     else
181       *p = '\0';
182
183     // Compare the two strings.  If they are equal, zap this string.
184     // Otherwise, restore it.
185     if (!strcmp(name, envp[index]))
186       *envp[index] = '\0';
187     else
188       *p = '=';
189   }
190
191   return;
192 }
193
194 /// GenerateBytecode - generates a bytecode file from the module provided
195 void GenerateBytecode(Module* M, const std::string& FileName) {
196
197   // Create the output file.
198   std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
199                                std::ios::binary;
200   std::ofstream Out(FileName.c_str(), io_mode);
201   if (!Out.good()) {
202     PrintAndReturn("error opening '" + FileName + "' for writing!");
203     return;
204   }
205
206   // Ensure that the bytecode file gets removed from the disk if we get a
207   // terminating signal.
208   sys::RemoveFileOnSignal(sys::Path(FileName));
209
210   // Write it out
211   WriteBytecodeToFile(M, Out, !DisableCompression);
212
213   // Close the bytecode file.
214   Out.close();
215 }
216
217 /// GenerateAssembly - generates a native assembly language source file from the
218 /// specified bytecode file.
219 ///
220 /// Inputs:
221 ///  InputFilename  - The name of the input bytecode file.
222 ///  OutputFilename - The name of the file to generate.
223 ///  llc            - The pathname to use for LLC.
224 ///  envp           - The environment to use when running LLC.
225 ///
226 /// Return non-zero value on error.
227 ///
228 static int GenerateAssembly(const std::string &OutputFilename,
229                             const std::string &InputFilename,
230                             const sys::Path &llc) {
231   // Run LLC to convert the bytecode file into assembly code.
232   std::vector<const char*> args;
233   args.push_back(llc.c_str());
234   args.push_back("-f");
235   args.push_back("-o");
236   args.push_back(OutputFilename.c_str());
237   args.push_back(InputFilename.c_str());
238   args.push_back(0);
239
240   return sys::Program::ExecuteAndWait(llc,&args[0]);
241 }
242
243 /// GenerateCFile - generates a C source file from the specified bytecode file.
244 static int GenerateCFile(const std::string &OutputFile,
245                          const std::string &InputFile,
246                          const sys::Path &llc) {
247   // Run LLC to convert the bytecode file into C.
248   std::vector<const char*> args;
249   args.push_back(llc.c_str());
250   args.push_back("-march=c");
251   args.push_back("-f");
252   args.push_back("-o");
253   args.push_back(OutputFile.c_str());
254   args.push_back(InputFile.c_str());
255   args.push_back(0);
256   return sys::Program::ExecuteAndWait(llc, &args[0]);
257 }
258
259 /// GenerateNative - generates a native object file from the
260 /// specified bytecode file.
261 ///
262 /// Inputs:
263 ///  InputFilename  - The name of the input bytecode file.
264 ///  OutputFilename - The name of the file to generate.
265 ///  Libraries      - The list of libraries with which to link.
266 ///  LibPaths       - The list of directories in which to find libraries.
267 ///  gcc            - The pathname to use for GGC.
268 ///  envp           - A copy of the process's current environment.
269 ///
270 /// Outputs:
271 ///  None.
272 ///
273 /// Returns non-zero value on error.
274 ///
275 static int GenerateNative(const std::string &OutputFilename,
276                           const std::string &InputFilename,
277                           const std::vector<std::string> &Libraries,
278                           const sys::Path &gcc, char ** const envp) {
279   // Remove these environment variables from the environment of the
280   // programs that we will execute.  It appears that GCC sets these
281   // environment variables so that the programs it uses can configure
282   // themselves identically.
283   //
284   // However, when we invoke GCC below, we want it to use its normal
285   // configuration.  Hence, we must sanitize its environment.
286   char ** clean_env = CopyEnv(envp);
287   if (clean_env == NULL)
288     return 1;
289   RemoveEnv("LIBRARY_PATH", clean_env);
290   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
291   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
292   RemoveEnv("COMPILER_PATH", clean_env);
293   RemoveEnv("COLLECT_GCC", clean_env);
294
295
296   // Run GCC to assemble and link the program into native code.
297   //
298   // Note:
299   //  We can't just assemble and link the file with the system assembler
300   //  and linker because we don't know where to put the _start symbol.
301   //  GCC mysteriously knows how to do it.
302   std::vector<const char*> args;
303   args.push_back(gcc.c_str());
304   args.push_back("-fno-strict-aliasing");
305   args.push_back("-O3");
306   args.push_back("-o");
307   args.push_back(OutputFilename.c_str());
308   args.push_back(InputFilename.c_str());
309
310   // Add in the library paths
311   for (unsigned index = 0; index < LibPaths.size(); index++) {
312     args.push_back("-L");
313     args.push_back(LibPaths[index].c_str());
314   }
315
316   // Add the requested options
317   for (unsigned index = 0; index < XLinker.size(); index++) {
318     args.push_back(XLinker[index].c_str());
319     args.push_back(Libraries[index].c_str());
320   }
321
322   // Add in the libraries to link.
323   for (unsigned index = 0; index < Libraries.size(); index++)
324     if (Libraries[index] != "crtend") {
325       args.push_back("-l");
326       args.push_back(Libraries[index].c_str());
327     }
328
329   args.push_back(0);
330
331   // Run the compiler to assembly and link together the program.
332   int R = sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
333   delete [] clean_env;
334   return R;
335 }
336
337 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
338 /// bytecode file for the program.
339 static void EmitShellScript(char **argv) {
340 #if defined(_WIN32) || defined(__CYGWIN__)
341   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
342   // support windows systems, we copy the llvm-stub.exe executable from the
343   // build tree to the destination file.
344   sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
345   if (llvmstub.isEmpty()) {
346     std::cerr << "Could not find llvm-stub.exe executable!\n";
347     exit(1);
348   }
349   sys::CopyFile(sys::Path(OutputFilename), llvmstub);
350   return;
351 #endif
352
353   // Output the script to start the program...
354   std::ofstream Out2(OutputFilename.c_str());
355   if (!Out2.good())
356     exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
357
358   Out2 << "#!/bin/sh\n";
359   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
360   Out2 << "lli=${LLVMINTERP-lli}\n";
361   Out2 << "exec $lli \\\n";
362   // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
363   LibPaths.push_back("/lib");
364   LibPaths.push_back("/usr/lib");
365   LibPaths.push_back("/usr/X11R6/lib");
366   // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
367   // shared object at all! See RH 8: plain text.
368   std::vector<std::string>::iterator libc =
369     std::find(Libraries.begin(), Libraries.end(), "c");
370   if (libc != Libraries.end()) Libraries.erase(libc);
371   // List all the shared object (native) libraries this executable will need
372   // on the command line, so that we don't have to do this manually!
373   for (std::vector<std::string>::iterator i = Libraries.begin(),
374          e = Libraries.end(); i != e; ++i) {
375     sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
376     if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
377       Out2 << "    -load=" << FullLibraryPath.toString() << " \\\n";
378   }
379   Out2 << "    $0.bc ${1+\"$@\"}\n";
380   Out2.close();
381 }
382
383 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
384 // linker function by combining the Files and Libraries in the order they were
385 // declared on the command line.
386 static void BuildLinkItems(
387   Linker::ItemList& Items,
388   const cl::list<std::string>& Files,
389   const cl::list<std::string>& Libraries) {
390
391   // Build the list of linkage items for LinkItems.
392
393   cl::list<std::string>::const_iterator fileIt = Files.begin();
394   cl::list<std::string>::const_iterator libIt  = Libraries.begin();
395
396   int libPos = -1, filePos = -1;
397   while ( libIt != Libraries.end() || fileIt != Files.end() ) {
398     if (libIt != Libraries.end())
399       libPos = Libraries.getPosition(libIt - Libraries.begin());
400     else
401       libPos = -1;
402     if (fileIt != Files.end())
403       filePos = Files.getPosition(fileIt - Files.begin());
404     else
405       filePos = -1;
406
407     if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
408       // Add a source file
409       Items.push_back(std::make_pair(*fileIt++, false));
410     } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
411       // Add a library
412       Items.push_back(std::make_pair(*libIt++, true));
413     }
414   }
415 }
416
417 // Rightly this should go in a header file but it just seems such a waste.
418 namespace llvm {
419 extern void Optimize(Module*);
420 }
421
422 int main(int argc, char **argv, char **envp) {
423   try {
424     // Initial global variable above for convenience printing of program name.
425     progname = sys::Path(argv[0]).getBasename();
426     Linker TheLinker(progname, OutputFilename, Verbose);
427
428     // Parse the command line options
429     cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
430     sys::PrintStackTraceOnErrorSignal();
431
432     // Set up the library paths for the Linker
433     TheLinker.addPaths(LibPaths);
434     TheLinker.addSystemPaths();
435
436     // Remove any consecutive duplicates of the same library...
437     Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
438                     Libraries.end());
439
440     if (LinkAsLibrary) {
441       std::vector<sys::Path> Files;
442       for (unsigned i = 0; i < InputFilenames.size(); ++i )
443         Files.push_back(sys::Path(InputFilenames[i]));
444       if (TheLinker.LinkInFiles(Files))
445         return 1; // Error already printed
446
447       // The libraries aren't linked in but are noted as "dependent" in the
448       // module.
449       for (cl::list<std::string>::const_iterator I = Libraries.begin(),
450            E = Libraries.end(); I != E ; ++I) {
451         TheLinker.getModule()->addLibrary(*I);
452       }
453     } else {
454       // Build a list of the items from our command line
455       Linker::ItemList Items;
456       Linker::ItemList NativeItems;
457       BuildLinkItems(Items, InputFilenames, Libraries);
458
459       // Link all the items together
460       if (TheLinker.LinkInItems(Items,NativeItems) )
461         return 1;
462     }
463
464     std::auto_ptr<Module> Composite(TheLinker.releaseModule());
465
466     // Optimize the module
467     Optimize(Composite.get());
468
469     // Generate the bytecode for the optimized module.
470     std::string RealBytecodeOutput = OutputFilename;
471     if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
472     GenerateBytecode(Composite.get(), RealBytecodeOutput);
473
474     // If we are not linking a library, generate either a native executable
475     // or a JIT shell script, depending upon what the user wants.
476     if (!LinkAsLibrary) {
477       // If the user wants to run a post-link optimization, run it now.
478       if (!PostLinkOpts.empty()) {
479         std::vector<std::string> opts = PostLinkOpts;
480         for (std::vector<std::string>::iterator I = opts.begin(),
481              E = opts.end(); I != E; ++I) {
482           sys::Path prog(*I);
483           if (!prog.canExecute()) {
484             prog = sys::Program::FindProgramByName(*I);
485             if (prog.isEmpty())
486               return PrintAndReturn(std::string("Optimization program '") + *I +
487                 "' is not found or not executable.");
488           }
489           // Get the program arguments
490           sys::Path tmp_output("opt_result");
491           if (!tmp_output.createTemporaryFileOnDisk()) {
492             return PrintAndReturn(
493               "Can't create temporary file for post-link optimization");
494           }
495           const char* args[4];
496           args[0] = I->c_str();
497           args[1] = RealBytecodeOutput.c_str();
498           args[2] = tmp_output.c_str();
499           args[3] = 0;
500           if (0 == sys::Program::ExecuteAndWait(prog, args)) {
501             if (tmp_output.isBytecodeFile()) {
502               sys::Path target(RealBytecodeOutput);
503               target.eraseFromDisk();
504               tmp_output.renamePathOnDisk(target);
505             } else
506               return PrintAndReturn(
507                 "Post-link optimization output is not bytecode");
508           }
509         }
510       }
511
512       // If the user wants to generate a native executable, compile it from the
513       // bytecode file.
514       //
515       // Otherwise, create a script that will run the bytecode through the JIT.
516       if (Native) {
517         // Name of the Assembly Language output file
518         sys::Path AssemblyFile ( OutputFilename);
519         AssemblyFile.appendSuffix("s");
520
521         // Mark the output files for removal if we get an interrupt.
522         sys::RemoveFileOnSignal(AssemblyFile);
523         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
524
525         // Determine the locations of the llc and gcc programs.
526         sys::Path llc = FindExecutable("llc", argv[0]);
527         if (llc.isEmpty())
528           return PrintAndReturn("Failed to find llc");
529
530         sys::Path gcc = FindExecutable("gcc", argv[0]);
531         if (gcc.isEmpty())
532           return PrintAndReturn("Failed to find gcc");
533
534         // Generate an assembly language file for the bytecode.
535         if (Verbose) std::cout << "Generating Assembly Code\n";
536         GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
537         if (Verbose) std::cout << "Generating Native Code\n";
538         GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
539                        gcc, envp);
540
541         // Remove the assembly language file.
542         AssemblyFile.eraseFromDisk();
543       } else if (NativeCBE) {
544         sys::Path CFile (OutputFilename);
545         CFile.appendSuffix("cbe.c");
546
547         // Mark the output files for removal if we get an interrupt.
548         sys::RemoveFileOnSignal(CFile);
549         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
550
551         // Determine the locations of the llc and gcc programs.
552         sys::Path llc = FindExecutable("llc", argv[0]);
553         if (llc.isEmpty())
554           return PrintAndReturn("Failed to find llc");
555
556         sys::Path gcc = FindExecutable("gcc", argv[0]);
557         if (gcc.isEmpty())
558           return PrintAndReturn("Failed to find gcc");
559
560         // Generate an assembly language file for the bytecode.
561         if (Verbose) std::cout << "Generating Assembly Code\n";
562         GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
563         if (Verbose) std::cout << "Generating Native Code\n";
564         GenerateNative(OutputFilename, CFile.toString(), Libraries, gcc, envp);
565
566         // Remove the assembly language file.
567         CFile.eraseFromDisk();
568
569       } else {
570         EmitShellScript(argv);
571       }
572
573       // Make the script executable...
574       sys::Path(OutputFilename).makeExecutableOnDisk();
575
576       // Make the bytecode file readable and directly executable in LLEE as well
577       sys::Path(RealBytecodeOutput).makeExecutableOnDisk();
578       sys::Path(RealBytecodeOutput).makeReadableOnDisk();
579     }
580
581     return 0;
582   } catch (const std::string& msg) {
583     std::cerr << argv[0] << ": " << msg << "\n";
584   } catch (...) {
585     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
586   }
587   return 1;
588 }