1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
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.
21 //===----------------------------------------------------------------------===//
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"
40 enum OptimizationLevels {
45 OPT_AGGRESSIVE_LINK_TIME
50 InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
54 OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
55 cl::value_desc("filename"));
58 Verbose("v", cl::desc("Print information about actions taken"));
61 LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
62 cl::value_desc("directory"));
65 Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
66 cl::value_desc("library prefix"));
69 Strip("s", cl::desc("Strip symbol info from executable"));
72 NoInternalize("disable-internalize",
73 cl::desc("Do not mark all symbols as internal"));
75 ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
76 cl::aliasopt(NoInternalize));
79 LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
80 " library, not an executable"));
82 Relink("r", cl::desc("Alias for -link-as-library"),
83 cl::aliasopt(LinkAsLibrary));
87 cl::desc("Generate a native binary instead of a shell script"));
89 NativeCBE("native-cbe",
90 cl::desc("Generate a native binary with the C backend and GCC"));
92 // Compatibility options that are ignored but supported by LD
94 CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
96 CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
98 CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
100 CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
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"),
122 /// PrintAndReturn - Prints a message to standard error and returns true.
125 /// progname - The name of the program (i.e. argv[0]).
126 /// Message - The message to print to standard error.
128 static int PrintAndReturn(const char *progname, const std::string &Message) {
129 std::cerr << progname << ": " << Message << "\n";
133 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
134 /// bytecode file for the program.
135 static 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";
145 if (CopyFile(OutputFilename, llvmstub)) {
146 std::cerr << "Could not copy the llvm-stub.exe executable!\n";
152 // Output the script to start the program...
153 std::ofstream Out2(OutputFilename.c_str());
155 exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
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";
179 Out2 << " $0.bc ${1+\"$@\"}\n";
183 int main(int argc, char **argv, char **envp) {
184 cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
185 sys::PrintStackTraceOnErrorSignal();
187 std::string ModuleID("gccld-output");
188 std::auto_ptr<Module> Composite(new Module(ModuleID));
190 // We always look first in the current directory when searching for libraries.
191 LibPaths.insert(LibPaths.begin(), ".");
193 // If the user specified an extra search path in their environment, respect
195 if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
196 LibPaths.push_back(SearchPath);
198 // Remove any consecutive duplicates of the same library...
199 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
202 // Link in all of the files
203 if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
204 return 1; // Error already printed
207 LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,
210 // Link in all of the libraries next...
212 // Create the output file.
213 std::string RealBytecodeOutput = OutputFilename;
214 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
215 std::ofstream Out(RealBytecodeOutput.c_str());
217 return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
220 // Ensure that the bytecode file gets removed from the disk if we get a
222 sys::RemoveFileOnSignal(RealBytecodeOutput);
224 // Generate the bytecode file.
225 if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {
227 return PrintAndReturn(argv[0], "error generating bytecode");
230 // Close the bytecode file.
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
239 // Otherwise, create a script that will run the bytecode through the JIT.
241 // Name of the Assembly Language output file
242 std::string AssemblyFile = OutputFilename + ".s";
244 // Mark the output files for removal if we get an interrupt.
245 sys::RemoveFileOnSignal(AssemblyFile);
246 sys::RemoveFileOnSignal(OutputFilename);
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]);
252 return PrintAndReturn(argv[0], "Failed to find llc");
255 return PrintAndReturn(argv[0], "Failed to find gcc");
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,
264 // Remove the assembly language file.
265 removeFile (AssemblyFile);
266 } else if (NativeCBE) {
267 std::string CFile = OutputFilename + ".cbe.c";
269 // Mark the output files for removal if we get an interrupt.
270 sys::RemoveFileOnSignal(CFile);
271 sys::RemoveFileOnSignal(OutputFilename);
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]);
277 return PrintAndReturn(argv[0], "Failed to find llc");
279 return PrintAndReturn(argv[0], "Failed to find gcc");
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);
287 // Remove the assembly language file.
291 EmitShellScript(argv);
294 // Make the script executable...
295 MakeFileExecutable(OutputFilename);
297 // Make the bytecode file readable and directly executable in LLEE as well
298 MakeFileExecutable(RealBytecodeOutput);
299 MakeFileReadable(RealBytecodeOutput);