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