For PR1187:
[oota-llvm.git] / tools / gccld / gccld.cpp
1 //===- gccld.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 "gccld.h"
24 #include "llvm/Linker.h"
25 #include "llvm/Module.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Bytecode/Reader.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/Streams.h"
36 #include "llvm/System/Signals.h"
37 #include "llvm/Support/SystemUtils.h"
38 #include <fstream>
39 #include <memory>
40 using namespace llvm;
41
42 namespace {
43   cl::list<std::string>
44   InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
45                  cl::OneOrMore);
46
47   cl::opt<std::string>
48   OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
49                  cl::value_desc("filename"));
50
51   cl::opt<bool>
52   Verbose("v", cl::desc("Print information about actions taken"));
53
54   cl::list<std::string>
55   LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
56            cl::value_desc("directory"));
57
58   cl::list<std::string>
59   Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
60             cl::value_desc("library prefix"));
61
62   cl::opt<bool>
63   Strip("strip-all", cl::desc("Strip all symbol info from executable"));
64   cl::opt<bool>
65   StripDebug("strip-debug",
66              cl::desc("Strip debugger symbol info from executable"));
67
68   cl::opt<bool>
69   NoInternalize("disable-internalize",
70                 cl::desc("Do not mark all symbols as internal"));
71   cl::alias
72   ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
73                 cl::aliasopt(NoInternalize));
74
75   cl::opt<bool>
76   LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
77                                             " library, not an executable"));
78   cl::alias
79   Relink("r", cl::desc("Alias for -link-as-library"),
80          cl::aliasopt(LinkAsLibrary));
81
82   cl::opt<bool>
83   Native("native", cl::ZeroOrMore,
84          cl::desc("Generate a native binary instead of a shell script"));
85   cl::opt<bool>
86   NativeCBE("native-cbe", cl::ZeroOrMore,
87             cl::desc("Generate a native binary with the C backend and GCC"));
88
89   cl::opt<bool>
90   SaveTemps("save-temps",
91          cl::desc("Do not delete temporary files"));
92
93   cl::list<std::string>
94   RPath("rpath",
95         cl::desc("Set runtime shared library search path (requires -native or"
96                  " -native-cbe)"),
97         cl::Prefix, cl::value_desc("directory"));
98
99   cl::opt<std::string>
100   SOName("soname",
101          cl::desc("Set internal name of shared library (requires -native or"
102                  " -native-cbe)"),
103          cl::Prefix, cl::value_desc("name"));
104
105   // Compatibility options that are ignored but supported by LD
106   cl::opt<std::string>
107   CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
108   cl::opt<bool>
109   CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
110   cl::opt<std::string>
111   CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
112   cl::opt<bool>
113   CO7("start-group", cl::Hidden, cl::desc("Compatibility option: ignored"));
114   cl::opt<bool>
115   CO8("end-group", cl::Hidden, cl::desc("Compatibility option: ignored"));
116
117   cl::alias A0("s", cl::desc("Alias for --strip-all"),
118                cl::aliasopt(Strip));
119   cl::alias A1("S", cl::desc("Alias for --strip-debug"),
120                cl::aliasopt(StripDebug));
121
122 }
123
124 /// PrintAndReturn - Prints a message to standard error and returns true.
125 ///
126 /// Inputs:
127 ///  progname - The name of the program (i.e. argv[0]).
128 ///  Message  - The message to print to standard error.
129 ///
130 static int PrintAndReturn(const char *progname, const std::string &Message) {
131   cerr << progname << ": " << Message << "\n";
132   return 1;
133 }
134
135 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
136 /// bytecode file for the program.
137 static void EmitShellScript(char **argv) {
138 #if defined(_WIN32) || defined(__CYGWIN__)  
139   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
140   // support windows systems, we copy the llvm-stub.exe executable from the
141   // build tree to the destination file.
142   std::string ErrMsg;  
143   sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
144   if (llvmstub.isEmpty()) {
145     cerr << "Could not find llvm-stub.exe executable!\n";
146     exit(1);
147   }
148   if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg)) {
149     cerr << argv[0] << ": " << ErrMsg << "\n";
150     exit(1);    
151   }
152
153   return;  
154 #endif
155
156   // Output the script to start the program...
157   std::ofstream Out2(OutputFilename.c_str());
158   if (!Out2.good())
159     exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
160                                  "' for writing!"));
161
162   Out2 << "#!/bin/sh\n";
163   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
164   Out2 << "lli=${LLVMINTERP-lli}\n";
165   Out2 << "exec $lli \\\n";
166
167   // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
168   // shared object at all! See RH 8: plain text.
169   std::vector<std::string>::iterator libc =
170     std::find(Libraries.begin(), Libraries.end(), "c");
171   if (libc != Libraries.end()) Libraries.erase(libc);
172   // List all the shared object (native) libraries this executable will need
173   // on the command line, so that we don't have to do this manually!
174   for (std::vector<std::string>::iterator i = Libraries.begin(),
175          e = Libraries.end(); i != e; ++i) {
176     sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
177     if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
178       Out2 << "    -load=" << FullLibraryPath.toString() << " \\\n";
179   }
180   Out2 << "    $0.bc ${1+\"$@\"}\n";
181   Out2.close();
182 }
183
184 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
185 // linker function by combining the Files and Libraries in the order they were
186 // declared on the command line.
187 static void BuildLinkItems(
188   Linker::ItemList& Items,
189   const cl::list<std::string>& Files,
190   const cl::list<std::string>& Libraries) {
191
192   // Build the list of linkage items for LinkItems.
193
194   cl::list<std::string>::const_iterator fileIt = Files.begin();
195   cl::list<std::string>::const_iterator libIt  = Libraries.begin();
196
197   int libPos = -1, filePos = -1;
198   while ( libIt != Libraries.end() || fileIt != Files.end() ) {
199     if (libIt != Libraries.end())
200       libPos = Libraries.getPosition(libIt - Libraries.begin());
201     else
202       libPos = -1;
203     if (fileIt != Files.end())
204       filePos = Files.getPosition(fileIt - Files.begin());
205     else
206       filePos = -1;
207
208     if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
209       // Add a source file
210       Items.push_back(std::make_pair(*fileIt++, false));
211     } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
212       // Add a library
213       Items.push_back(std::make_pair(*libIt++, true));
214     }
215   }
216 }
217
218 int main(int argc, char **argv, char **envp ) {
219   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
220   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
221   sys::PrintStackTraceOnErrorSignal();
222
223   int exitCode = 0;
224
225   std::string ProgName = sys::Path(argv[0]).getBasename();
226   Linker TheLinker(ProgName, OutputFilename, Verbose);
227
228   try {
229     // Remove any consecutive duplicates of the same library...
230     Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
231                     Libraries.end());
232
233     TheLinker.addPaths(LibPaths);
234     TheLinker.addSystemPaths();
235
236     if (LinkAsLibrary) {
237       std::vector<sys::Path> Files;
238       for (unsigned i = 0; i < InputFilenames.size(); ++i )
239         Files.push_back(sys::Path(InputFilenames[i]));
240
241       if (TheLinker.LinkInFiles(Files))
242         return 1; // Error already printed by linker
243
244       // The libraries aren't linked in but are noted as "dependent" in the
245       // module.
246       for (cl::list<std::string>::const_iterator I = Libraries.begin(),
247            E = Libraries.end(); I != E ; ++I) {
248         TheLinker.getModule()->addLibrary(*I);
249       }
250
251     } else {
252       // Build a list of the items from our command line
253       Linker::ItemList Items;
254       Linker::ItemList NativeItems;
255       BuildLinkItems(Items, InputFilenames, Libraries);
256
257       // Link all the items together
258       if (TheLinker.LinkInItems(Items,NativeItems))
259         return 1; // Error already printed
260
261       // Revise the Libraries based on the remaining (native) libraries that
262       // were not linked in to the bytecode. This ensures that we don't attempt
263       // to pass a bytecode library to the native linker
264       Libraries.clear(); // we've consumed the libraries except for native
265       if ((Native || NativeCBE) && !NativeItems.empty()) {
266         for (Linker::ItemList::const_iterator I = NativeItems.begin(), 
267              E = NativeItems.end(); I != E; ++I) {
268           Libraries.push_back(I->first);
269         }
270       }
271     }
272
273     // We're done with the Linker, so tell it to release its module
274     std::auto_ptr<Module> Composite(TheLinker.releaseModule());
275
276     // Create the output file.
277     std::string RealBytecodeOutput = OutputFilename;
278     if (!LinkAsLibrary || Native || NativeCBE) RealBytecodeOutput += ".bc";
279     std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
280                                  std::ios::binary;
281     std::ofstream Out(RealBytecodeOutput.c_str(), io_mode);
282     if (!Out.good())
283       return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
284                                      "' for writing!");
285
286     // Ensure that the bytecode file gets removed from the disk if we get a
287     // SIGINT signal.
288     sys::RemoveFileOnSignal(sys::Path(RealBytecodeOutput));
289
290     // Strip everything if Strip is set, otherwise if stripdebug is set, just
291     // strip debug info.
292     int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
293
294     // Internalize the module if neither -disable-internalize nor
295     // -link-as-library are passed in.
296     bool ShouldInternalize = !NoInternalize & !LinkAsLibrary;
297
298     // Generate the bytecode file.
299     if (GenerateBytecode(Composite.get(), StripLevel, ShouldInternalize, &Out)){
300       Out.close();
301       return PrintAndReturn(argv[0], "error generating bytecode");
302     }
303
304     // Close the bytecode file.
305     Out.close();
306
307     // Generate either a native file or a JIT shell script.  If the user wants
308     // to generate a native file, compile it from the bytecode file. Otherwise,
309     // if the target is not a library, create a script that will run the
310     // bytecode through the JIT.
311     if (Native) {
312       // Name of the Assembly Language output file
313       sys::Path AssemblyFile (OutputFilename);
314       AssemblyFile.appendSuffix("s");
315
316       // Mark the output files for removal if we get an interrupt.
317       sys::RemoveFileOnSignal(AssemblyFile);
318       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
319
320       // Determine the locations of the llc and gcc programs.
321       sys::Path llc = FindExecutable("llc", argv[0]);
322       if (llc.isEmpty())
323         return PrintAndReturn(argv[0], "Failed to find llc");
324
325       sys::Path gcc = FindExecutable("gcc", argv[0]);
326       if (gcc.isEmpty())
327         return PrintAndReturn(argv[0], "Failed to find gcc");
328
329       // Generate an assembly language file for the bytecode.
330       if (Verbose) cout << "Generating Assembly Code\n";
331       std::string ErrMsg;
332       if (0 != GenerateAssembly(
333           AssemblyFile.toString(), RealBytecodeOutput, llc, ErrMsg, Verbose)) {
334         cerr << argv[0] << ": " << ErrMsg << "\n";
335         return 2;
336       }
337       if (Verbose) cout << "Generating Native Code\n";
338       if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
339                      LibPaths, Libraries, gcc, envp, LinkAsLibrary,
340                      NoInternalize, RPath, SOName, ErrMsg, Verbose) ) {
341         cerr << argv[0] << ": " << ErrMsg << "\n";
342         return 2;
343       }
344
345       if (!SaveTemps) {
346         // Remove the assembly language file.
347         AssemblyFile.eraseFromDisk();
348         // Remove the bytecode language file.
349         sys::Path(RealBytecodeOutput).eraseFromDisk();
350       }
351
352     } else if (NativeCBE) {
353       sys::Path CFile (OutputFilename);
354       CFile.appendSuffix("cbe.c");
355
356       // Mark the output files for removal if we get an interrupt.
357       sys::RemoveFileOnSignal(CFile);
358       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
359
360       // Determine the locations of the llc and gcc programs.
361       sys::Path llc = FindExecutable("llc", argv[0]);
362       if (llc.isEmpty())
363         return PrintAndReturn(argv[0], "Failed to find llc");
364
365       sys::Path gcc = FindExecutable("gcc", argv[0]);
366       if (gcc.isEmpty())
367         return PrintAndReturn(argv[0], "Failed to find gcc");
368
369       // Generate an assembly language file for the bytecode.
370       if (Verbose) cout << "Generating C Source Code\n";
371       std::string ErrMsg;
372       if (0 != GenerateCFile(
373           CFile.toString(), RealBytecodeOutput, llc, ErrMsg, Verbose)) {
374         cerr << argv[0] << ": " << ErrMsg << "\n";
375         return 2;
376       }
377       if (Verbose) cout << "Generating Native Code\n";
378       if (0 != GenerateNative(OutputFilename, CFile.toString(),
379                      LibPaths, Libraries, gcc, envp, LinkAsLibrary,
380                      NoInternalize, RPath, SOName, ErrMsg, Verbose)) {
381         cerr << argv[0] << ": " << ErrMsg << "\n";
382         return 2;
383       }
384
385       if (!SaveTemps) {
386         // Remove the assembly language file.
387         CFile.eraseFromDisk();
388         // Remove the bytecode language file.
389         sys::Path(RealBytecodeOutput).eraseFromDisk();
390       }
391
392     } else if (!LinkAsLibrary) {
393       EmitShellScript(argv);
394
395       // Make the bytecode file readable and directly executable in LLEE
396       std::string ErrMsg;
397       if (sys::Path(RealBytecodeOutput).makeExecutableOnDisk(&ErrMsg)) {
398         cerr << argv[0] << ": " << ErrMsg << "\n";
399         return 1;
400       }
401       if (sys::Path(RealBytecodeOutput).makeReadableOnDisk(&ErrMsg)) {
402         cerr << argv[0] << ": " << ErrMsg << "\n";
403         return 1;
404       }
405     }
406
407     // Make the output, whether native or script, executable as well...
408     std::string ErrMsg;
409     if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg)) {
410       cerr << argv[0] << ": " << ErrMsg << "\n";
411       return 1;
412     }
413   } catch (const char*msg) {
414     cerr << argv[0] << ": " << msg << "\n";
415     exitCode = 1;
416   } catch (const std::string& msg) {
417     cerr << argv[0] << ": " << msg << "\n";
418     exitCode = 2;
419   } catch (...) {
420     // This really shouldn't happen, but just in case ....
421     cerr << argv[0] << ": An unexpected unknown exception occurred.\n";
422     exitCode = 3;
423   }
424   
425   llvm_shutdown();
426   return exitCode;
427 }