blob: 0c633d2462db470064e685577c312b0a2f5d91e5 [file] [log] [blame]
Reid Spencerc0af3f02004-09-13 01:27:53 +00001//===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
Reid Spencerc0af3f02004-09-13 01:27:53 +00003// 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.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
Reid Spencerc0af3f02004-09-13 01:27:53 +00008//===----------------------------------------------------------------------===//
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
Reid Spencer605b9e22004-11-14 23:00:08 +000023#include "llvm/Linker.h"
Reid Spencer6da1e0d2004-12-14 04:20:08 +000024#include "llvm/System/Program.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000025#include "llvm/Module.h"
26#include "llvm/PassManager.h"
27#include "llvm/Bytecode/Reader.h"
Reid Spencer445564a2004-11-20 20:02:56 +000028#include "llvm/Bytecode/Writer.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000029#include "llvm/Target/TargetData.h"
Reid Spenceraefd04b2004-09-25 16:00:07 +000030#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetMachineRegistry.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/FileUtilities.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000034#include "llvm/Support/SystemUtils.h"
Reid Spencer445564a2004-11-20 20:02:56 +000035#include "llvm/System/Signals.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000036#include <fstream>
Reid Spencer445564a2004-11-20 20:02:56 +000037#include <iostream>
Reid Spencerc0af3f02004-09-13 01:27:53 +000038#include <memory>
Reid Spencer445564a2004-11-20 20:02:56 +000039
Reid Spencerc0af3f02004-09-13 01:27:53 +000040using namespace llvm;
41
Reid Spencer445564a2004-11-20 20:02:56 +000042// Input/Output Options
43static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
44 cl::desc("<input bytecode files>"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000045
Reid Spencer445564a2004-11-20 20:02:56 +000046static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
Misha Brukman3da94ae2005-04-22 00:00:37 +000047 cl::desc("Override output filename"),
Reid Spencer445564a2004-11-20 20:02:56 +000048 cl::value_desc("filename"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000049
Misha Brukman3da94ae2005-04-22 00:00:37 +000050static cl::opt<bool> Verbose("v",
Reid Spencer445564a2004-11-20 20:02:56 +000051 cl::desc("Print information about actions taken"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000052
Reid Spencer445564a2004-11-20 20:02:56 +000053static cl::list<std::string> LibPaths("L", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000054 cl::desc("Specify a library search path"),
Reid Spencer445564a2004-11-20 20:02:56 +000055 cl::value_desc("directory"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000056
Reid Spencer445564a2004-11-20 20:02:56 +000057static cl::list<std::string> Libraries("l", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000058 cl::desc("Specify libraries to link to"),
Reid Spencer445564a2004-11-20 20:02:56 +000059 cl::value_desc("library prefix"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000060
Misha Brukman3da94ae2005-04-22 00:00:37 +000061static cl::opt<bool> LinkAsLibrary("link-as-library",
Reid Spencer445564a2004-11-20 20:02:56 +000062 cl::desc("Link the .bc files together as a library, not an executable"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000063
Reid Spencer445564a2004-11-20 20:02:56 +000064static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
65 cl::desc("Alias for -link-as-library"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000066
Reid Spencer445564a2004-11-20 20:02:56 +000067static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
Reid Spenceraefd04b2004-09-25 16:00:07 +000068 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
69
Reid Spencer445564a2004-11-20 20:02:56 +000070static cl::opt<bool> Native("native",
71 cl::desc("Generate a native binary instead of a shell script"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000072
Reid Spencer445564a2004-11-20 20:02:56 +000073static cl::opt<bool>NativeCBE("native-cbe",
74 cl::desc("Generate a native binary with the C backend and GCC"));
75
76static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
77 cl::desc("Disable writing of compressed bytecode files"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000078
Reid Spencer73a74be2005-12-21 05:03:23 +000079static cl::list<std::string> PostLinkOpts("post-link-opts",
80 cl::value_desc("path to post-link optimization programs"),
81 cl::desc("Run one or more optimization programs after linking"));
82
Reid Spencer445564a2004-11-20 20:02:56 +000083// Compatibility options that are ignored but supported by LD
Misha Brukman3da94ae2005-04-22 00:00:37 +000084static cl::opt<std::string> CO3("soname", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000085 cl::desc("Compatibility option: ignored"));
86
Misha Brukman3da94ae2005-04-22 00:00:37 +000087static cl::opt<std::string> CO4("version-script", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000088 cl::desc("Compatibility option: ignored"));
89
Misha Brukman3da94ae2005-04-22 00:00:37 +000090static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000091 cl::desc("Compatibility option: ignored"));
92
Misha Brukman3da94ae2005-04-22 00:00:37 +000093static cl::opt<std::string> CO6("h", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000094 cl::desc("Compatibility option: ignored"));
95
96/// This is just for convenience so it doesn't have to be passed around
97/// everywhere.
Reid Spencerc4064132004-12-13 03:01:14 +000098static std::string progname;
Reid Spencerc0af3f02004-09-13 01:27:53 +000099
100/// PrintAndReturn - Prints a message to standard error and returns true.
101///
102/// Inputs:
103/// progname - The name of the program (i.e. argv[0]).
104/// Message - The message to print to standard error.
105///
Reid Spencer445564a2004-11-20 20:02:56 +0000106static int PrintAndReturn(const std::string &Message) {
Reid Spencerc0af3f02004-09-13 01:27:53 +0000107 std::cerr << progname << ": " << Message << "\n";
108 return 1;
109}
110
Reid Spencer445564a2004-11-20 20:02:56 +0000111/// CopyEnv - This function takes an array of environment variables and makes a
112/// copy of it. This copy can then be manipulated any way the caller likes
113/// without affecting the process's real environment.
114///
115/// Inputs:
116/// envp - An array of C strings containing an environment.
117///
118/// Return value:
119/// NULL - An error occurred.
120///
121/// Otherwise, a pointer to a new array of C strings is returned. Every string
122/// in the array is a duplicate of the one in the original array (i.e. we do
123/// not copy the char *'s from one array to another).
124///
125static char ** CopyEnv(char ** const envp) {
126 // Count the number of entries in the old list;
127 unsigned entries; // The number of entries in the old environment list
128 for (entries = 0; envp[entries] != NULL; entries++)
129 /*empty*/;
130
131 // Add one more entry for the NULL pointer that ends the list.
132 ++entries;
133
134 // If there are no entries at all, just return NULL.
135 if (entries == 0)
136 return NULL;
137
138 // Allocate a new environment list.
139 char **newenv = new char* [entries];
140 if ((newenv = new char* [entries]) == NULL)
141 return NULL;
142
143 // Make a copy of the list. Don't forget the NULL that ends the list.
144 entries = 0;
145 while (envp[entries] != NULL) {
146 newenv[entries] = new char[strlen (envp[entries]) + 1];
147 strcpy (newenv[entries], envp[entries]);
148 ++entries;
149 }
150 newenv[entries] = NULL;
151
152 return newenv;
153}
154
155
156/// RemoveEnv - Remove the specified environment variable from the environment
157/// array.
158///
159/// Inputs:
160/// name - The name of the variable to remove. It cannot be NULL.
161/// envp - The array of environment variables. It cannot be NULL.
162///
163/// Notes:
164/// This is mainly done because functions to remove items from the environment
165/// are not available across all platforms. In particular, Solaris does not
166/// seem to have an unsetenv() function or a setenv() function (or they are
167/// undocumented if they do exist).
168///
169static void RemoveEnv(const char * name, char ** const envp) {
170 for (unsigned index=0; envp[index] != NULL; index++) {
171 // Find the first equals sign in the array and make it an EOS character.
172 char *p = strchr (envp[index], '=');
173 if (p == NULL)
174 continue;
175 else
176 *p = '\0';
177
178 // Compare the two strings. If they are equal, zap this string.
179 // Otherwise, restore it.
180 if (!strcmp(name, envp[index]))
181 *envp[index] = '\0';
182 else
183 *p = '=';
184 }
185
186 return;
187}
188
189/// GenerateBytecode - generates a bytecode file from the module provided
190void GenerateBytecode(Module* M, const std::string& FileName) {
191
192 // Create the output file.
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000193 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
194 std::ios::binary;
195 std::ofstream Out(FileName.c_str(), io_mode);
Reid Spencer445564a2004-11-20 20:02:56 +0000196 if (!Out.good()) {
197 PrintAndReturn("error opening '" + FileName + "' for writing!");
198 return;
199 }
200
201 // Ensure that the bytecode file gets removed from the disk if we get a
202 // terminating signal.
203 sys::RemoveFileOnSignal(sys::Path(FileName));
204
205 // Write it out
206 WriteBytecodeToFile(M, Out, !DisableCompression);
207
208 // Close the bytecode file.
209 Out.close();
210}
211
212/// GenerateAssembly - generates a native assembly language source file from the
213/// specified bytecode file.
214///
215/// Inputs:
216/// InputFilename - The name of the output bytecode file.
217/// OutputFilename - The name of the file to generate.
218/// llc - The pathname to use for LLC.
219/// envp - The environment to use when running LLC.
220///
221/// Return non-zero value on error.
222///
223static int GenerateAssembly(const std::string &OutputFilename,
224 const std::string &InputFilename,
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000225 const sys::Path &llc) {
Reid Spencer445564a2004-11-20 20:02:56 +0000226 // Run LLC to convert the bytecode file into assembly code.
Reid Spencerf6358c72004-12-19 18:00:56 +0000227 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000228 args.push_back(llc.c_str());
229 args.push_back("-f");
230 args.push_back("-o");
231 args.push_back(OutputFilename.c_str());
232 args.push_back(InputFilename.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000233 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000234
Reid Spencerf6358c72004-12-19 18:00:56 +0000235 return sys::Program::ExecuteAndWait(llc,&args[0]);
Reid Spencer445564a2004-11-20 20:02:56 +0000236}
237
238/// GenerateAssembly - generates a native assembly language source file from the
239/// specified bytecode file.
240static int GenerateCFile(const std::string &OutputFile,
241 const std::string &InputFile,
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000242 const sys::Path &llc) {
Reid Spencer445564a2004-11-20 20:02:56 +0000243 // Run LLC to convert the bytecode file into C.
Reid Spencerf6358c72004-12-19 18:00:56 +0000244 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000245 args.push_back(llc.c_str());
246 args.push_back("-march=c");
247 args.push_back("-f");
248 args.push_back("-o");
249 args.push_back(OutputFile.c_str());
250 args.push_back(InputFile.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000251 args.push_back(0);
Reid Spencerf6358c72004-12-19 18:00:56 +0000252 return sys::Program::ExecuteAndWait(llc, &args[0]);
Reid Spencer445564a2004-11-20 20:02:56 +0000253}
254
255/// GenerateNative - generates a native assembly language source file from the
256/// specified assembly source file.
257///
258/// Inputs:
259/// InputFilename - The name of the output bytecode file.
260/// OutputFilename - The name of the file to generate.
261/// Libraries - The list of libraries with which to link.
262/// LibPaths - The list of directories in which to find libraries.
263/// gcc - The pathname to use for GGC.
264/// envp - A copy of the process's current environment.
265///
266/// Outputs:
267/// None.
268///
269/// Returns non-zero value on error.
270///
271static int GenerateNative(const std::string &OutputFilename,
272 const std::string &InputFilename,
273 const std::vector<std::string> &Libraries,
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000274 const sys::Path &gcc, char ** const envp) {
Reid Spencer445564a2004-11-20 20:02:56 +0000275 // Remove these environment variables from the environment of the
276 // programs that we will execute. It appears that GCC sets these
277 // environment variables so that the programs it uses can configure
278 // themselves identically.
279 //
280 // However, when we invoke GCC below, we want it to use its normal
281 // configuration. Hence, we must sanitize its environment.
282 char ** clean_env = CopyEnv(envp);
283 if (clean_env == NULL)
284 return 1;
285 RemoveEnv("LIBRARY_PATH", clean_env);
286 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
287 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
288 RemoveEnv("COMPILER_PATH", clean_env);
289 RemoveEnv("COLLECT_GCC", clean_env);
290
Reid Spencer445564a2004-11-20 20:02:56 +0000291
292 // Run GCC to assemble and link the program into native code.
293 //
294 // Note:
295 // We can't just assemble and link the file with the system assembler
296 // and linker because we don't know where to put the _start symbol.
297 // GCC mysteriously knows how to do it.
Reid Spencerf6358c72004-12-19 18:00:56 +0000298 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000299 args.push_back(gcc.c_str());
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000300 args.push_back("-fno-strict-aliasing");
301 args.push_back("-O3");
302 args.push_back("-o");
Reid Spencerf6358c72004-12-19 18:00:56 +0000303 args.push_back(OutputFilename.c_str());
304 args.push_back(InputFilename.c_str());
Reid Spencer445564a2004-11-20 20:02:56 +0000305
306 // Add in the libraries to link.
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000307 for (unsigned index = 0; index < Libraries.size(); index++)
Reid Spencerf6358c72004-12-19 18:00:56 +0000308 if (Libraries[index] != "crtend") {
309 args.push_back("-l");
310 args.push_back(Libraries[index].c_str());
311 }
Chris Lattner7456e3c2005-02-13 23:10:45 +0000312 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000313
314 // Run the compiler to assembly and link together the program.
Reid Spencerf6358c72004-12-19 18:00:56 +0000315 return sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
Reid Spencer445564a2004-11-20 20:02:56 +0000316}
317
Reid Spencerc0af3f02004-09-13 01:27:53 +0000318/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
319/// bytecode file for the program.
320static void EmitShellScript(char **argv) {
321#if defined(_WIN32) || defined(__CYGWIN__)
322 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
323 // support windows systems, we copy the llvm-stub.exe executable from the
324 // build tree to the destination file.
Reid Spencer8d8b41d2004-12-22 13:50:17 +0000325 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
326 if (llvmstub.isEmpty()) {
Reid Spencerc0af3f02004-09-13 01:27:53 +0000327 std::cerr << "Could not find llvm-stub.exe executable!\n";
328 exit(1);
329 }
Reid Spencer8d8b41d2004-12-22 13:50:17 +0000330 sys::CopyFile(sys::Path(OutputFilename), llvmstub);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000331 return;
332#endif
333
334 // Output the script to start the program...
335 std::ofstream Out2(OutputFilename.c_str());
336 if (!Out2.good())
Reid Spencer445564a2004-11-20 20:02:56 +0000337 exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
Reid Spencerc0af3f02004-09-13 01:27:53 +0000338
339 Out2 << "#!/bin/sh\n";
340 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
341 Out2 << "lli=${LLVMINTERP-lli}\n";
342 Out2 << "exec $lli \\\n";
343 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
344 LibPaths.push_back("/lib");
345 LibPaths.push_back("/usr/lib");
346 LibPaths.push_back("/usr/X11R6/lib");
347 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
348 // shared object at all! See RH 8: plain text.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000349 std::vector<std::string>::iterator libc =
Reid Spencerc0af3f02004-09-13 01:27:53 +0000350 std::find(Libraries.begin(), Libraries.end(), "c");
351 if (libc != Libraries.end()) Libraries.erase(libc);
352 // List all the shared object (native) libraries this executable will need
353 // on the command line, so that we don't have to do this manually!
Misha Brukman3da94ae2005-04-22 00:00:37 +0000354 for (std::vector<std::string>::iterator i = Libraries.begin(),
Reid Spencerc0af3f02004-09-13 01:27:53 +0000355 e = Libraries.end(); i != e; ++i) {
Reid Spencerc4064132004-12-13 03:01:14 +0000356 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
357 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
358 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000359 }
360 Out2 << " $0.bc ${1+\"$@\"}\n";
361 Out2.close();
362}
363
Reid Spencerc4064132004-12-13 03:01:14 +0000364// BuildLinkItems -- This function generates a LinkItemList for the LinkItems
365// linker function by combining the Files and Libraries in the order they were
366// declared on the command line.
367static void BuildLinkItems(
368 Linker::ItemList& Items,
369 const cl::list<std::string>& Files,
370 const cl::list<std::string>& Libraries) {
371
Misha Brukman3da94ae2005-04-22 00:00:37 +0000372 // Build the list of linkage items for LinkItems.
Reid Spencerc4064132004-12-13 03:01:14 +0000373
374 cl::list<std::string>::const_iterator fileIt = Files.begin();
375 cl::list<std::string>::const_iterator libIt = Libraries.begin();
376
377 int libPos = -1, filePos = -1;
Reid Spencer05f7e792004-12-13 17:18:19 +0000378 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
Reid Spencerc4064132004-12-13 03:01:14 +0000379 if (libIt != Libraries.end())
380 libPos = Libraries.getPosition(libIt - Libraries.begin());
381 else
382 libPos = -1;
383 if (fileIt != Files.end())
384 filePos = Files.getPosition(fileIt - Files.begin());
385 else
386 filePos = -1;
387
388 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
389 // Add a source file
390 Items.push_back(std::make_pair(*fileIt++, false));
391 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
392 // Add a library
393 Items.push_back(std::make_pair(*libIt++, true));
Reid Spencerc4064132004-12-13 03:01:14 +0000394 }
395 }
396}
397
Reid Spencer445564a2004-11-20 20:02:56 +0000398// Rightly this should go in a header file but it just seems such a waste.
399namespace llvm {
400extern void Optimize(Module*);
401}
402
Reid Spencerc0af3f02004-09-13 01:27:53 +0000403int main(int argc, char **argv, char **envp) {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000404 try {
405 // Initial global variable above for convenience printing of program name.
406 progname = sys::Path(argv[0]).getBasename();
Reid Spencer328ead92005-12-13 20:00:37 +0000407 Linker TheLinker(progname, OutputFilename, Verbose);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000408
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000409 // Set up the library paths for the Linker
410 TheLinker.addPaths(LibPaths);
411 TheLinker.addSystemPaths();
Reid Spencer445564a2004-11-20 20:02:56 +0000412
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000413 // Parse the command line options
414 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
415 sys::PrintStackTraceOnErrorSignal();
Reid Spencerc0af3f02004-09-13 01:27:53 +0000416
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000417 // Remove any consecutive duplicates of the same library...
418 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
419 Libraries.end());
Reid Spencerc0af3f02004-09-13 01:27:53 +0000420
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000421 if (LinkAsLibrary) {
422 std::vector<sys::Path> Files;
423 for (unsigned i = 0; i < InputFilenames.size(); ++i )
424 Files.push_back(sys::Path(InputFilenames[i]));
425 if (TheLinker.LinkInFiles(Files))
426 return 1; // Error already printed
Reid Spencer6b463b22004-12-08 05:17:40 +0000427
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000428 // The libraries aren't linked in but are noted as "dependent" in the
429 // module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000430 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000431 E = Libraries.end(); I != E ; ++I) {
432 TheLinker.getModule()->addLibrary(*I);
433 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000434 } else {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000435 // Build a list of the items from our command line
436 Linker::ItemList Items;
437 BuildLinkItems(Items, InputFilenames, Libraries);
438
439 // Link all the items together
440 if (TheLinker.LinkInItems(Items) )
441 return 1;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000442 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000443
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000444 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
445
446 // Optimize the module
447 Optimize(Composite.get());
448
449 // Generate the bytecode for the optimized module.
450 std::string RealBytecodeOutput = OutputFilename;
451 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
452 GenerateBytecode(Composite.get(), RealBytecodeOutput);
453
454 // If we are not linking a library, generate either a native executable
455 // or a JIT shell script, depending upon what the user wants.
456 if (!LinkAsLibrary) {
Reid Spencer73a74be2005-12-21 05:03:23 +0000457 // If the user wants to run a post-link optimization, run it now.
458 if (!PostLinkOpts.empty()) {
459 std::vector<std::string> opts = PostLinkOpts;
460 for (std::vector<std::string>::iterator I = opts.begin(),
461 E = opts.end(); I != E; ++I) {
462 sys::Path prog(*I);
463 if (!prog.canExecute()) {
464 prog = sys::Program::FindProgramByName(*I);
465 if (prog.isEmpty())
466 return PrintAndReturn(std::string("Optimization program '") + *I +
467 "' is not found or not executable.");
468 }
469 // Get the program arguments
470 sys::Path tmp_output("opt_result");
471 if (!tmp_output.createTemporaryFileOnDisk()) {
472 return PrintAndReturn(
473 "Can't create temporary file for post-link optimization");
474 }
475 const char* args[4];
476 args[0] = I->c_str();
477 args[1] = RealBytecodeOutput.c_str();
478 args[2] = tmp_output.c_str();
479 args[3] = 0;
480 if (0 == sys::Program::ExecuteAndWait(prog, args)) {
481 if (tmp_output.isBytecodeFile()) {
482 sys::Path target(RealBytecodeOutput);
483 target.eraseFromDisk();
484 tmp_output.renamePathOnDisk(target);
485 } else
486 return PrintAndReturn(
487 "Post-link optimization output is not bytecode");
488 }
489 }
490 }
491
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000492 // If the user wants to generate a native executable, compile it from the
493 // bytecode file.
494 //
495 // Otherwise, create a script that will run the bytecode through the JIT.
496 if (Native) {
497 // Name of the Assembly Language output file
498 sys::Path AssemblyFile ( OutputFilename);
499 AssemblyFile.appendSuffix("s");
500
501 // Mark the output files for removal if we get an interrupt.
502 sys::RemoveFileOnSignal(AssemblyFile);
503 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
504
505 // Determine the locations of the llc and gcc programs.
506 sys::Path llc = FindExecutable("llc", argv[0]);
507 if (llc.isEmpty())
508 return PrintAndReturn("Failed to find llc");
509
510 sys::Path gcc = FindExecutable("gcc", argv[0]);
511 if (gcc.isEmpty())
512 return PrintAndReturn("Failed to find gcc");
513
514 // Generate an assembly language file for the bytecode.
515 if (Verbose) std::cout << "Generating Assembly Code\n";
516 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
517 if (Verbose) std::cout << "Generating Native Code\n";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000518 GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000519 gcc, envp);
520
521 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000522 AssemblyFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000523 } else if (NativeCBE) {
524 sys::Path CFile (OutputFilename);
525 CFile.appendSuffix("cbe.c");
526
527 // Mark the output files for removal if we get an interrupt.
528 sys::RemoveFileOnSignal(CFile);
529 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
530
531 // Determine the locations of the llc and gcc programs.
532 sys::Path llc = FindExecutable("llc", argv[0]);
533 if (llc.isEmpty())
534 return PrintAndReturn("Failed to find llc");
535
536 sys::Path gcc = FindExecutable("gcc", argv[0]);
537 if (gcc.isEmpty())
538 return PrintAndReturn("Failed to find gcc");
539
540 // Generate an assembly language file for the bytecode.
541 if (Verbose) std::cout << "Generating Assembly Code\n";
542 GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
543 if (Verbose) std::cout << "Generating Native Code\n";
544 GenerateNative(OutputFilename, CFile.toString(), Libraries, gcc, envp);
545
546 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000547 CFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000548
549 } else {
550 EmitShellScript(argv);
551 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000552
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000553 // Make the script executable...
Reid Spencera229c5c2005-07-08 03:08:58 +0000554 sys::Path(OutputFilename).makeExecutableOnDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000555
556 // Make the bytecode file readable and directly executable in LLEE as well
Reid Spencera229c5c2005-07-08 03:08:58 +0000557 sys::Path(RealBytecodeOutput).makeExecutableOnDisk();
558 sys::Path(RealBytecodeOutput).makeReadableOnDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000559 }
560
561 return 0;
562 } catch (const std::string& msg) {
563 std::cerr << argv[0] << ": " << msg << "\n";
564 } catch (...) {
565 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000566 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000567 return 1;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000568}