It's not necessary to call raw_ostream::close explicitly on automatic
[oota-llvm.git] / tools / llvm-ld / llvm-ld.cpp
1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility is intended to be compatible with GCC, and follows standard
11 // system 'ld' conventions.  As such, the default output file is ./a.out.
12 // Additionally, this program outputs a shell script that is used to invoke LLI
13 // to execute the program.  In this manner, the generated executable (a.out for
14 // example), is directly executable, whereas the bitcode file actually lives in
15 // the a.out.bc file generated by this program.
16 //
17 // Note that if someone (or a script) deletes the executable program generated,
18 // the .bc file will be left around.  Considering that this is a temporary hack,
19 // I'm not too worried about this.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "llvm/LinkAllVMCore.h"
24 #include "llvm/Linker.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/System/Program.h"
27 #include "llvm/Module.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Bitcode/ReaderWriter.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/SystemUtils.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/System/Signals.h"
40 #include "llvm/Config/config.h"
41 #include <memory>
42 #include <cstring>
43 using namespace llvm;
44
45 // Rightly this should go in a header file but it just seems such a waste.
46 namespace llvm {
47 extern void Optimize(Module*);
48 }
49
50 // Input/Output Options
51 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
52   cl::desc("<input bitcode files>"));
53
54 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
55   cl::desc("Override output filename"),
56   cl::value_desc("filename"));
57
58 static cl::opt<std::string> BitcodeOutputFilename("b", cl::init(""),
59   cl::desc("Override bitcode output filename"),
60   cl::value_desc("filename"));
61
62 static cl::opt<bool> Verbose("v",
63   cl::desc("Print information about actions taken"));
64
65 static cl::list<std::string> LibPaths("L", cl::Prefix,
66   cl::desc("Specify a library search path"),
67   cl::value_desc("directory"));
68
69 static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
70   cl::desc("Specify a framework search path"),
71   cl::value_desc("directory"));
72
73 static cl::list<std::string> Libraries("l", cl::Prefix,
74   cl::desc("Specify libraries to link to"),
75   cl::value_desc("library prefix"));
76
77 static cl::list<std::string> Frameworks("framework",
78   cl::desc("Specify frameworks to link to"),
79   cl::value_desc("framework"));
80
81 // Options to control the linking, optimization, and code gen processes
82 static cl::opt<bool> LinkAsLibrary("link-as-library",
83   cl::desc("Link the .bc files together as a library, not an executable"));
84
85 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
86   cl::desc("Alias for -link-as-library"));
87
88 static cl::opt<bool> Native("native",
89   cl::desc("Generate a native binary instead of a shell script"));
90
91 static cl::opt<bool>NativeCBE("native-cbe",
92   cl::desc("Generate a native binary with the C backend and GCC"));
93
94 static cl::list<std::string> PostLinkOpts("post-link-opts",
95   cl::value_desc("path"),
96   cl::desc("Run one or more optimization programs after linking"));
97
98 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
99   cl::desc("Pass options to the system linker"));
100
101 // Compatibility options that llvm-ld ignores but are supported for 
102 // compatibility with LD
103 static cl::opt<std::string> CO3("soname", cl::Hidden,
104   cl::desc("Compatibility option: ignored"));
105
106 static cl::opt<std::string> CO4("version-script", cl::Hidden,
107   cl::desc("Compatibility option: ignored"));
108
109 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
110   cl::desc("Compatibility option: ignored"));
111
112 static  cl::opt<std::string> CO6("h", cl::Hidden,
113   cl::desc("Compatibility option: ignored"));
114
115 static cl::opt<bool> CO7("start-group", cl::Hidden, 
116   cl::desc("Compatibility option: ignored"));
117
118 static cl::opt<bool> CO8("end-group", cl::Hidden, 
119   cl::desc("Compatibility option: ignored"));
120
121 static cl::opt<std::string> CO9("m", cl::Hidden, 
122   cl::desc("Compatibility option: ignored"));
123
124 /// This is just for convenience so it doesn't have to be passed around
125 /// everywhere.
126 static std::string progname;
127
128 /// PrintAndExit - Prints a message to standard error and exits with error code
129 ///
130 /// Inputs:
131 ///  Message  - The message to print to standard error.
132 ///
133 static void PrintAndExit(const std::string &Message, Module *M, int errcode = 1) {
134   errs() << progname << ": " << Message << "\n";
135   delete M;
136   llvm_shutdown();
137   exit(errcode);
138 }
139
140 static void PrintCommand(const std::vector<const char*> &args) {
141   std::vector<const char*>::const_iterator I = args.begin(), E = args.end(); 
142   for (; I != E; ++I)
143     if (*I)
144       outs() << "'" << *I << "'" << " ";
145   outs() << "\n"; outs().flush();
146 }
147
148 /// CopyEnv - This function takes an array of environment variables and makes a
149 /// copy of it.  This copy can then be manipulated any way the caller likes
150 /// without affecting the process's real environment.
151 ///
152 /// Inputs:
153 ///  envp - An array of C strings containing an environment.
154 ///
155 /// Return value:
156 ///  NULL - An error occurred.
157 ///
158 ///  Otherwise, a pointer to a new array of C strings is returned.  Every string
159 ///  in the array is a duplicate of the one in the original array (i.e. we do
160 ///  not copy the char *'s from one array to another).
161 ///
162 static char ** CopyEnv(char ** const envp) {
163   // Count the number of entries in the old list;
164   unsigned entries;   // The number of entries in the old environment list
165   for (entries = 0; envp[entries] != NULL; entries++)
166     /*empty*/;
167
168   // Add one more entry for the NULL pointer that ends the list.
169   ++entries;
170
171   // If there are no entries at all, just return NULL.
172   if (entries == 0)
173     return NULL;
174
175   // Allocate a new environment list.
176   char **newenv = new char* [entries];
177   if ((newenv = new char* [entries]) == NULL)
178     return NULL;
179
180   // Make a copy of the list.  Don't forget the NULL that ends the list.
181   entries = 0;
182   while (envp[entries] != NULL) {
183     size_t len = strlen(envp[entries]) + 1;
184     newenv[entries] = new char[len];
185     memcpy(newenv[entries], envp[entries], len);
186     ++entries;
187   }
188   newenv[entries] = NULL;
189
190   return newenv;
191 }
192
193
194 /// RemoveEnv - Remove the specified environment variable from the environment
195 /// array.
196 ///
197 /// Inputs:
198 ///  name - The name of the variable to remove.  It cannot be NULL.
199 ///  envp - The array of environment variables.  It cannot be NULL.
200 ///
201 /// Notes:
202 ///  This is mainly done because functions to remove items from the environment
203 ///  are not available across all platforms.  In particular, Solaris does not
204 ///  seem to have an unsetenv() function or a setenv() function (or they are
205 ///  undocumented if they do exist).
206 ///
207 static void RemoveEnv(const char * name, char ** const envp) {
208   for (unsigned index=0; envp[index] != NULL; index++) {
209     // Find the first equals sign in the array and make it an EOS character.
210     char *p = strchr (envp[index], '=');
211     if (p == NULL)
212       continue;
213     else
214       *p = '\0';
215
216     // Compare the two strings.  If they are equal, zap this string.
217     // Otherwise, restore it.
218     if (!strcmp(name, envp[index]))
219       *envp[index] = '\0';
220     else
221       *p = '=';
222   }
223
224   return;
225 }
226
227 /// GenerateBitcode - generates a bitcode file from the module provided
228 void GenerateBitcode(Module* M, const std::string& FileName) {
229
230   if (Verbose)
231     outs() << "Generating Bitcode To " << FileName << '\n';
232
233   // Create the output file.
234   std::string ErrorInfo;
235   raw_fd_ostream Out(FileName.c_str(), ErrorInfo,
236                      raw_fd_ostream::F_Binary);
237   if (!ErrorInfo.empty())
238     PrintAndExit(ErrorInfo, M);
239
240   // Ensure that the bitcode file gets removed from the disk if we get a
241   // terminating signal.
242   sys::RemoveFileOnSignal(sys::Path(FileName));
243
244   // Write it out
245   WriteBitcodeToFile(M, Out);
246 }
247
248 /// GenerateAssembly - generates a native assembly language source file from the
249 /// specified bitcode file.
250 ///
251 /// Inputs:
252 ///  InputFilename  - The name of the input bitcode file.
253 ///  OutputFilename - The name of the file to generate.
254 ///  llc            - The pathname to use for LLC.
255 ///  envp           - The environment to use when running LLC.
256 ///
257 /// Return non-zero value on error.
258 ///
259 static int GenerateAssembly(const std::string &OutputFilename,
260                             const std::string &InputFilename,
261                             const sys::Path &llc,
262                             std::string &ErrMsg ) {
263   // Run LLC to convert the bitcode file into assembly code.
264   std::vector<const char*> args;
265   args.push_back(llc.c_str());
266   // We will use GCC to assemble the program so set the assembly syntax to AT&T,
267   // regardless of what the target in the bitcode file is.
268   args.push_back("-x86-asm-syntax=att");
269   args.push_back("-f");
270   args.push_back("-o");
271   args.push_back(OutputFilename.c_str());
272   args.push_back(InputFilename.c_str());
273   args.push_back(0);
274
275   if (Verbose) {
276     outs() << "Generating Assembly With: \n";
277     PrintCommand(args);
278   }
279
280   return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
281 }
282
283 /// GenerateCFile - generates a C source file from the specified bitcode file.
284 static int GenerateCFile(const std::string &OutputFile,
285                          const std::string &InputFile,
286                          const sys::Path &llc,
287                          std::string& ErrMsg) {
288   // Run LLC to convert the bitcode file into C.
289   std::vector<const char*> args;
290   args.push_back(llc.c_str());
291   args.push_back("-march=c");
292   args.push_back("-f");
293   args.push_back("-o");
294   args.push_back(OutputFile.c_str());
295   args.push_back(InputFile.c_str());
296   args.push_back(0);
297
298   if (Verbose) {
299     outs() << "Generating C Source With: \n";
300     PrintCommand(args);
301   }
302
303   return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
304 }
305
306 /// GenerateNative - generates a native object file from the
307 /// specified bitcode file.
308 ///
309 /// Inputs:
310 ///  InputFilename   - The name of the input bitcode file.
311 ///  OutputFilename  - The name of the file to generate.
312 ///  NativeLinkItems - The native libraries, files, code with which to link
313 ///  LibPaths        - The list of directories in which to find libraries.
314 ///  FrameworksPaths - The list of directories in which to find frameworks.
315 ///  Frameworks      - The list of frameworks (dynamic libraries)
316 ///  gcc             - The pathname to use for GGC.
317 ///  envp            - A copy of the process's current environment.
318 ///
319 /// Outputs:
320 ///  None.
321 ///
322 /// Returns non-zero value on error.
323 ///
324 static int GenerateNative(const std::string &OutputFilename,
325                           const std::string &InputFilename,
326                           const Linker::ItemList &LinkItems,
327                           const sys::Path &gcc, char ** const envp,
328                           std::string& ErrMsg) {
329   // Remove these environment variables from the environment of the
330   // programs that we will execute.  It appears that GCC sets these
331   // environment variables so that the programs it uses can configure
332   // themselves identically.
333   //
334   // However, when we invoke GCC below, we want it to use its normal
335   // configuration.  Hence, we must sanitize its environment.
336   char ** clean_env = CopyEnv(envp);
337   if (clean_env == NULL)
338     return 1;
339   RemoveEnv("LIBRARY_PATH", clean_env);
340   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
341   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
342   RemoveEnv("COMPILER_PATH", clean_env);
343   RemoveEnv("COLLECT_GCC", clean_env);
344
345
346   // Run GCC to assemble and link the program into native code.
347   //
348   // Note:
349   //  We can't just assemble and link the file with the system assembler
350   //  and linker because we don't know where to put the _start symbol.
351   //  GCC mysteriously knows how to do it.
352   std::vector<std::string> args;
353   args.push_back(gcc.c_str());
354   args.push_back("-fno-strict-aliasing");
355   args.push_back("-O3");
356   args.push_back("-o");
357   args.push_back(OutputFilename);
358   args.push_back(InputFilename);
359
360   // Add in the library and framework paths
361   for (unsigned index = 0; index < LibPaths.size(); index++) {
362     args.push_back("-L" + LibPaths[index]);
363   }
364   for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
365     args.push_back("-F" + FrameworkPaths[index]);
366   }
367
368   // Add the requested options
369   for (unsigned index = 0; index < XLinker.size(); index++)
370     args.push_back(XLinker[index]);
371
372   // Add in the libraries to link.
373   for (unsigned index = 0; index < LinkItems.size(); index++)
374     if (LinkItems[index].first != "crtend") {
375       if (LinkItems[index].second)
376         args.push_back("-l" + LinkItems[index].first);
377       else
378         args.push_back(LinkItems[index].first);
379     }
380
381   // Add in frameworks to link.
382   for (unsigned index = 0; index < Frameworks.size(); index++) {
383     args.push_back("-framework");
384     args.push_back(Frameworks[index]);
385   }
386       
387   // Now that "args" owns all the std::strings for the arguments, call the c_str
388   // method to get the underlying string array.  We do this game so that the
389   // std::string array is guaranteed to outlive the const char* array.
390   std::vector<const char *> Args;
391   for (unsigned i = 0, e = args.size(); i != e; ++i)
392     Args.push_back(args[i].c_str());
393   Args.push_back(0);
394
395   if (Verbose) {
396     outs() << "Generating Native Executable With:\n";
397     PrintCommand(Args);
398   }
399
400   // Run the compiler to assembly and link together the program.
401   int R = sys::Program::ExecuteAndWait(
402     gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
403   delete [] clean_env;
404   return R;
405 }
406
407 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
408 /// bitcode file for the program.
409 static void EmitShellScript(char **argv, Module *M) {
410   if (Verbose)
411     outs() << "Emitting Shell Script\n";
412 #if defined(_WIN32) || defined(__CYGWIN__)
413   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
414   // support windows systems, we copy the llvm-stub.exe executable from the
415   // build tree to the destination file.
416   std::string ErrMsg;  
417   sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0],
418                                       (void *)(intptr_t)&Optimize);
419   if (llvmstub.isEmpty())
420     PrintAndExit("Could not find llvm-stub.exe executable!", M);
421
422   if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
423     PrintAndExit(ErrMsg, M);
424
425   return;
426 #endif
427
428   // Output the script to start the program...
429   std::string ErrorInfo;
430   raw_fd_ostream Out2(OutputFilename.c_str(), ErrorInfo);
431   if (!ErrorInfo.empty())
432     PrintAndExit(ErrorInfo, M);
433
434   Out2 << "#!/bin/sh\n";
435   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
436   Out2 << "lli=${LLVMINTERP-lli}\n";
437   Out2 << "exec $lli \\\n";
438   // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
439   LibPaths.push_back("/lib");
440   LibPaths.push_back("/usr/lib");
441   LibPaths.push_back("/usr/X11R6/lib");
442   // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
443   // shared object at all! See RH 8: plain text.
444   std::vector<std::string>::iterator libc =
445     std::find(Libraries.begin(), Libraries.end(), "c");
446   if (libc != Libraries.end()) Libraries.erase(libc);
447   // List all the shared object (native) libraries this executable will need
448   // on the command line, so that we don't have to do this manually!
449   for (std::vector<std::string>::iterator i = Libraries.begin(),
450          e = Libraries.end(); i != e; ++i) {
451     // try explicit -L arguments first:
452     sys::Path FullLibraryPath;
453     for (cl::list<std::string>::const_iterator P = LibPaths.begin(),
454            E = LibPaths.end(); P != E; ++P) {
455       FullLibraryPath = *P;
456       FullLibraryPath.appendComponent("lib" + *i);
457       FullLibraryPath.appendSuffix(&(LTDL_SHLIB_EXT[1]));
458       if (!FullLibraryPath.isEmpty()) {
459         if (!FullLibraryPath.isDynamicLibrary()) {
460           // Not a native shared library; mark as invalid
461           FullLibraryPath = sys::Path();
462         } else break;
463       }
464     }
465     if (FullLibraryPath.isEmpty())
466       FullLibraryPath = sys::Path::FindLibrary(*i);
467     if (!FullLibraryPath.isEmpty())
468       Out2 << "    -load=" << FullLibraryPath.str() << " \\\n";
469   }
470   Out2 << "    "  << BitcodeOutputFilename << " ${1+\"$@\"}\n";
471 }
472
473 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
474 // linker function by combining the Files and Libraries in the order they were
475 // declared on the command line.
476 static void BuildLinkItems(
477   Linker::ItemList& Items,
478   const cl::list<std::string>& Files,
479   const cl::list<std::string>& Libraries) {
480
481   // Build the list of linkage items for LinkItems.
482
483   cl::list<std::string>::const_iterator fileIt = Files.begin();
484   cl::list<std::string>::const_iterator libIt  = Libraries.begin();
485
486   int libPos = -1, filePos = -1;
487   while ( libIt != Libraries.end() || fileIt != Files.end() ) {
488     if (libIt != Libraries.end())
489       libPos = Libraries.getPosition(libIt - Libraries.begin());
490     else
491       libPos = -1;
492     if (fileIt != Files.end())
493       filePos = Files.getPosition(fileIt - Files.begin());
494     else
495       filePos = -1;
496
497     if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
498       // Add a source file
499       Items.push_back(std::make_pair(*fileIt++, false));
500     } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
501       // Add a library
502       Items.push_back(std::make_pair(*libIt++, true));
503     }
504   }
505 }
506
507 int main(int argc, char **argv, char **envp) {
508   // Print a stack trace if we signal out.
509   sys::PrintStackTraceOnErrorSignal();
510   PrettyStackTraceProgram X(argc, argv);
511
512   LLVMContext &Context = getGlobalContext();
513   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
514   
515   // Initial global variable above for convenience printing of program name.
516   progname = sys::Path(argv[0]).getBasename();
517
518   // Parse the command line options
519   cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
520
521   // Construct a Linker (now that Verbose is set)
522   Linker TheLinker(progname, OutputFilename, Context, Verbose);
523
524   // Keep track of the native link items (versus the bitcode items)
525   Linker::ItemList NativeLinkItems;
526
527   // Add library paths to the linker
528   TheLinker.addPaths(LibPaths);
529   TheLinker.addSystemPaths();
530
531   // Remove any consecutive duplicates of the same library...
532   Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
533                   Libraries.end());
534
535   if (LinkAsLibrary) {
536     std::vector<sys::Path> Files;
537     for (unsigned i = 0; i < InputFilenames.size(); ++i )
538       Files.push_back(sys::Path(InputFilenames[i]));
539     if (TheLinker.LinkInFiles(Files))
540       return 1; // Error already printed
541
542     // The libraries aren't linked in but are noted as "dependent" in the
543     // module.
544     for (cl::list<std::string>::const_iterator I = Libraries.begin(),
545          E = Libraries.end(); I != E ; ++I) {
546       TheLinker.getModule()->addLibrary(*I);
547     }
548   } else {
549     // Build a list of the items from our command line
550     Linker::ItemList Items;
551     BuildLinkItems(Items, InputFilenames, Libraries);
552
553     // Link all the items together
554     if (TheLinker.LinkInItems(Items, NativeLinkItems) )
555       return 1; // Error already printed
556   }
557
558   std::auto_ptr<Module> Composite(TheLinker.releaseModule());
559
560   // Optimize the module
561   Optimize(Composite.get());
562
563 #if defined(_WIN32) || defined(__CYGWIN__)
564   if (!LinkAsLibrary) {
565     // Default to "a.exe" instead of "a.out".
566     if (OutputFilename.getNumOccurrences() == 0)
567       OutputFilename = "a.exe";
568
569     // If there is no suffix add an "exe" one.
570     sys::Path ExeFile( OutputFilename );
571     if (ExeFile.getSuffix() == "") {
572       ExeFile.appendSuffix("exe");
573       OutputFilename = ExeFile.str();
574     }
575   }
576 #endif
577
578   // Generate the bitcode for the optimized module.
579   // If -b wasn't specified, use the name specified
580   // with -o to construct BitcodeOutputFilename.
581   if (BitcodeOutputFilename.empty()) {
582     BitcodeOutputFilename = OutputFilename;
583     if (!LinkAsLibrary) BitcodeOutputFilename += ".bc";
584   }
585
586   GenerateBitcode(Composite.get(), BitcodeOutputFilename);
587
588   // If we are not linking a library, generate either a native executable
589   // or a JIT shell script, depending upon what the user wants.
590   if (!LinkAsLibrary) {
591     // If the user wants to run a post-link optimization, run it now.
592     if (!PostLinkOpts.empty()) {
593       std::vector<std::string> opts = PostLinkOpts;
594       for (std::vector<std::string>::iterator I = opts.begin(),
595            E = opts.end(); I != E; ++I) {
596         sys::Path prog(*I);
597         if (!prog.canExecute()) {
598           prog = sys::Program::FindProgramByName(*I);
599           if (prog.isEmpty())
600             PrintAndExit(std::string("Optimization program '") + *I +
601                          "' is not found or not executable.", Composite.get());
602         }
603         // Get the program arguments
604         sys::Path tmp_output("opt_result");
605         std::string ErrMsg;
606         if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
607           PrintAndExit(ErrMsg, Composite.get());
608
609         const char* args[4];
610         args[0] = I->c_str();
611         args[1] = BitcodeOutputFilename.c_str();
612         args[2] = tmp_output.c_str();
613         args[3] = 0;
614         if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
615           if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
616             sys::Path target(BitcodeOutputFilename);
617             target.eraseFromDisk();
618             if (tmp_output.renamePathOnDisk(target, &ErrMsg))
619               PrintAndExit(ErrMsg, Composite.get(), 2);
620           } else
621             PrintAndExit("Post-link optimization output is not bitcode",
622                          Composite.get());
623         } else {
624           PrintAndExit(ErrMsg, Composite.get());
625         }
626       }
627     }
628
629     // If the user wants to generate a native executable, compile it from the
630     // bitcode file.
631     //
632     // Otherwise, create a script that will run the bitcode through the JIT.
633     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                                      (void *)(intptr_t)&Optimize);
645       if (llc.isEmpty())
646         PrintAndExit("Failed to find llc", Composite.get());
647
648       sys::Path gcc = sys::Program::FindProgramByName("gcc");
649       if (gcc.isEmpty())
650         PrintAndExit("Failed to find gcc", Composite.get());
651
652       // Generate an assembly language file for the bitcode.
653       std::string ErrMsg;
654       if (0 != GenerateAssembly(AssemblyFile.str(), BitcodeOutputFilename,
655           llc, ErrMsg))
656         PrintAndExit(ErrMsg, Composite.get());
657
658       if (0 != GenerateNative(OutputFilename, AssemblyFile.str(),
659                               NativeLinkItems, gcc, envp, ErrMsg))
660         PrintAndExit(ErrMsg, Composite.get());
661
662       // Remove the assembly language file.
663       AssemblyFile.eraseFromDisk();
664     } else if (NativeCBE) {
665       sys::Path CFile (OutputFilename);
666       CFile.appendSuffix("cbe.c");
667
668       // Mark the output files for removal if we get an interrupt.
669       sys::RemoveFileOnSignal(CFile);
670       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
671
672       // Determine the locations of the llc and gcc programs.
673       sys::Path llc = FindExecutable("llc", argv[0],
674                                      (void *)(intptr_t)&Optimize);
675       if (llc.isEmpty())
676         PrintAndExit("Failed to find llc", Composite.get());
677
678       sys::Path gcc = sys::Program::FindProgramByName("gcc");
679       if (gcc.isEmpty())
680         PrintAndExit("Failed to find gcc", Composite.get());
681
682       // Generate an assembly language file for the bitcode.
683       std::string ErrMsg;
684       if (GenerateCFile(CFile.str(), BitcodeOutputFilename, llc, ErrMsg))
685         PrintAndExit(ErrMsg, Composite.get());
686
687       if (GenerateNative(OutputFilename, CFile.str(), 
688                          NativeLinkItems, gcc, envp, ErrMsg))
689         PrintAndExit(ErrMsg, Composite.get());
690
691       // Remove the assembly language file.
692       CFile.eraseFromDisk();
693
694     } else {
695       EmitShellScript(argv, Composite.get());
696     }
697
698     // Make the script executable...
699     std::string ErrMsg;
700     if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
701       PrintAndExit(ErrMsg, Composite.get());
702
703     // Make the bitcode file readable and directly executable in LLEE as well
704     if (sys::Path(BitcodeOutputFilename).makeExecutableOnDisk(&ErrMsg))
705       PrintAndExit(ErrMsg, Composite.get());
706
707     if (sys::Path(BitcodeOutputFilename).makeReadableOnDisk(&ErrMsg))
708       PrintAndExit(ErrMsg, Composite.get());
709   }
710
711   // Graceful exit
712   return 0;
713 }