Added -b option to override the default bitcode output file name.
[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.  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
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/System/Signals.h"
39 #include "llvm/Config/config.h"
40 #include <memory>
41 #include <cstring>
42 using namespace llvm;
43
44 // Input/Output Options
45 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
46   cl::desc("<input bitcode files>"));
47
48 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
49   cl::desc("Override output filename"),
50   cl::value_desc("filename"));
51
52 static cl::opt<std::string> BitcodeOutputFilename("b", cl::init(""),
53   cl::desc("Override bitcode output filename"),
54   cl::value_desc("filename"));
55
56 static cl::opt<bool> Verbose("v",
57   cl::desc("Print information about actions taken"));
58
59 static cl::list<std::string> LibPaths("L", cl::Prefix,
60   cl::desc("Specify a library search path"),
61   cl::value_desc("directory"));
62
63 static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
64   cl::desc("Specify a framework search path"),
65   cl::value_desc("directory"));
66
67 static cl::list<std::string> Libraries("l", cl::Prefix,
68   cl::desc("Specify libraries to link to"),
69   cl::value_desc("library prefix"));
70
71 static cl::list<std::string> Frameworks("framework",
72   cl::desc("Specify frameworks to link to"),
73   cl::value_desc("framework"));
74
75 // Options to control the linking, optimization, and code gen processes
76 static cl::opt<bool> LinkAsLibrary("link-as-library",
77   cl::desc("Link the .bc files together as a library, not an executable"));
78
79 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
80   cl::desc("Alias for -link-as-library"));
81
82 static cl::opt<bool> Native("native",
83   cl::desc("Generate a native binary instead of a shell script"));
84
85 static cl::opt<bool>NativeCBE("native-cbe",
86   cl::desc("Generate a native binary with the C backend and GCC"));
87
88 static cl::list<std::string> PostLinkOpts("post-link-opts",
89   cl::value_desc("path"),
90   cl::desc("Run one or more optimization programs after linking"));
91
92 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
93   cl::desc("Pass options to the system linker"));
94
95 // Compatibility options that llvm-ld ignores but are supported for 
96 // compatibility with LD
97 static cl::opt<std::string> CO3("soname", cl::Hidden,
98   cl::desc("Compatibility option: ignored"));
99
100 static cl::opt<std::string> CO4("version-script", cl::Hidden,
101   cl::desc("Compatibility option: ignored"));
102
103 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
104   cl::desc("Compatibility option: ignored"));
105
106 static  cl::opt<std::string> CO6("h", cl::Hidden,
107   cl::desc("Compatibility option: ignored"));
108
109 static cl::opt<bool> CO7("start-group", cl::Hidden, 
110   cl::desc("Compatibility option: ignored"));
111
112 static cl::opt<bool> CO8("end-group", cl::Hidden, 
113   cl::desc("Compatibility option: ignored"));
114
115 static cl::opt<std::string> CO9("m", cl::Hidden, 
116   cl::desc("Compatibility option: ignored"));
117
118 /// This is just for convenience so it doesn't have to be passed around
119 /// everywhere.
120 static std::string progname;
121
122 /// PrintAndExit - Prints a message to standard error and exits with error code
123 ///
124 /// Inputs:
125 ///  Message  - The message to print to standard error.
126 ///
127 static void PrintAndExit(const std::string &Message, int errcode = 1) {
128   errs() << progname << ": " << Message << "\n";
129   llvm_shutdown();
130   exit(errcode);
131 }
132
133 static 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)
137       outs() << "'" << *I << "'" << " ";
138   outs() << "\n"; outs().flush();
139 }
140
141 /// 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 ///
155 static 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 ///
199 static 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
219 /// GenerateBitcode - generates a bitcode file from the module provided
220 void GenerateBitcode(Module* M, const std::string& FileName) {
221
222   if (Verbose)
223     outs() << "Generating Bitcode To " << FileName << '\n';
224
225   // Create the output file.
226   std::string ErrorInfo;
227   raw_fd_ostream Out(FileName.c_str(), /*Binary=*/true, /*Force=*/true,
228                      ErrorInfo);
229   if (!ErrorInfo.empty())
230     PrintAndExit(ErrorInfo);
231
232   // Ensure that the bitcode file gets removed from the disk if we get a
233   // terminating signal.
234   sys::RemoveFileOnSignal(sys::Path(FileName));
235
236   // Write it out
237   WriteBitcodeToFile(M, Out);
238
239   // Close the bitcode file.
240   Out.close();
241 }
242
243 /// GenerateAssembly - generates a native assembly language source file from the
244 /// specified bitcode file.
245 ///
246 /// Inputs:
247 ///  InputFilename  - The name of the input bitcode file.
248 ///  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 ///
254 static int GenerateAssembly(const std::string &OutputFilename,
255                             const std::string &InputFilename,
256                             const sys::Path &llc,
257                             std::string &ErrMsg ) {
258   // Run LLC to convert the bitcode file into assembly code.
259   std::vector<const char*> args;
260   args.push_back(llc.c_str());
261   // 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");
264   args.push_back("-f");
265   args.push_back("-o");
266   args.push_back(OutputFilename.c_str());
267   args.push_back(InputFilename.c_str());
268   args.push_back(0);
269
270   if (Verbose) {
271     outs() << "Generating Assembly With: \n";
272     PrintCommand(args);
273   }
274
275   return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
276 }
277
278 /// GenerateCFile - generates a C source file from the specified bitcode file.
279 static int GenerateCFile(const std::string &OutputFile,
280                          const std::string &InputFile,
281                          const sys::Path &llc,
282                          std::string& ErrMsg) {
283   // Run LLC to convert the bitcode file into C.
284   std::vector<const char*> args;
285   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());
291   args.push_back(0);
292
293   if (Verbose) {
294     outs() << "Generating C Source With: \n";
295     PrintCommand(args);
296   }
297
298   return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
299 }
300
301 /// GenerateNative - generates a native object file from the
302 /// specified bitcode file.
303 ///
304 /// Inputs:
305 ///  InputFilename   - The name of the input bitcode file.
306 ///  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.
309 ///  FrameworksPaths - The list of directories in which to find frameworks.
310 ///  Frameworks      - The list of frameworks (dynamic libraries)
311 ///  gcc             - The pathname to use for GGC.
312 ///  envp            - A copy of the process's current environment.
313 ///
314 /// Outputs:
315 ///  None.
316 ///
317 /// Returns non-zero value on error.
318 ///
319 static int GenerateNative(const std::string &OutputFilename,
320                           const std::string &InputFilename,
321                           const Linker::ItemList &LinkItems,
322                           const sys::Path &gcc, char ** const envp,
323                           std::string& ErrMsg) {
324   // 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
340
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.
347   std::vector<std::string> args;
348   args.push_back(gcc.c_str());
349   args.push_back("-fno-strict-aliasing");
350   args.push_back("-O3");
351   args.push_back("-o");
352   args.push_back(OutputFilename);
353   args.push_back(InputFilename);
354
355   // Add in the library and framework paths
356   for (unsigned index = 0; index < LibPaths.size(); index++) {
357     args.push_back("-L" + LibPaths[index]);
358   }
359   for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
360     args.push_back("-F" + FrameworkPaths[index]);
361   }
362
363   // Add the requested options
364   for (unsigned index = 0; index < XLinker.size(); index++)
365     args.push_back(XLinker[index]);
366
367   // Add in the libraries to link.
368   for (unsigned index = 0; index < LinkItems.size(); index++)
369     if (LinkItems[index].first != "crtend") {
370       if (LinkItems[index].second)
371         args.push_back("-l" + LinkItems[index].first);
372       else
373         args.push_back(LinkItems[index].first);
374     }
375
376   // 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   }
381       
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);
389
390   if (Verbose) {
391     outs() << "Generating Native Executable With:\n";
392     PrintCommand(Args);
393   }
394
395   // Run the compiler to assembly and link together the program.
396   int R = sys::Program::ExecuteAndWait(
397     gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
398   delete [] clean_env;
399   return R;
400 }
401
402 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
403 /// bitcode file for the program.
404 static void EmitShellScript(char **argv) {
405   if (Verbose)
406     outs() << "Emitting Shell Script\n";
407 #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.
411   std::string ErrMsg;  
412   sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
413   if (llvmstub.isEmpty())
414     PrintAndExit("Could not find llvm-stub.exe executable!");
415
416   if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
417     PrintAndExit(ErrMsg);
418
419   return;
420 #endif
421
422   // Output the script to start the program...
423   std::string ErrorInfo;
424   raw_fd_ostream Out2(OutputFilename.c_str(), /*Binary=*/false, /*Force=*/true,
425                       ErrorInfo);
426   if (!ErrorInfo.empty())
427     PrintAndExit(ErrorInfo);
428
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.
439   std::vector<std::string>::iterator libc =
440     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!
444   for (std::vector<std::string>::iterator i = Libraries.begin(),
445          e = Libraries.end(); i != e; ++i) {
446     // 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())
463       Out2 << "    -load=" << FullLibraryPath.toString() << " \\\n";
464   }
465   Out2 << "    "  << BitcodeOutputFilename << " ${1+\"$@\"}\n";
466   Out2.close();
467 }
468
469 // 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.
472 static void BuildLinkItems(
473   Linker::ItemList& Items,
474   const cl::list<std::string>& Files,
475   const cl::list<std::string>& Libraries) {
476
477   // Build the list of linkage items for LinkItems.
478
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;
483   while ( libIt != Libraries.end() || fileIt != Files.end() ) {
484     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));
499     }
500   }
501 }
502
503 // Rightly this should go in a header file but it just seems such a waste.
504 namespace llvm {
505 extern void Optimize(Module*);
506 }
507
508 int main(int argc, char **argv, char **envp) {
509   // Print a stack trace if we signal out.
510   sys::PrintStackTraceOnErrorSignal();
511   PrettyStackTraceProgram X(argc, argv);
512
513   LLVMContext &Context = getGlobalContext();
514   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
515   try {
516     // Initial global variable above for convenience printing of program name.
517     progname = sys::Path(argv[0]).getBasename();
518
519     // Parse the command line options
520     cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
521
522     // Construct a Linker (now that Verbose is set)
523     Linker TheLinker(progname, OutputFilename, Context, Verbose);
524
525     // Keep track of the native link items (versus the bitcode items)
526     Linker::ItemList NativeLinkItems;
527
528     // Add library paths to the linker
529     TheLinker.addPaths(LibPaths);
530     TheLinker.addSystemPaths();
531
532     // Remove any consecutive duplicates of the same library...
533     Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
534                     Libraries.end());
535
536     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
542
543       // The libraries aren't linked in but are noted as "dependent" in the
544       // module.
545       for (cl::list<std::string>::const_iterator I = Libraries.begin(),
546            E = Libraries.end(); I != E ; ++I) {
547         TheLinker.getModule()->addLibrary(*I);
548       }
549     } else {
550       // 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
555       if (TheLinker.LinkInItems(Items, NativeLinkItems) )
556         return 1; // Error already printed
557     }
558
559     std::auto_ptr<Module> Composite(TheLinker.releaseModule());
560
561     // Optimize the module
562     Optimize(Composite.get());
563
564 #if defined(_WIN32) || defined(__CYGWIN__)
565     if (!LinkAsLibrary) {
566       // 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.
571       sys::Path ExeFile( OutputFilename );
572       if (ExeFile.getSuffix() == "") {
573         ExeFile.appendSuffix("exe");
574         OutputFilename = ExeFile.toString();
575       }
576     }
577 #endif
578
579     // Generate the bitcode for the optimized module.
580     // 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     }
586
587     GenerateBitcode(Composite.get(), BitcodeOutputFilename);
588
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) {
592       // 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())
601               PrintAndExit(std::string("Optimization program '") + *I +
602                 "' is not found or not executable.");
603           }
604           // Get the program arguments
605           sys::Path tmp_output("opt_result");
606           std::string ErrMsg;
607           if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
608             PrintAndExit(ErrMsg);
609
610           const char* args[4];
611           args[0] = I->c_str();
612           args[1] = BitcodeOutputFilename.c_str();
613           args[2] = tmp_output.c_str();
614           args[3] = 0;
615           if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
616             if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
617               sys::Path target(BitcodeOutputFilename);
618               target.eraseFromDisk();
619               if (tmp_output.renamePathOnDisk(target, &ErrMsg))
620                 PrintAndExit(ErrMsg, 2);
621             } else
622               PrintAndExit("Post-link optimization output is not bitcode");
623           } else {
624             PrintAndExit(ErrMsg);
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         if (llc.isEmpty())
645           PrintAndExit("Failed to find llc");
646
647         sys::Path gcc = FindExecutable("gcc", argv[0]);
648         if (gcc.isEmpty())
649           PrintAndExit("Failed to find gcc");
650
651         // Generate an assembly language file for the bitcode.
652         std::string ErrMsg;
653         if (0 != GenerateAssembly(AssemblyFile.toString(), BitcodeOutputFilename,
654             llc, ErrMsg))
655           PrintAndExit(ErrMsg);
656
657         if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
658                                 NativeLinkItems, gcc, envp, ErrMsg))
659           PrintAndExit(ErrMsg);
660
661         // Remove the assembly language file.
662         AssemblyFile.eraseFromDisk();
663       } 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())
674           PrintAndExit("Failed to find llc");
675
676         sys::Path gcc = FindExecutable("gcc", argv[0]);
677         if (gcc.isEmpty())
678           PrintAndExit("Failed to find gcc");
679
680         // Generate an assembly language file for the bitcode.
681         std::string ErrMsg;
682         if (0 != GenerateCFile(
683             CFile.toString(), BitcodeOutputFilename, llc, ErrMsg))
684           PrintAndExit(ErrMsg);
685
686         if (0 != GenerateNative(OutputFilename, CFile.toString(), 
687                                 NativeLinkItems, gcc, envp, ErrMsg))
688           PrintAndExit(ErrMsg);
689
690         // Remove the assembly language file.
691         CFile.eraseFromDisk();
692
693       } else {
694         EmitShellScript(argv);
695       }
696
697       // Make the script executable...
698       std::string ErrMsg;
699       if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
700         PrintAndExit(ErrMsg);
701
702       // Make the bitcode file readable and directly executable in LLEE as well
703       if (sys::Path(BitcodeOutputFilename).makeExecutableOnDisk(&ErrMsg))
704         PrintAndExit(ErrMsg);
705
706       if (sys::Path(BitcodeOutputFilename).makeReadableOnDisk(&ErrMsg))
707         PrintAndExit(ErrMsg);
708     }
709   } catch (const std::string& msg) {
710     PrintAndExit(msg,2);
711   } catch (...) {
712     PrintAndExit("Unexpected unknown exception occurred.", 2);
713   }
714
715   // Graceful exit
716   return 0;
717 }