When -link-as-library, add -l options to Module's deplibs
[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/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"
35 #include <fstream>
36 #include <iostream>
37 #include <memory>
38
39 using namespace llvm;
40
41 // Input/Output Options
42 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
43   cl::desc("<input bytecode files>"));
44
45 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
46   cl::desc("Override output filename"), 
47   cl::value_desc("filename"));
48
49 static cl::opt<bool> Verbose("v", 
50   cl::desc("Print information about actions taken"));
51   
52 static cl::list<std::string> LibPaths("L", cl::Prefix,
53   cl::desc("Specify a library search path"), 
54   cl::value_desc("directory"));
55
56 static cl::list<std::string> Libraries("l", cl::Prefix,
57   cl::desc("Specify libraries to link to"), 
58   cl::value_desc("library prefix"));
59
60 static cl::opt<bool> LinkAsLibrary("link-as-library", 
61   cl::desc("Link the .bc files together as a library, not an executable"));
62
63 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
64   cl::desc("Alias for -link-as-library"));
65
66 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
67   MachineArch("march", cl::desc("Architecture to generate assembly for:"));
68
69 static cl::opt<bool> Native("native",
70   cl::desc("Generate a native binary instead of a shell script"));
71
72 static cl::opt<bool>NativeCBE("native-cbe",
73   cl::desc("Generate a native binary with the C backend and GCC"));
74
75 static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
76   cl::desc("Disable writing of compressed bytecode files"));
77   
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"));
81
82 static cl::opt<std::string> CO4("version-script", cl::Hidden, 
83   cl::desc("Compatibility option: ignored"));
84
85 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden, 
86   cl::desc("Compatibility option: ignored"));
87
88 static  cl::opt<std::string> CO6("h", cl::Hidden, 
89   cl::desc("Compatibility option: ignored"));
90
91 /// This is just for convenience so it doesn't have to be passed around
92 /// everywhere.
93 static const char* progname = 0;
94
95 /// PrintAndReturn - Prints a message to standard error and returns true.
96 ///
97 /// Inputs:
98 ///  progname - The name of the program (i.e. argv[0]).
99 ///  Message  - The message to print to standard error.
100 ///
101 static int PrintAndReturn(const std::string &Message) {
102   std::cerr << progname << ": " << Message << "\n";
103   return 1;
104 }
105
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.
109 ///
110 /// Inputs:
111 ///  envp - An array of C strings containing an environment.
112 ///
113 /// Return value:
114 ///  NULL - An error occurred.
115 ///
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).
119 ///
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++)
124     /*empty*/;
125
126   // Add one more entry for the NULL pointer that ends the list.
127   ++entries;
128
129   // If there are no entries at all, just return NULL.
130   if (entries == 0)
131     return NULL;
132
133   // Allocate a new environment list.
134   char **newenv = new char* [entries];
135   if ((newenv = new char* [entries]) == NULL)
136     return NULL;
137
138   // Make a copy of the list.  Don't forget the NULL that ends the list.
139   entries = 0;
140   while (envp[entries] != NULL) {
141     newenv[entries] = new char[strlen (envp[entries]) + 1];
142     strcpy (newenv[entries], envp[entries]);
143     ++entries;
144   }
145   newenv[entries] = NULL;
146
147   return newenv;
148 }
149
150
151 /// RemoveEnv - Remove the specified environment variable from the environment
152 /// array.
153 ///
154 /// Inputs:
155 ///  name - The name of the variable to remove.  It cannot be NULL.
156 ///  envp - The array of environment variables.  It cannot be NULL.
157 ///
158 /// Notes:
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).
163 ///
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], '=');
168     if (p == NULL)
169       continue;
170     else
171       *p = '\0';
172
173     // Compare the two strings.  If they are equal, zap this string.
174     // Otherwise, restore it.
175     if (!strcmp(name, envp[index]))
176       *envp[index] = '\0';
177     else
178       *p = '=';
179   }
180
181   return;
182 }
183
184 /// GenerateBytecode - generates a bytecode file from the module provided
185 void GenerateBytecode(Module* M, const std::string& FileName) {
186
187   // Create the output file.
188   std::ofstream Out(FileName.c_str());
189   if (!Out.good()) {
190     PrintAndReturn("error opening '" + FileName + "' for writing!");
191     return;
192   }
193
194   // Ensure that the bytecode file gets removed from the disk if we get a
195   // terminating signal.
196   sys::RemoveFileOnSignal(sys::Path(FileName));
197
198   // Write it out
199   WriteBytecodeToFile(M, Out, !DisableCompression);
200
201   // Close the bytecode file.
202   Out.close();
203 }
204
205 /// GenerateAssembly - generates a native assembly language source file from the
206 /// specified bytecode file.
207 ///
208 /// Inputs:
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.
213 ///
214 /// Return non-zero value on error.
215 ///
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.
221   const char *cmd[6];
222   cmd[0] = llc.c_str();
223   cmd[1] = "-f";
224   cmd[2] = "-o";
225   cmd[3] = OutputFilename.c_str();
226   cmd[4] = InputFilename.c_str();
227   cmd[5] = 0;
228
229   return ExecWait(cmd, envp);
230 }
231
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.
238   const char *cmd[7];
239
240   cmd[0] = llc.c_str();
241   cmd[1] = "-march=c";
242   cmd[2] = "-f";
243   cmd[3] = "-o";
244   cmd[4] = OutputFile.c_str();
245   cmd[5] = InputFile.c_str();
246   cmd[6] = 0;
247   return ExecWait(cmd, envp);
248 }
249
250 /// GenerateNative - generates a native assembly language source file from the
251 /// specified assembly source file.
252 ///
253 /// Inputs:
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.
260 ///
261 /// Outputs:
262 ///  None.
263 ///
264 /// Returns non-zero value on error.
265 ///
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.
275   //
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)
280     return 1;
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);
286
287   std::vector<const char *> cmd;
288
289   // Run GCC to assemble and link the program into native code.
290   //
291   // Note:
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");
298   cmd.push_back("-o");
299   cmd.push_back(OutputFilename.c_str());
300   cmd.push_back(InputFilename.c_str());
301
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
307   // program.
308 #if 0
309   // Add in the library path options.
310   for (unsigned index=0; index < LibPaths.size(); index++) {
311     cmd.push_back("-L");
312     cmd.push_back(LibPaths[index].c_str());
313   }
314 #endif
315
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());
322     }
323   }
324   cmd.push_back(NULL);
325
326   // Run the compiler to assembly and link together the program.
327   return ExecWait(&(cmd[0]), clean_env);
328 }
329
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";
340     exit(1);
341   }
342   if (CopyFile(OutputFilename, llvmstub)) {
343     std::cerr << "Could not copy the llvm-stub.exe executable!\n";
344     exit(1);
345   }
346   return;
347 #endif
348
349   // Output the script to start the program...
350   std::ofstream Out2(OutputFilename.c_str());
351   if (!Out2.good())
352     exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
353
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     std::string FullLibraryPath = FindLib(*i, LibPaths, true);
372     if (!FullLibraryPath.empty() && IsSharedObject(FullLibraryPath))
373       Out2 << "    -load=" << FullLibraryPath << " \\\n";
374   }
375   Out2 << "    $0.bc ${1+\"$@\"}\n";
376   Out2.close();
377 }
378
379 // Rightly this should go in a header file but it just seems such a waste.
380 namespace llvm {
381 extern void Optimize(Module*);
382 }
383
384 int main(int argc, char **argv, char **envp) {
385   // Initial global variable above for convenience printing of program name.
386   progname = argv[0];
387
388   // Parse the command line options
389   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
390   sys::PrintStackTraceOnErrorSignal();
391
392   // Remove any consecutive duplicates of the same library...
393   Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
394                   Libraries.end());
395
396   // Set up the Composite module.
397   std::auto_ptr<Module> Composite(0);
398
399   if (LinkAsLibrary) {
400     // Link in only the files.
401     Composite.reset( new Module(argv[0]) );
402     if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
403       return 1; // Error already printed
404
405     // The libraries aren't linked in but are noted as "dependent" in the
406     // module.
407     for (cl::list<std::string>::const_iterator I = Libraries.begin(), 
408          E = Libraries.end(); I != E ; ++I) {
409       Composite.get()->addLibrary(*I);
410     }
411   } else {
412     // Build a list of the items from our command line
413     LinkItemList Items;
414     BuildLinkItems(Items, InputFilenames, Libraries);
415
416     // Link all the items together
417     Composite.reset( LinkItems(argv[0], Items, LibPaths, Verbose, Native) );
418
419     // Check for an error during linker
420     if (!Composite.get())
421       return 1; // Error already printed
422   }
423
424   // Optimize the module
425   Optimize(Composite.get());
426
427   // Generate the bytecode for the optimized module.
428   std::string RealBytecodeOutput = OutputFilename;
429   if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
430   GenerateBytecode(Composite.get(), RealBytecodeOutput);
431
432   // If we are not linking a library, generate either a native executable
433   // or a JIT shell script, depending upon what the user wants.
434   if (!LinkAsLibrary) {
435     // If the user wants to generate a native executable, compile it from the
436     // bytecode file.
437     //
438     // Otherwise, create a script that will run the bytecode through the JIT.
439     if (Native) {
440       // Name of the Assembly Language output file
441       std::string AssemblyFile = OutputFilename + ".s";
442
443       // Mark the output files for removal if we get an interrupt.
444       sys::RemoveFileOnSignal(sys::Path(AssemblyFile));
445       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
446
447       // Determine the locations of the llc and gcc programs.
448       std::string llc = FindExecutable("llc", argv[0]);
449       std::string gcc = FindExecutable("gcc", argv[0]);
450       if (llc.empty())
451         return PrintAndReturn("Failed to find llc");
452
453       if (gcc.empty())
454         return PrintAndReturn("Failed to find gcc");
455
456       // Generate an assembly language file for the bytecode.
457       if (Verbose) std::cout << "Generating Assembly Code\n";
458       GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
459       if (Verbose) std::cout << "Generating Native Code\n";
460       GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
461                      gcc, envp);
462
463       // Remove the assembly language file.
464       removeFile (AssemblyFile);
465     } else if (NativeCBE) {
466       std::string CFile = OutputFilename + ".cbe.c";
467
468       // Mark the output files for removal if we get an interrupt.
469       sys::RemoveFileOnSignal(sys::Path(CFile));
470       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
471
472       // Determine the locations of the llc and gcc programs.
473       std::string llc = FindExecutable("llc", argv[0]);
474       std::string gcc = FindExecutable("gcc", argv[0]);
475       if (llc.empty())
476         return PrintAndReturn("Failed to find llc");
477       if (gcc.empty())
478         return PrintAndReturn("Failed to find gcc");
479
480       // Generate an assembly language file for the bytecode.
481       if (Verbose) std::cout << "Generating Assembly Code\n";
482       GenerateCFile(CFile, RealBytecodeOutput, llc, envp);
483       if (Verbose) std::cout << "Generating Native Code\n";
484       GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp);
485
486       // Remove the assembly language file.
487       removeFile(CFile);
488
489     } else {
490       EmitShellScript(argv);
491     }
492   
493     // Make the script executable...
494     MakeFileExecutable(OutputFilename);
495
496     // Make the bytecode file readable and directly executable in LLEE as well
497     MakeFileExecutable(RealBytecodeOutput);
498     MakeFileReadable(RealBytecodeOutput);
499   }
500
501   return 0;
502 }