blob: ccd643e1736cbf9d59a18069f2420407c9c17ccc [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 Spencer445564a2004-11-20 20:02:56 +000079// Compatibility options that are ignored but supported by LD
Misha Brukman3da94ae2005-04-22 00:00:37 +000080static cl::opt<std::string> CO3("soname", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000081 cl::desc("Compatibility option: ignored"));
82
Misha Brukman3da94ae2005-04-22 00:00:37 +000083static cl::opt<std::string> CO4("version-script", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000084 cl::desc("Compatibility option: ignored"));
85
Misha Brukman3da94ae2005-04-22 00:00:37 +000086static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000087 cl::desc("Compatibility option: ignored"));
88
Misha Brukman3da94ae2005-04-22 00:00:37 +000089static cl::opt<std::string> CO6("h", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000090 cl::desc("Compatibility option: ignored"));
91
92/// This is just for convenience so it doesn't have to be passed around
93/// everywhere.
Reid Spencerc4064132004-12-13 03:01:14 +000094static std::string progname;
Reid Spencerc0af3f02004-09-13 01:27:53 +000095
96/// PrintAndReturn - Prints a message to standard error and returns true.
97///
98/// Inputs:
99/// progname - The name of the program (i.e. argv[0]).
100/// Message - The message to print to standard error.
101///
Reid Spencer445564a2004-11-20 20:02:56 +0000102static int PrintAndReturn(const std::string &Message) {
Reid Spencerc0af3f02004-09-13 01:27:53 +0000103 std::cerr << progname << ": " << Message << "\n";
104 return 1;
105}
106
Reid Spencer445564a2004-11-20 20:02:56 +0000107/// CopyEnv - This function takes an array of environment variables and makes a
108/// copy of it. This copy can then be manipulated any way the caller likes
109/// without affecting the process's real environment.
110///
111/// Inputs:
112/// envp - An array of C strings containing an environment.
113///
114/// Return value:
115/// NULL - An error occurred.
116///
117/// Otherwise, a pointer to a new array of C strings is returned. Every string
118/// in the array is a duplicate of the one in the original array (i.e. we do
119/// not copy the char *'s from one array to another).
120///
121static char ** CopyEnv(char ** const envp) {
122 // Count the number of entries in the old list;
123 unsigned entries; // The number of entries in the old environment list
124 for (entries = 0; envp[entries] != NULL; entries++)
125 /*empty*/;
126
127 // Add one more entry for the NULL pointer that ends the list.
128 ++entries;
129
130 // If there are no entries at all, just return NULL.
131 if (entries == 0)
132 return NULL;
133
134 // Allocate a new environment list.
135 char **newenv = new char* [entries];
136 if ((newenv = new char* [entries]) == NULL)
137 return NULL;
138
139 // Make a copy of the list. Don't forget the NULL that ends the list.
140 entries = 0;
141 while (envp[entries] != NULL) {
142 newenv[entries] = new char[strlen (envp[entries]) + 1];
143 strcpy (newenv[entries], envp[entries]);
144 ++entries;
145 }
146 newenv[entries] = NULL;
147
148 return newenv;
149}
150
151
152/// RemoveEnv - Remove the specified environment variable from the environment
153/// array.
154///
155/// Inputs:
156/// name - The name of the variable to remove. It cannot be NULL.
157/// envp - The array of environment variables. It cannot be NULL.
158///
159/// Notes:
160/// This is mainly done because functions to remove items from the environment
161/// are not available across all platforms. In particular, Solaris does not
162/// seem to have an unsetenv() function or a setenv() function (or they are
163/// undocumented if they do exist).
164///
165static void RemoveEnv(const char * name, char ** const envp) {
166 for (unsigned index=0; envp[index] != NULL; index++) {
167 // Find the first equals sign in the array and make it an EOS character.
168 char *p = strchr (envp[index], '=');
169 if (p == NULL)
170 continue;
171 else
172 *p = '\0';
173
174 // Compare the two strings. If they are equal, zap this string.
175 // Otherwise, restore it.
176 if (!strcmp(name, envp[index]))
177 *envp[index] = '\0';
178 else
179 *p = '=';
180 }
181
182 return;
183}
184
185/// GenerateBytecode - generates a bytecode file from the module provided
186void GenerateBytecode(Module* M, const std::string& FileName) {
187
188 // Create the output file.
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000189 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
190 std::ios::binary;
191 std::ofstream Out(FileName.c_str(), io_mode);
Reid Spencer445564a2004-11-20 20:02:56 +0000192 if (!Out.good()) {
193 PrintAndReturn("error opening '" + FileName + "' for writing!");
194 return;
195 }
196
197 // Ensure that the bytecode file gets removed from the disk if we get a
198 // terminating signal.
199 sys::RemoveFileOnSignal(sys::Path(FileName));
200
201 // Write it out
202 WriteBytecodeToFile(M, Out, !DisableCompression);
203
204 // Close the bytecode file.
205 Out.close();
206}
207
208/// GenerateAssembly - generates a native assembly language source file from the
209/// specified bytecode file.
210///
211/// Inputs:
212/// InputFilename - The name of the output bytecode file.
213/// OutputFilename - The name of the file to generate.
214/// llc - The pathname to use for LLC.
215/// envp - The environment to use when running LLC.
216///
217/// Return non-zero value on error.
218///
219static int GenerateAssembly(const std::string &OutputFilename,
220 const std::string &InputFilename,
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000221 const sys::Path &llc) {
Reid Spencer445564a2004-11-20 20:02:56 +0000222 // Run LLC to convert the bytecode file into assembly code.
Reid Spencerf6358c72004-12-19 18:00:56 +0000223 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000224 args.push_back(llc.c_str());
225 args.push_back("-f");
226 args.push_back("-o");
227 args.push_back(OutputFilename.c_str());
228 args.push_back(InputFilename.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000229 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000230
Reid Spencerf6358c72004-12-19 18:00:56 +0000231 return sys::Program::ExecuteAndWait(llc,&args[0]);
Reid Spencer445564a2004-11-20 20:02:56 +0000232}
233
234/// GenerateAssembly - generates a native assembly language source file from the
235/// specified bytecode file.
236static int GenerateCFile(const std::string &OutputFile,
237 const std::string &InputFile,
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000238 const sys::Path &llc) {
Reid Spencer445564a2004-11-20 20:02:56 +0000239 // Run LLC to convert the bytecode file into C.
Reid Spencerf6358c72004-12-19 18:00:56 +0000240 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000241 args.push_back(llc.c_str());
242 args.push_back("-march=c");
243 args.push_back("-f");
244 args.push_back("-o");
245 args.push_back(OutputFile.c_str());
246 args.push_back(InputFile.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000247 args.push_back(0);
Reid Spencerf6358c72004-12-19 18:00:56 +0000248 return sys::Program::ExecuteAndWait(llc, &args[0]);
Reid Spencer445564a2004-11-20 20:02:56 +0000249}
250
251/// GenerateNative - generates a native assembly language source file from the
252/// specified assembly source file.
253///
254/// Inputs:
255/// InputFilename - The name of the output bytecode file.
256/// OutputFilename - The name of the file to generate.
257/// Libraries - The list of libraries with which to link.
258/// LibPaths - The list of directories in which to find libraries.
259/// gcc - The pathname to use for GGC.
260/// envp - A copy of the process's current environment.
261///
262/// Outputs:
263/// None.
264///
265/// Returns non-zero value on error.
266///
267static int GenerateNative(const std::string &OutputFilename,
268 const std::string &InputFilename,
269 const std::vector<std::string> &Libraries,
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000270 const sys::Path &gcc, char ** const envp) {
Reid Spencer445564a2004-11-20 20:02:56 +0000271 // Remove these environment variables from the environment of the
272 // programs that we will execute. It appears that GCC sets these
273 // environment variables so that the programs it uses can configure
274 // themselves identically.
275 //
276 // However, when we invoke GCC below, we want it to use its normal
277 // configuration. Hence, we must sanitize its environment.
278 char ** clean_env = CopyEnv(envp);
279 if (clean_env == NULL)
280 return 1;
281 RemoveEnv("LIBRARY_PATH", clean_env);
282 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
283 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
284 RemoveEnv("COMPILER_PATH", clean_env);
285 RemoveEnv("COLLECT_GCC", clean_env);
286
Reid Spencer445564a2004-11-20 20:02:56 +0000287
288 // Run GCC to assemble and link the program into native code.
289 //
290 // Note:
291 // We can't just assemble and link the file with the system assembler
292 // and linker because we don't know where to put the _start symbol.
293 // GCC mysteriously knows how to do it.
Reid Spencerf6358c72004-12-19 18:00:56 +0000294 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000295 args.push_back(gcc.c_str());
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000296 args.push_back("-fno-strict-aliasing");
297 args.push_back("-O3");
298 args.push_back("-o");
Reid Spencerf6358c72004-12-19 18:00:56 +0000299 args.push_back(OutputFilename.c_str());
300 args.push_back(InputFilename.c_str());
Reid Spencer445564a2004-11-20 20:02:56 +0000301
302 // Add in the libraries to link.
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000303 for (unsigned index = 0; index < Libraries.size(); index++)
Reid Spencerf6358c72004-12-19 18:00:56 +0000304 if (Libraries[index] != "crtend") {
305 args.push_back("-l");
306 args.push_back(Libraries[index].c_str());
307 }
Chris Lattner7456e3c2005-02-13 23:10:45 +0000308 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000309
310 // Run the compiler to assembly and link together the program.
Reid Spencerf6358c72004-12-19 18:00:56 +0000311 return sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
Reid Spencer445564a2004-11-20 20:02:56 +0000312}
313
Reid Spencerc0af3f02004-09-13 01:27:53 +0000314/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
315/// bytecode file for the program.
316static void EmitShellScript(char **argv) {
317#if defined(_WIN32) || defined(__CYGWIN__)
318 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
319 // support windows systems, we copy the llvm-stub.exe executable from the
320 // build tree to the destination file.
Reid Spencer8d8b41d2004-12-22 13:50:17 +0000321 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
322 if (llvmstub.isEmpty()) {
Reid Spencerc0af3f02004-09-13 01:27:53 +0000323 std::cerr << "Could not find llvm-stub.exe executable!\n";
324 exit(1);
325 }
Reid Spencer8d8b41d2004-12-22 13:50:17 +0000326 sys::CopyFile(sys::Path(OutputFilename), llvmstub);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000327 return;
328#endif
329
330 // Output the script to start the program...
331 std::ofstream Out2(OutputFilename.c_str());
332 if (!Out2.good())
Reid Spencer445564a2004-11-20 20:02:56 +0000333 exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
Reid Spencerc0af3f02004-09-13 01:27:53 +0000334
335 Out2 << "#!/bin/sh\n";
336 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
337 Out2 << "lli=${LLVMINTERP-lli}\n";
338 Out2 << "exec $lli \\\n";
339 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
340 LibPaths.push_back("/lib");
341 LibPaths.push_back("/usr/lib");
342 LibPaths.push_back("/usr/X11R6/lib");
343 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
344 // shared object at all! See RH 8: plain text.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000345 std::vector<std::string>::iterator libc =
Reid Spencerc0af3f02004-09-13 01:27:53 +0000346 std::find(Libraries.begin(), Libraries.end(), "c");
347 if (libc != Libraries.end()) Libraries.erase(libc);
348 // List all the shared object (native) libraries this executable will need
349 // on the command line, so that we don't have to do this manually!
Misha Brukman3da94ae2005-04-22 00:00:37 +0000350 for (std::vector<std::string>::iterator i = Libraries.begin(),
Reid Spencerc0af3f02004-09-13 01:27:53 +0000351 e = Libraries.end(); i != e; ++i) {
Reid Spencerc4064132004-12-13 03:01:14 +0000352 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
353 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
354 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000355 }
356 Out2 << " $0.bc ${1+\"$@\"}\n";
357 Out2.close();
358}
359
Reid Spencerc4064132004-12-13 03:01:14 +0000360// BuildLinkItems -- This function generates a LinkItemList for the LinkItems
361// linker function by combining the Files and Libraries in the order they were
362// declared on the command line.
363static void BuildLinkItems(
364 Linker::ItemList& Items,
365 const cl::list<std::string>& Files,
366 const cl::list<std::string>& Libraries) {
367
Misha Brukman3da94ae2005-04-22 00:00:37 +0000368 // Build the list of linkage items for LinkItems.
Reid Spencerc4064132004-12-13 03:01:14 +0000369
370 cl::list<std::string>::const_iterator fileIt = Files.begin();
371 cl::list<std::string>::const_iterator libIt = Libraries.begin();
372
373 int libPos = -1, filePos = -1;
Reid Spencer05f7e792004-12-13 17:18:19 +0000374 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
Reid Spencerc4064132004-12-13 03:01:14 +0000375 if (libIt != Libraries.end())
376 libPos = Libraries.getPosition(libIt - Libraries.begin());
377 else
378 libPos = -1;
379 if (fileIt != Files.end())
380 filePos = Files.getPosition(fileIt - Files.begin());
381 else
382 filePos = -1;
383
384 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
385 // Add a source file
386 Items.push_back(std::make_pair(*fileIt++, false));
387 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
388 // Add a library
389 Items.push_back(std::make_pair(*libIt++, true));
Reid Spencerc4064132004-12-13 03:01:14 +0000390 }
391 }
392}
393
Reid Spencer445564a2004-11-20 20:02:56 +0000394// Rightly this should go in a header file but it just seems such a waste.
395namespace llvm {
396extern void Optimize(Module*);
397}
398
Reid Spencerc0af3f02004-09-13 01:27:53 +0000399int main(int argc, char **argv, char **envp) {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000400 try {
401 // Initial global variable above for convenience printing of program name.
402 progname = sys::Path(argv[0]).getBasename();
403 Linker TheLinker(progname, Verbose);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000404
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000405 // Set up the library paths for the Linker
406 TheLinker.addPaths(LibPaths);
407 TheLinker.addSystemPaths();
Reid Spencer445564a2004-11-20 20:02:56 +0000408
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000409 // Parse the command line options
410 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
411 sys::PrintStackTraceOnErrorSignal();
Reid Spencerc0af3f02004-09-13 01:27:53 +0000412
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000413 // Remove any consecutive duplicates of the same library...
414 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
415 Libraries.end());
Reid Spencerc0af3f02004-09-13 01:27:53 +0000416
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000417 if (LinkAsLibrary) {
418 std::vector<sys::Path> Files;
419 for (unsigned i = 0; i < InputFilenames.size(); ++i )
420 Files.push_back(sys::Path(InputFilenames[i]));
421 if (TheLinker.LinkInFiles(Files))
422 return 1; // Error already printed
Reid Spencer6b463b22004-12-08 05:17:40 +0000423
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000424 // The libraries aren't linked in but are noted as "dependent" in the
425 // module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000426 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000427 E = Libraries.end(); I != E ; ++I) {
428 TheLinker.getModule()->addLibrary(*I);
429 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000430 } else {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000431 // Build a list of the items from our command line
432 Linker::ItemList Items;
433 BuildLinkItems(Items, InputFilenames, Libraries);
434
435 // Link all the items together
436 if (TheLinker.LinkInItems(Items) )
437 return 1;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000438 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000439
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000440 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
441
442 // Optimize the module
443 Optimize(Composite.get());
444
445 // Generate the bytecode for the optimized module.
446 std::string RealBytecodeOutput = OutputFilename;
447 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
448 GenerateBytecode(Composite.get(), RealBytecodeOutput);
449
450 // If we are not linking a library, generate either a native executable
451 // or a JIT shell script, depending upon what the user wants.
452 if (!LinkAsLibrary) {
453 // If the user wants to generate a native executable, compile it from the
454 // bytecode file.
455 //
456 // Otherwise, create a script that will run the bytecode through the JIT.
457 if (Native) {
458 // Name of the Assembly Language output file
459 sys::Path AssemblyFile ( OutputFilename);
460 AssemblyFile.appendSuffix("s");
461
462 // Mark the output files for removal if we get an interrupt.
463 sys::RemoveFileOnSignal(AssemblyFile);
464 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
465
466 // Determine the locations of the llc and gcc programs.
467 sys::Path llc = FindExecutable("llc", argv[0]);
468 if (llc.isEmpty())
469 return PrintAndReturn("Failed to find llc");
470
471 sys::Path gcc = FindExecutable("gcc", argv[0]);
472 if (gcc.isEmpty())
473 return PrintAndReturn("Failed to find gcc");
474
475 // Generate an assembly language file for the bytecode.
476 if (Verbose) std::cout << "Generating Assembly Code\n";
477 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
478 if (Verbose) std::cout << "Generating Native Code\n";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000479 GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000480 gcc, envp);
481
482 // Remove the assembly language file.
483 AssemblyFile.destroyFile();
484 } else if (NativeCBE) {
485 sys::Path CFile (OutputFilename);
486 CFile.appendSuffix("cbe.c");
487
488 // Mark the output files for removal if we get an interrupt.
489 sys::RemoveFileOnSignal(CFile);
490 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
491
492 // Determine the locations of the llc and gcc programs.
493 sys::Path llc = FindExecutable("llc", argv[0]);
494 if (llc.isEmpty())
495 return PrintAndReturn("Failed to find llc");
496
497 sys::Path gcc = FindExecutable("gcc", argv[0]);
498 if (gcc.isEmpty())
499 return PrintAndReturn("Failed to find gcc");
500
501 // Generate an assembly language file for the bytecode.
502 if (Verbose) std::cout << "Generating Assembly Code\n";
503 GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
504 if (Verbose) std::cout << "Generating Native Code\n";
505 GenerateNative(OutputFilename, CFile.toString(), Libraries, gcc, envp);
506
507 // Remove the assembly language file.
508 CFile.destroyFile();
509
510 } else {
511 EmitShellScript(argv);
512 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000513
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000514 // Make the script executable...
515 sys::Path(OutputFilename).makeExecutable();
516
517 // Make the bytecode file readable and directly executable in LLEE as well
518 sys::Path(RealBytecodeOutput).makeExecutable();
519 sys::Path(RealBytecodeOutput).makeReadable();
520 }
521
522 return 0;
523 } catch (const std::string& msg) {
524 std::cerr << argv[0] << ": " << msg << "\n";
525 } catch (...) {
526 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000527 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000528 return 1;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000529}