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