blob: cc672bc5da7a8f59c8e85a4d0d27b115badf8e8d [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//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Gabor Greifa99be512007-07-05 17:07:56 +000014// example), is directly executable, whereas the bitcode file actually lives in
Reid Spencerc0af3f02004-09-13 01:27:53 +000015// 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 Spenceraf303d52006-06-07 23:03:13 +000023#include "llvm/LinkAllVMCore.h"
Reid Spencer605b9e22004-11-14 23:00:08 +000024#include "llvm/Linker.h"
Owen Anderson8b477ed2009-07-01 16:58:40 +000025#include "llvm/LLVMContext.h"
Reid Spencer6da1e0d2004-12-14 04:20:08 +000026#include "llvm/System/Program.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000027#include "llvm/Module.h"
28#include "llvm/PassManager.h"
Chris Lattnerbb3f3d32007-05-06 05:56:58 +000029#include "llvm/Bitcode/ReaderWriter.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000030#include "llvm/Target/TargetData.h"
Reid Spenceraefd04b2004-09-25 16:00:07 +000031#include "llvm/Target/TargetMachine.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/FileUtilities.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000034#include "llvm/Support/ManagedStatic.h"
Chris Lattnerbb3f3d32007-05-06 05:56:58 +000035#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercc14d252009-03-06 05:34:10 +000036#include "llvm/Support/PrettyStackTrace.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000037#include "llvm/Support/SystemUtils.h"
Reid Spencer445564a2004-11-20 20:02:56 +000038#include "llvm/System/Signals.h"
Chris Lattner5d5a8972009-01-05 19:01:32 +000039#include "llvm/Config/config.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000040#include <memory>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000041#include <cstring>
Reid Spencerc0af3f02004-09-13 01:27:53 +000042using namespace llvm;
43
Reid Spencer445564a2004-11-20 20:02:56 +000044// Input/Output Options
45static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
Gabor Greifa99be512007-07-05 17:07:56 +000046 cl::desc("<input bitcode files>"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000047
Reid Spencer445564a2004-11-20 20:02:56 +000048static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
Misha Brukman3da94ae2005-04-22 00:00:37 +000049 cl::desc("Override output filename"),
Reid Spencer445564a2004-11-20 20:02:56 +000050 cl::value_desc("filename"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000051
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +000052static cl::opt<std::string> BitcodeOutputFilename("b", cl::init(""),
53 cl::desc("Override bitcode output filename"),
54 cl::value_desc("filename"));
55
Misha Brukman3da94ae2005-04-22 00:00:37 +000056static cl::opt<bool> Verbose("v",
Reid Spencer445564a2004-11-20 20:02:56 +000057 cl::desc("Print information about actions taken"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000058
Reid Spencer445564a2004-11-20 20:02:56 +000059static cl::list<std::string> LibPaths("L", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000060 cl::desc("Specify a library search path"),
Reid Spencer445564a2004-11-20 20:02:56 +000061 cl::value_desc("directory"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000062
Chris Lattner3992f522008-01-27 22:58:59 +000063static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
64 cl::desc("Specify a framework search path"),
65 cl::value_desc("directory"));
66
Reid Spencer445564a2004-11-20 20:02:56 +000067static cl::list<std::string> Libraries("l", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000068 cl::desc("Specify libraries to link to"),
Reid Spencer445564a2004-11-20 20:02:56 +000069 cl::value_desc("library prefix"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000070
Chris Lattner3992f522008-01-27 22:58:59 +000071static cl::list<std::string> Frameworks("framework",
72 cl::desc("Specify frameworks to link to"),
73 cl::value_desc("framework"));
74
Reid Spencer708585a2007-02-09 03:08:06 +000075// Options to control the linking, optimization, and code gen processes
Misha Brukman3da94ae2005-04-22 00:00:37 +000076static cl::opt<bool> LinkAsLibrary("link-as-library",
Reid Spencer445564a2004-11-20 20:02:56 +000077 cl::desc("Link the .bc files together as a library, not an executable"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000078
Reid Spencer445564a2004-11-20 20:02:56 +000079static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
80 cl::desc("Alias for -link-as-library"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000081
Reid Spencer445564a2004-11-20 20:02:56 +000082static cl::opt<bool> Native("native",
83 cl::desc("Generate a native binary instead of a shell script"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000084
Reid Spencer445564a2004-11-20 20:02:56 +000085static cl::opt<bool>NativeCBE("native-cbe",
86 cl::desc("Generate a native binary with the C backend and GCC"));
87
Reid Spencer73a74be2005-12-21 05:03:23 +000088static cl::list<std::string> PostLinkOpts("post-link-opts",
Reid Spenceraf303d52006-06-07 23:03:13 +000089 cl::value_desc("path"),
Reid Spencer73a74be2005-12-21 05:03:23 +000090 cl::desc("Run one or more optimization programs after linking"));
91
Reid Spenceraf303d52006-06-07 23:03:13 +000092static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
93 cl::desc("Pass options to the system linker"));
94
Reid Spencer708585a2007-02-09 03:08:06 +000095// Compatibility options that llvm-ld ignores but are supported for
96// compatibility with LD
Misha Brukman3da94ae2005-04-22 00:00:37 +000097static cl::opt<std::string> CO3("soname", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000098 cl::desc("Compatibility option: ignored"));
99
Misha Brukman3da94ae2005-04-22 00:00:37 +0000100static cl::opt<std::string> CO4("version-script", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000101 cl::desc("Compatibility option: ignored"));
102
Misha Brukman3da94ae2005-04-22 00:00:37 +0000103static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000104 cl::desc("Compatibility option: ignored"));
105
Misha Brukman3da94ae2005-04-22 00:00:37 +0000106static cl::opt<std::string> CO6("h", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000107 cl::desc("Compatibility option: ignored"));
108
Reid Spencer98a030c2007-02-08 19:03:11 +0000109static cl::opt<bool> CO7("start-group", cl::Hidden,
110 cl::desc("Compatibility option: ignored"));
111
112static cl::opt<bool> CO8("end-group", cl::Hidden,
113 cl::desc("Compatibility option: ignored"));
Reid Spenceraf303d52006-06-07 23:03:13 +0000114
Andrew Lenharth0c6ba442008-11-19 17:00:08 +0000115static cl::opt<std::string> CO9("m", cl::Hidden,
116 cl::desc("Compatibility option: ignored"));
117
Reid Spencer445564a2004-11-20 20:02:56 +0000118/// This is just for convenience so it doesn't have to be passed around
119/// everywhere.
Reid Spencerc4064132004-12-13 03:01:14 +0000120static std::string progname;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000121
Reid Spencer708585a2007-02-09 03:08:06 +0000122/// PrintAndExit - Prints a message to standard error and exits with error code
Reid Spencerc0af3f02004-09-13 01:27:53 +0000123///
124/// Inputs:
Reid Spencerc0af3f02004-09-13 01:27:53 +0000125/// Message - The message to print to standard error.
126///
Reid Spencer708585a2007-02-09 03:08:06 +0000127static void PrintAndExit(const std::string &Message, int errcode = 1) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000128 errs() << progname << ": " << Message << "\n";
Reid Spencer708585a2007-02-09 03:08:06 +0000129 llvm_shutdown();
130 exit(errcode);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000131}
132
Reid Spencer3b726392007-04-29 23:59:47 +0000133static void PrintCommand(const std::vector<const char*> &args) {
134 std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
135 for (; I != E; ++I)
136 if (*I)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000137 outs() << "'" << *I << "'" << " ";
138 outs() << "\n"; outs().flush();
Reid Spencer3b726392007-04-29 23:59:47 +0000139}
140
Reid Spencer445564a2004-11-20 20:02:56 +0000141/// CopyEnv - This function takes an array of environment variables and makes a
142/// copy of it. This copy can then be manipulated any way the caller likes
143/// without affecting the process's real environment.
144///
145/// Inputs:
146/// envp - An array of C strings containing an environment.
147///
148/// Return value:
149/// NULL - An error occurred.
150///
151/// Otherwise, a pointer to a new array of C strings is returned. Every string
152/// in the array is a duplicate of the one in the original array (i.e. we do
153/// not copy the char *'s from one array to another).
154///
155static char ** CopyEnv(char ** const envp) {
156 // Count the number of entries in the old list;
157 unsigned entries; // The number of entries in the old environment list
158 for (entries = 0; envp[entries] != NULL; entries++)
159 /*empty*/;
160
161 // Add one more entry for the NULL pointer that ends the list.
162 ++entries;
163
164 // If there are no entries at all, just return NULL.
165 if (entries == 0)
166 return NULL;
167
168 // Allocate a new environment list.
169 char **newenv = new char* [entries];
170 if ((newenv = new char* [entries]) == NULL)
171 return NULL;
172
173 // Make a copy of the list. Don't forget the NULL that ends the list.
174 entries = 0;
175 while (envp[entries] != NULL) {
176 newenv[entries] = new char[strlen (envp[entries]) + 1];
177 strcpy (newenv[entries], envp[entries]);
178 ++entries;
179 }
180 newenv[entries] = NULL;
181
182 return newenv;
183}
184
185
186/// RemoveEnv - Remove the specified environment variable from the environment
187/// array.
188///
189/// Inputs:
190/// name - The name of the variable to remove. It cannot be NULL.
191/// envp - The array of environment variables. It cannot be NULL.
192///
193/// Notes:
194/// This is mainly done because functions to remove items from the environment
195/// are not available across all platforms. In particular, Solaris does not
196/// seem to have an unsetenv() function or a setenv() function (or they are
197/// undocumented if they do exist).
198///
199static void RemoveEnv(const char * name, char ** const envp) {
200 for (unsigned index=0; envp[index] != NULL; index++) {
201 // Find the first equals sign in the array and make it an EOS character.
202 char *p = strchr (envp[index], '=');
203 if (p == NULL)
204 continue;
205 else
206 *p = '\0';
207
208 // Compare the two strings. If they are equal, zap this string.
209 // Otherwise, restore it.
210 if (!strcmp(name, envp[index]))
211 *envp[index] = '\0';
212 else
213 *p = '=';
214 }
215
216 return;
217}
218
Gabor Greifa99be512007-07-05 17:07:56 +0000219/// GenerateBitcode - generates a bitcode file from the module provided
220void GenerateBitcode(Module* M, const std::string& FileName) {
Reid Spencer445564a2004-11-20 20:02:56 +0000221
Reid Spencer3b726392007-04-29 23:59:47 +0000222 if (Verbose)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000223 outs() << "Generating Bitcode To " << FileName << '\n';
Reid Spencer3b726392007-04-29 23:59:47 +0000224
Reid Spencer445564a2004-11-20 20:02:56 +0000225 // Create the output file.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000226 std::string ErrorInfo;
227 raw_fd_ostream Out(FileName.c_str(), /*Binary=*/true, /*Force=*/true,
228 ErrorInfo);
229 if (!ErrorInfo.empty())
230 PrintAndExit(ErrorInfo);
Reid Spencer445564a2004-11-20 20:02:56 +0000231
Gabor Greifa99be512007-07-05 17:07:56 +0000232 // Ensure that the bitcode file gets removed from the disk if we get a
Reid Spencer445564a2004-11-20 20:02:56 +0000233 // terminating signal.
234 sys::RemoveFileOnSignal(sys::Path(FileName));
235
236 // Write it out
Chris Lattner44dadff2007-05-06 09:29:57 +0000237 WriteBitcodeToFile(M, Out);
Reid Spencer445564a2004-11-20 20:02:56 +0000238
Gabor Greifa99be512007-07-05 17:07:56 +0000239 // Close the bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000240 Out.close();
241}
242
243/// GenerateAssembly - generates a native assembly language source file from the
Gabor Greifa99be512007-07-05 17:07:56 +0000244/// specified bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000245///
246/// Inputs:
Gabor Greifa99be512007-07-05 17:07:56 +0000247/// InputFilename - The name of the input bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000248/// OutputFilename - The name of the file to generate.
249/// llc - The pathname to use for LLC.
250/// envp - The environment to use when running LLC.
251///
252/// Return non-zero value on error.
253///
254static int GenerateAssembly(const std::string &OutputFilename,
255 const std::string &InputFilename,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000256 const sys::Path &llc,
257 std::string &ErrMsg ) {
Gabor Greifa99be512007-07-05 17:07:56 +0000258 // Run LLC to convert the bitcode file into assembly code.
Reid Spencerf6358c72004-12-19 18:00:56 +0000259 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000260 args.push_back(llc.c_str());
Argyrios Kyrtzidisca29dff2008-06-27 15:08:59 +0000261 // We will use GCC to assemble the program so set the assembly syntax to AT&T,
262 // regardless of what the target in the bitcode file is.
263 args.push_back("-x86-asm-syntax=att");
Chris Lattnerbf9add42005-04-10 20:59:38 +0000264 args.push_back("-f");
265 args.push_back("-o");
266 args.push_back(OutputFilename.c_str());
267 args.push_back(InputFilename.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000268 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000269
Reid Spencer3b726392007-04-29 23:59:47 +0000270 if (Verbose) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000271 outs() << "Generating Assembly With: \n";
Reid Spencer3b726392007-04-29 23:59:47 +0000272 PrintCommand(args);
273 }
274
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000275 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000276}
277
Gabor Greifa99be512007-07-05 17:07:56 +0000278/// GenerateCFile - generates a C source file from the specified bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000279static int GenerateCFile(const std::string &OutputFile,
280 const std::string &InputFile,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000281 const sys::Path &llc,
282 std::string& ErrMsg) {
Gabor Greifa99be512007-07-05 17:07:56 +0000283 // Run LLC to convert the bitcode file into C.
Reid Spencerf6358c72004-12-19 18:00:56 +0000284 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000285 args.push_back(llc.c_str());
286 args.push_back("-march=c");
287 args.push_back("-f");
288 args.push_back("-o");
289 args.push_back(OutputFile.c_str());
290 args.push_back(InputFile.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000291 args.push_back(0);
Reid Spencer3b726392007-04-29 23:59:47 +0000292
293 if (Verbose) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000294 outs() << "Generating C Source With: \n";
Reid Spencer3b726392007-04-29 23:59:47 +0000295 PrintCommand(args);
296 }
297
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000298 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000299}
300
Devang Patele2f8ad82006-06-27 18:07:29 +0000301/// GenerateNative - generates a native object file from the
Gabor Greifa99be512007-07-05 17:07:56 +0000302/// specified bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000303///
304/// Inputs:
Gabor Greifa99be512007-07-05 17:07:56 +0000305/// InputFilename - The name of the input bitcode file.
Reid Spencerc82a5da2007-04-04 06:34:22 +0000306/// OutputFilename - The name of the file to generate.
307/// NativeLinkItems - The native libraries, files, code with which to link
308/// LibPaths - The list of directories in which to find libraries.
Chris Lattner3992f522008-01-27 22:58:59 +0000309/// FrameworksPaths - The list of directories in which to find frameworks.
310/// Frameworks - The list of frameworks (dynamic libraries)
Reid Spencerc82a5da2007-04-04 06:34:22 +0000311/// gcc - The pathname to use for GGC.
312/// envp - A copy of the process's current environment.
Reid Spencer445564a2004-11-20 20:02:56 +0000313///
314/// Outputs:
315/// None.
316///
317/// Returns non-zero value on error.
318///
319static int GenerateNative(const std::string &OutputFilename,
320 const std::string &InputFilename,
Reid Spencer49521432006-11-11 11:54:25 +0000321 const Linker::ItemList &LinkItems,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000322 const sys::Path &gcc, char ** const envp,
323 std::string& ErrMsg) {
Reid Spencer445564a2004-11-20 20:02:56 +0000324 // Remove these environment variables from the environment of the
325 // programs that we will execute. It appears that GCC sets these
326 // environment variables so that the programs it uses can configure
327 // themselves identically.
328 //
329 // However, when we invoke GCC below, we want it to use its normal
330 // configuration. Hence, we must sanitize its environment.
331 char ** clean_env = CopyEnv(envp);
332 if (clean_env == NULL)
333 return 1;
334 RemoveEnv("LIBRARY_PATH", clean_env);
335 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
336 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
337 RemoveEnv("COMPILER_PATH", clean_env);
338 RemoveEnv("COLLECT_GCC", clean_env);
339
Reid Spencer445564a2004-11-20 20:02:56 +0000340
341 // Run GCC to assemble and link the program into native code.
342 //
343 // Note:
344 // We can't just assemble and link the file with the system assembler
345 // and linker because we don't know where to put the _start symbol.
346 // GCC mysteriously knows how to do it.
Chris Lattner3f931b82007-06-19 16:46:48 +0000347 std::vector<std::string> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000348 args.push_back(gcc.c_str());
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000349 args.push_back("-fno-strict-aliasing");
350 args.push_back("-O3");
351 args.push_back("-o");
Chris Lattner3f931b82007-06-19 16:46:48 +0000352 args.push_back(OutputFilename);
353 args.push_back(InputFilename);
Reid Spencer445564a2004-11-20 20:02:56 +0000354
Chris Lattner3992f522008-01-27 22:58:59 +0000355 // Add in the library and framework paths
Reid Spenceraf303d52006-06-07 23:03:13 +0000356 for (unsigned index = 0; index < LibPaths.size(); index++) {
Chris Lattner3992f522008-01-27 22:58:59 +0000357 args.push_back("-L" + LibPaths[index]);
358 }
359 for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
360 args.push_back("-F" + FrameworkPaths[index]);
Reid Spenceraf303d52006-06-07 23:03:13 +0000361 }
362
363 // Add the requested options
Chris Lattner03a1c7a2008-01-09 01:01:17 +0000364 for (unsigned index = 0; index < XLinker.size(); index++)
Chris Lattner3f931b82007-06-19 16:46:48 +0000365 args.push_back(XLinker[index]);
Reid Spenceraf303d52006-06-07 23:03:13 +0000366
Reid Spencer445564a2004-11-20 20:02:56 +0000367 // Add in the libraries to link.
Reid Spencer49521432006-11-11 11:54:25 +0000368 for (unsigned index = 0; index < LinkItems.size(); index++)
369 if (LinkItems[index].first != "crtend") {
Chris Lattner3f931b82007-06-19 16:46:48 +0000370 if (LinkItems[index].second)
371 args.push_back("-l" + LinkItems[index].first);
372 else
373 args.push_back(LinkItems[index].first);
Reid Spencerf6358c72004-12-19 18:00:56 +0000374 }
Reid Spenceraf303d52006-06-07 23:03:13 +0000375
Chris Lattner3992f522008-01-27 22:58:59 +0000376 // Add in frameworks to link.
377 for (unsigned index = 0; index < Frameworks.size(); index++) {
378 args.push_back("-framework");
379 args.push_back(Frameworks[index]);
380 }
Chris Lattner3f931b82007-06-19 16:46:48 +0000381
382 // Now that "args" owns all the std::strings for the arguments, call the c_str
383 // method to get the underlying string array. We do this game so that the
384 // std::string array is guaranteed to outlive the const char* array.
385 std::vector<const char *> Args;
386 for (unsigned i = 0, e = args.size(); i != e; ++i)
387 Args.push_back(args[i].c_str());
388 Args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000389
Reid Spencer3b726392007-04-29 23:59:47 +0000390 if (Verbose) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000391 outs() << "Generating Native Executable With:\n";
Chris Lattner3f931b82007-06-19 16:46:48 +0000392 PrintCommand(Args);
Reid Spencer3b726392007-04-29 23:59:47 +0000393 }
394
Reid Spencer445564a2004-11-20 20:02:56 +0000395 // Run the compiler to assembly and link together the program.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000396 int R = sys::Program::ExecuteAndWait(
Chris Lattner3f931b82007-06-19 16:46:48 +0000397 gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
Chris Lattner2f863622006-05-14 18:38:13 +0000398 delete [] clean_env;
399 return R;
Reid Spencer445564a2004-11-20 20:02:56 +0000400}
401
Reid Spencerc0af3f02004-09-13 01:27:53 +0000402/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
Gabor Greifa99be512007-07-05 17:07:56 +0000403/// bitcode file for the program.
Reid Spencerc0af3f02004-09-13 01:27:53 +0000404static void EmitShellScript(char **argv) {
Reid Spencer3b726392007-04-29 23:59:47 +0000405 if (Verbose)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000406 outs() << "Emitting Shell Script\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000407#if defined(_WIN32) || defined(__CYGWIN__)
408 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
409 // support windows systems, we copy the llvm-stub.exe executable from the
410 // build tree to the destination file.
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000411 std::string ErrMsg;
Reid Spencer8d8b41d2004-12-22 13:50:17 +0000412 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
Reid Spencer708585a2007-02-09 03:08:06 +0000413 if (llvmstub.isEmpty())
414 PrintAndExit("Could not find llvm-stub.exe executable!");
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000415
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000416 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000417 PrintAndExit(ErrMsg);
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000418
Reid Spencerc0af3f02004-09-13 01:27:53 +0000419 return;
420#endif
421
422 // Output the script to start the program...
Dan Gohmanac95cc72009-07-16 15:30:09 +0000423 std::string ErrorInfo;
424 raw_fd_ostream Out2(OutputFilename.c_str(), /*Binary=*/false, /*Force=*/true,
425 ErrorInfo);
426 if (!ErrorInfo.empty())
427 PrintAndExit(ErrorInfo);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000428
429 Out2 << "#!/bin/sh\n";
430 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
431 Out2 << "lli=${LLVMINTERP-lli}\n";
432 Out2 << "exec $lli \\\n";
433 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
434 LibPaths.push_back("/lib");
435 LibPaths.push_back("/usr/lib");
436 LibPaths.push_back("/usr/X11R6/lib");
437 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
438 // shared object at all! See RH 8: plain text.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000439 std::vector<std::string>::iterator libc =
Reid Spencerc0af3f02004-09-13 01:27:53 +0000440 std::find(Libraries.begin(), Libraries.end(), "c");
441 if (libc != Libraries.end()) Libraries.erase(libc);
442 // List all the shared object (native) libraries this executable will need
443 // on the command line, so that we don't have to do this manually!
Misha Brukman3da94ae2005-04-22 00:00:37 +0000444 for (std::vector<std::string>::iterator i = Libraries.begin(),
Reid Spencerc0af3f02004-09-13 01:27:53 +0000445 e = Libraries.end(); i != e; ++i) {
Chris Lattner5d5a8972009-01-05 19:01:32 +0000446 // try explicit -L arguments first:
447 sys::Path FullLibraryPath;
448 for (cl::list<std::string>::const_iterator P = LibPaths.begin(),
449 E = LibPaths.end(); P != E; ++P) {
450 FullLibraryPath = *P;
451 FullLibraryPath.appendComponent("lib" + *i);
452 FullLibraryPath.appendSuffix(&(LTDL_SHLIB_EXT[1]));
453 if (!FullLibraryPath.isEmpty()) {
454 if (!FullLibraryPath.isDynamicLibrary()) {
455 // Not a native shared library; mark as invalid
456 FullLibraryPath = sys::Path();
457 } else break;
458 }
459 }
460 if (FullLibraryPath.isEmpty())
461 FullLibraryPath = sys::Path::FindLibrary(*i);
462 if (!FullLibraryPath.isEmpty())
Reid Spencerc4064132004-12-13 03:01:14 +0000463 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000464 }
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +0000465 Out2 << " " << BitcodeOutputFilename << " ${1+\"$@\"}\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000466 Out2.close();
467}
468
Reid Spencerc4064132004-12-13 03:01:14 +0000469// BuildLinkItems -- This function generates a LinkItemList for the LinkItems
470// linker function by combining the Files and Libraries in the order they were
471// declared on the command line.
472static void BuildLinkItems(
473 Linker::ItemList& Items,
474 const cl::list<std::string>& Files,
475 const cl::list<std::string>& Libraries) {
476
Misha Brukman3da94ae2005-04-22 00:00:37 +0000477 // Build the list of linkage items for LinkItems.
Reid Spencerc4064132004-12-13 03:01:14 +0000478
479 cl::list<std::string>::const_iterator fileIt = Files.begin();
480 cl::list<std::string>::const_iterator libIt = Libraries.begin();
481
482 int libPos = -1, filePos = -1;
Reid Spencer05f7e792004-12-13 17:18:19 +0000483 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
Reid Spencerc4064132004-12-13 03:01:14 +0000484 if (libIt != Libraries.end())
485 libPos = Libraries.getPosition(libIt - Libraries.begin());
486 else
487 libPos = -1;
488 if (fileIt != Files.end())
489 filePos = Files.getPosition(fileIt - Files.begin());
490 else
491 filePos = -1;
492
493 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
494 // Add a source file
495 Items.push_back(std::make_pair(*fileIt++, false));
496 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
497 // Add a library
498 Items.push_back(std::make_pair(*libIt++, true));
Reid Spencerc4064132004-12-13 03:01:14 +0000499 }
500 }
501}
502
Reid Spencer445564a2004-11-20 20:02:56 +0000503// Rightly this should go in a header file but it just seems such a waste.
504namespace llvm {
505extern void Optimize(Module*);
506}
507
Reid Spencerc0af3f02004-09-13 01:27:53 +0000508int main(int argc, char **argv, char **envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000509 // Print a stack trace if we signal out.
510 sys::PrintStackTraceOnErrorSignal();
511 PrettyStackTraceProgram X(argc, argv);
Owen Anderson8b477ed2009-07-01 16:58:40 +0000512
Owen Anderson0d7c6952009-07-15 22:16:10 +0000513 LLVMContext &Context = getGlobalContext();
Chris Lattnercc14d252009-03-06 05:34:10 +0000514 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000515 try {
516 // Initial global variable above for convenience printing of program name.
517 progname = sys::Path(argv[0]).getBasename();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000518
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000519 // Parse the command line options
Dan Gohman82a13c92007-10-08 15:45:12 +0000520 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
Reid Spencerc0af3f02004-09-13 01:27:53 +0000521
Reid Spencer49521432006-11-11 11:54:25 +0000522 // Construct a Linker (now that Verbose is set)
Owen Anderson31895e72009-07-01 21:22:36 +0000523 Linker TheLinker(progname, OutputFilename, Context, Verbose);
Reid Spencerc82a5da2007-04-04 06:34:22 +0000524
Gabor Greifa99be512007-07-05 17:07:56 +0000525 // Keep track of the native link items (versus the bitcode items)
Reid Spencerc82a5da2007-04-04 06:34:22 +0000526 Linker::ItemList NativeLinkItems;
Reid Spencer49521432006-11-11 11:54:25 +0000527
528 // Add library paths to the linker
Reid Spencer78df5c32006-03-06 06:38:19 +0000529 TheLinker.addPaths(LibPaths);
530 TheLinker.addSystemPaths();
531
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000532 // Remove any consecutive duplicates of the same library...
533 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
534 Libraries.end());
Reid Spencerc0af3f02004-09-13 01:27:53 +0000535
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000536 if (LinkAsLibrary) {
537 std::vector<sys::Path> Files;
538 for (unsigned i = 0; i < InputFilenames.size(); ++i )
539 Files.push_back(sys::Path(InputFilenames[i]));
540 if (TheLinker.LinkInFiles(Files))
541 return 1; // Error already printed
Reid Spencer6b463b22004-12-08 05:17:40 +0000542
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000543 // The libraries aren't linked in but are noted as "dependent" in the
544 // module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000545 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000546 E = Libraries.end(); I != E ; ++I) {
547 TheLinker.getModule()->addLibrary(*I);
548 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000549 } else {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000550 // Build a list of the items from our command line
551 Linker::ItemList Items;
552 BuildLinkItems(Items, InputFilenames, Libraries);
553
554 // Link all the items together
Reid Spencerc82a5da2007-04-04 06:34:22 +0000555 if (TheLinker.LinkInItems(Items, NativeLinkItems) )
Reid Spencer708585a2007-02-09 03:08:06 +0000556 return 1; // Error already printed
Reid Spencerc0af3f02004-09-13 01:27:53 +0000557 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000558
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000559 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
560
561 // Optimize the module
562 Optimize(Composite.get());
563
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000564#if defined(_WIN32) || defined(__CYGWIN__)
565 if (!LinkAsLibrary) {
Argyrios Kyrtzidis48cca1f2008-06-15 15:20:16 +0000566 // Default to "a.exe" instead of "a.out".
567 if (OutputFilename.getNumOccurrences() == 0)
568 OutputFilename = "a.exe";
569
570 // If there is no suffix add an "exe" one.
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000571 sys::Path ExeFile( OutputFilename );
Argyrios Kyrtzidis48cca1f2008-06-15 15:20:16 +0000572 if (ExeFile.getSuffix() == "") {
573 ExeFile.appendSuffix("exe");
574 OutputFilename = ExeFile.toString();
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000575 }
576 }
577#endif
578
Gabor Greifa99be512007-07-05 17:07:56 +0000579 // Generate the bitcode for the optimized module.
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +0000580 // If -b wasn't specified, use the name specified
581 // with -o to construct BitcodeOutputFilename.
582 if (BitcodeOutputFilename.empty()) {
583 BitcodeOutputFilename = OutputFilename;
584 if (!LinkAsLibrary) BitcodeOutputFilename += ".bc";
585 }
Argyrios Kyrtzidis5b90a722008-06-15 12:01:16 +0000586
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +0000587 GenerateBitcode(Composite.get(), BitcodeOutputFilename);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000588
589 // If we are not linking a library, generate either a native executable
590 // or a JIT shell script, depending upon what the user wants.
591 if (!LinkAsLibrary) {
Reid Spencer73a74be2005-12-21 05:03:23 +0000592 // If the user wants to run a post-link optimization, run it now.
593 if (!PostLinkOpts.empty()) {
594 std::vector<std::string> opts = PostLinkOpts;
595 for (std::vector<std::string>::iterator I = opts.begin(),
596 E = opts.end(); I != E; ++I) {
597 sys::Path prog(*I);
598 if (!prog.canExecute()) {
599 prog = sys::Program::FindProgramByName(*I);
600 if (prog.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000601 PrintAndExit(std::string("Optimization program '") + *I +
Reid Spencer73a74be2005-12-21 05:03:23 +0000602 "' is not found or not executable.");
603 }
604 // Get the program arguments
605 sys::Path tmp_output("opt_result");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000606 std::string ErrMsg;
Reid Spencer708585a2007-02-09 03:08:06 +0000607 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
608 PrintAndExit(ErrMsg);
609
Reid Spencer73a74be2005-12-21 05:03:23 +0000610 const char* args[4];
611 args[0] = I->c_str();
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +0000612 args[1] = BitcodeOutputFilename.c_str();
Reid Spencer73a74be2005-12-21 05:03:23 +0000613 args[2] = tmp_output.c_str();
614 args[3] = 0;
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000615 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
Gabor Greifa99be512007-07-05 17:07:56 +0000616 if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +0000617 sys::Path target(BitcodeOutputFilename);
Reid Spencer73a74be2005-12-21 05:03:23 +0000618 target.eraseFromDisk();
Reid Spencer708585a2007-02-09 03:08:06 +0000619 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
620 PrintAndExit(ErrMsg, 2);
Reid Spencer73a74be2005-12-21 05:03:23 +0000621 } else
Gabor Greifa99be512007-07-05 17:07:56 +0000622 PrintAndExit("Post-link optimization output is not bitcode");
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000623 } else {
Reid Spencer708585a2007-02-09 03:08:06 +0000624 PrintAndExit(ErrMsg);
Reid Spencer73a74be2005-12-21 05:03:23 +0000625 }
626 }
627 }
628
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000629 // If the user wants to generate a native executable, compile it from the
Gabor Greifa99be512007-07-05 17:07:56 +0000630 // bitcode file.
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000631 //
Gabor Greifa99be512007-07-05 17:07:56 +0000632 // Otherwise, create a script that will run the bitcode through the JIT.
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000633 if (Native) {
634 // Name of the Assembly Language output file
635 sys::Path AssemblyFile ( OutputFilename);
636 AssemblyFile.appendSuffix("s");
637
638 // Mark the output files for removal if we get an interrupt.
639 sys::RemoveFileOnSignal(AssemblyFile);
640 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
641
642 // Determine the locations of the llc and gcc programs.
643 sys::Path llc = FindExecutable("llc", argv[0]);
644 if (llc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000645 PrintAndExit("Failed to find llc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000646
647 sys::Path gcc = FindExecutable("gcc", argv[0]);
648 if (gcc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000649 PrintAndExit("Failed to find gcc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000650
Gabor Greifa99be512007-07-05 17:07:56 +0000651 // Generate an assembly language file for the bitcode.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000652 std::string ErrMsg;
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +0000653 if (0 != GenerateAssembly(AssemblyFile.toString(), BitcodeOutputFilename,
Reid Spencer708585a2007-02-09 03:08:06 +0000654 llc, ErrMsg))
655 PrintAndExit(ErrMsg);
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000656
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000657 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
Reid Spencerc82a5da2007-04-04 06:34:22 +0000658 NativeLinkItems, gcc, envp, ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000659 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000660
661 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000662 AssemblyFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000663 } else if (NativeCBE) {
664 sys::Path CFile (OutputFilename);
665 CFile.appendSuffix("cbe.c");
666
667 // Mark the output files for removal if we get an interrupt.
668 sys::RemoveFileOnSignal(CFile);
669 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
670
671 // Determine the locations of the llc and gcc programs.
672 sys::Path llc = FindExecutable("llc", argv[0]);
673 if (llc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000674 PrintAndExit("Failed to find llc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000675
676 sys::Path gcc = FindExecutable("gcc", argv[0]);
677 if (gcc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000678 PrintAndExit("Failed to find gcc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000679
Gabor Greifa99be512007-07-05 17:07:56 +0000680 // Generate an assembly language file for the bitcode.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000681 std::string ErrMsg;
682 if (0 != GenerateCFile(
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +0000683 CFile.toString(), BitcodeOutputFilename, llc, ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000684 PrintAndExit(ErrMsg);
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000685
Reid Spencerc82a5da2007-04-04 06:34:22 +0000686 if (0 != GenerateNative(OutputFilename, CFile.toString(),
687 NativeLinkItems, gcc, envp, ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000688 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000689
690 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000691 CFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000692
693 } else {
694 EmitShellScript(argv);
695 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000696
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000697 // Make the script executable...
Reid Spencere1647f42006-08-22 23:27:23 +0000698 std::string ErrMsg;
Reid Spencer708585a2007-02-09 03:08:06 +0000699 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
700 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000701
Gabor Greifa99be512007-07-05 17:07:56 +0000702 // Make the bitcode file readable and directly executable in LLEE as well
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +0000703 if (sys::Path(BitcodeOutputFilename).makeExecutableOnDisk(&ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000704 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000705
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +0000706 if (sys::Path(BitcodeOutputFilename).makeReadableOnDisk(&ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000707 PrintAndExit(ErrMsg);
708 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000709 } catch (const std::string& msg) {
Reid Spencer708585a2007-02-09 03:08:06 +0000710 PrintAndExit(msg,2);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000711 } catch (...) {
Reid Spencer708585a2007-02-09 03:08:06 +0000712 PrintAndExit("Unexpected unknown exception occurred.", 2);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000713 }
Reid Spencer708585a2007-02-09 03:08:06 +0000714
715 // Graceful exit
716 return 0;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000717}