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