Fix PR139:\
[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/System/Signals.h"
35 #include "llvm/Support/SystemUtils.h"
36 #include <fstream>
37 #include <memory>
38 using namespace llvm;
39
40 namespace {
41   cl::list<std::string> 
42   InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
43                  cl::OneOrMore);
44
45   cl::opt<std::string> 
46   OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
47                  cl::value_desc("filename"));
48
49   cl::opt<bool>    
50   Verbose("v", cl::desc("Print information about actions taken"));
51   
52   cl::list<std::string> 
53   LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
54            cl::value_desc("directory"));
55
56   cl::list<std::string> 
57   Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
58             cl::value_desc("library prefix"));
59
60   cl::opt<bool>
61   Strip("strip-all", cl::desc("Strip all symbol info from executable"));
62   cl::opt<bool>
63   StripDebug("strip-debug",
64              cl::desc("Strip debugger symbol info from executable"));
65
66   cl::opt<bool>
67   NoInternalize("disable-internalize",
68                 cl::desc("Do not mark all symbols as internal"));
69   cl::alias
70   ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
71                 cl::aliasopt(NoInternalize));
72
73   cl::opt<bool>
74   LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
75                                             " library, not an executable"));
76   cl::alias
77   Relink("r", cl::desc("Alias for -link-as-library"),
78          cl::aliasopt(LinkAsLibrary));
79
80   cl::opt<bool>    
81   Native("native",
82          cl::desc("Generate a native binary instead of a shell script"));
83   cl::opt<bool>    
84   NativeCBE("native-cbe",
85             cl::desc("Generate a native binary with the C backend and GCC"));
86   
87   // Compatibility options that are ignored but supported by LD
88   cl::opt<std::string>
89   CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
90   cl::opt<std::string>
91   CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
92   cl::opt<bool>
93   CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
94   cl::opt<std::string>
95   CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
96
97   cl::alias A0("s", cl::desc("Alias for --strip-all"),
98                cl::aliasopt(Strip));
99   cl::alias A1("S", cl::desc("Alias for --strip-debug"),
100                cl::aliasopt(StripDebug));
101 }
102
103 /// PrintAndReturn - Prints a message to standard error and returns true.
104 ///
105 /// Inputs:
106 ///  progname - The name of the program (i.e. argv[0]).
107 ///  Message  - The message to print to standard error.
108 ///
109 static int PrintAndReturn(const char *progname, const std::string &Message) {
110   std::cerr << progname << ": " << Message << "\n";
111   return 1;
112 }
113
114 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
115 /// bytecode file for the program.
116 static void EmitShellScript(char **argv) {
117 #if defined(_WIN32) || defined(__CYGWIN__)
118   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
119   // support windows systems, we copy the llvm-stub.exe executable from the
120   // build tree to the destination file.
121   std::string llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
122   if (llvmstub.empty()) {
123     std::cerr << "Could not find llvm-stub.exe executable!\n";
124     exit(1);
125   }
126   if (CopyFile(OutputFilename, llvmstub)) {
127     std::cerr << "Could not copy the llvm-stub.exe executable!\n";
128     exit(1);
129   }
130   return;
131 #endif
132
133   // Output the script to start the program...
134   std::ofstream Out2(OutputFilename.c_str());
135   if (!Out2.good())
136     exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
137                                  "' for writing!"));
138
139   Out2 << "#!/bin/sh\n";
140   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
141   Out2 << "lli=${LLVMINTERP-lli}\n";
142   Out2 << "exec $lli \\\n";
143   // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
144   LibPaths.push_back("/lib");
145   LibPaths.push_back("/usr/lib");
146   LibPaths.push_back("/usr/X11R6/lib");
147   // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
148   // shared object at all! See RH 8: plain text.
149   std::vector<std::string>::iterator libc = 
150     std::find(Libraries.begin(), Libraries.end(), "c");
151   if (libc != Libraries.end()) Libraries.erase(libc);
152   // List all the shared object (native) libraries this executable will need
153   // on the command line, so that we don't have to do this manually!
154   for (std::vector<std::string>::iterator i = Libraries.begin(), 
155          e = Libraries.end(); i != e; ++i) {
156     std::string FullLibraryPath = FindLib(*i, LibPaths, true);
157     if (!FullLibraryPath.empty() && IsSharedObject(FullLibraryPath))
158       Out2 << "    -load=" << FullLibraryPath << " \\\n";
159   }
160   Out2 << "    $0.bc ${1+\"$@\"}\n";
161   Out2.close();
162 }
163
164 int main(int argc, char **argv, char **envp) {
165   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
166   sys::PrintStackTraceOnErrorSignal();
167
168   int exitCode = 0;
169
170   try {
171     // Remove any consecutive duplicates of the same library...
172     Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
173                     Libraries.end());
174
175     // Set up the Composite module.
176     std::auto_ptr<Module> Composite(0);
177
178     if (LinkAsLibrary) {
179       // Link in only the files, we ignore libraries in this case.
180       Composite.reset( new Module(argv[0]) );
181       if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
182         return 1; // Error already printed
183     } else {
184       // Build a list of the items from our command line
185       LinkItemList Items;
186       BuildLinkItems(Items, InputFilenames, Libraries);
187
188       // Link all the items together
189       Composite.reset( LinkItems(argv[0], Items, LibPaths, Verbose, Native) );
190
191       // Check for an error during linker
192       if (!Composite.get())
193         return 1; // Error already printed
194     }
195
196     // Create the output file.
197     std::string RealBytecodeOutput = OutputFilename;
198     if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
199     std::ofstream Out(RealBytecodeOutput.c_str());
200     if (!Out.good())
201       return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
202                                      "' for writing!");
203
204     // Ensure that the bytecode file gets removed from the disk if we get a
205     // SIGINT signal.
206     sys::RemoveFileOnSignal(sys::Path(RealBytecodeOutput));
207
208     // Generate the bytecode file.
209     int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
210     if (GenerateBytecode(Composite.get(), StripLevel, !NoInternalize, &Out)) {
211       Out.close();
212       return PrintAndReturn(argv[0], "error generating bytecode");
213     }
214
215     // Close the bytecode file.
216     Out.close();
217
218     // If we are not linking a library, generate either a native executable
219     // or a JIT shell script, depending upon what the user wants.
220     if (!LinkAsLibrary) {
221       // If the user wants to generate a native executable, compile it from the
222       // bytecode file.
223       //
224       // Otherwise, create a script that will run the bytecode through the JIT.
225       if (Native) {
226         // Name of the Assembly Language output file
227         std::string AssemblyFile = OutputFilename + ".s";
228
229         // Mark the output files for removal if we get an interrupt.
230         sys::RemoveFileOnSignal(sys::Path(AssemblyFile));
231         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
232
233         // Determine the locations of the llc and gcc programs.
234         std::string llc = FindExecutable("llc", argv[0]);
235         std::string gcc = FindExecutable("gcc", argv[0]);
236         if (llc.empty())
237           return PrintAndReturn(argv[0], "Failed to find llc");
238
239         if (gcc.empty())
240           return PrintAndReturn(argv[0], "Failed to find gcc");
241
242         // Generate an assembly language file for the bytecode.
243         if (Verbose) std::cout << "Generating Assembly Code\n";
244         GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
245         if (Verbose) std::cout << "Generating Native Code\n";
246         GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
247                        gcc, envp);
248
249         // Remove the assembly language file.
250         removeFile (AssemblyFile);
251       } else if (NativeCBE) {
252         std::string CFile = OutputFilename + ".cbe.c";
253
254         // Mark the output files for removal if we get an interrupt.
255         sys::RemoveFileOnSignal(sys::Path(CFile));
256         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
257
258         // Determine the locations of the llc and gcc programs.
259         std::string llc = FindExecutable("llc", argv[0]);
260         std::string gcc = FindExecutable("gcc", argv[0]);
261         if (llc.empty())
262           return PrintAndReturn(argv[0], "Failed to find llc");
263         if (gcc.empty())
264           return PrintAndReturn(argv[0], "Failed to find gcc");
265
266         // Generate an assembly language file for the bytecode.
267         if (Verbose) std::cout << "Generating Assembly Code\n";
268         GenerateCFile(CFile, RealBytecodeOutput, llc, envp);
269         if (Verbose) std::cout << "Generating Native Code\n";
270         GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp);
271
272         // Remove the assembly language file.
273         removeFile(CFile);
274
275       } else {
276         EmitShellScript(argv);
277       }
278     
279       // Make the script executable...
280       MakeFileExecutable(OutputFilename);
281
282       // Make the bytecode file readable and directly executable in LLEE as well
283       MakeFileExecutable(RealBytecodeOutput);
284       MakeFileReadable(RealBytecodeOutput);
285     }
286   } catch (const char*msg) {
287     std::cerr << argv[0] << ": " << msg << "\n";
288     exitCode = 1;
289   } catch (const std::string& msg) {
290     std::cerr << argv[0] << ": " << msg << "\n";
291     exitCode = 2;
292   } catch (...) {
293     // This really shouldn't happen, but just in case ....
294     std::cerr << argv[0] << ": An nexpected unknown exception occurred.\n";
295     exitCode = 3;
296   }
297
298   return exitCode;
299 }