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