Oops :)
[oota-llvm.git] / tools / llvm-ld / llvm-ld.cpp
index 6b9adaff5a4b481db8949d5db4fc375b4a30a207..207f0cbb4f422a43db0cfd3d248df3a166e62be3 100644 (file)
 #include "llvm/Target/TargetMachineRegistry.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileUtilities.h"
+#include "llvm/Support/ManagedStatic.h"
+#include "llvm/Support/Streams.h"
 #include "llvm/Support/SystemUtils.h"
 #include "llvm/System/Signals.h"
 #include <fstream>
-#include <iostream>
 #include <memory>
-
 using namespace llvm;
 
 // Input/Output Options
@@ -59,6 +59,7 @@ static cl::list<std::string> Libraries("l", cl::Prefix,
   cl::desc("Specify libraries to link to"),
   cl::value_desc("library prefix"));
 
+// Options to control the linking, optimization, and code gen processes
 static cl::opt<bool> LinkAsLibrary("link-as-library",
   cl::desc("Link the .bc files together as a library, not an executable"));
 
@@ -74,7 +75,7 @@ static cl::opt<bool> Native("native",
 static cl::opt<bool>NativeCBE("native-cbe",
   cl::desc("Generate a native binary with the C backend and GCC"));
 
-static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
+static cl::opt<bool>DisableCompression("disable-compression", cl::init(true),
   cl::desc("Disable writing of compressed bytecode files"));
 
 static cl::list<std::string> PostLinkOpts("post-link-opts",
@@ -84,7 +85,8 @@ static cl::list<std::string> PostLinkOpts("post-link-opts",
 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
   cl::desc("Pass options to the system linker"));
 
-// Compatibility options that are ignored but supported by LD
+// Compatibility options that llvm-ld ignores but are supported for 
+// compatibility with LD
 static cl::opt<std::string> CO3("soname", cl::Hidden,
   cl::desc("Compatibility option: ignored"));
 
@@ -97,20 +99,25 @@ static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
 static  cl::opt<std::string> CO6("h", cl::Hidden,
   cl::desc("Compatibility option: ignored"));
 
+static cl::opt<bool> CO7("start-group", cl::Hidden, 
+  cl::desc("Compatibility option: ignored"));
+
+static cl::opt<bool> CO8("end-group", cl::Hidden, 
+  cl::desc("Compatibility option: ignored"));
 
 /// This is just for convenience so it doesn't have to be passed around
 /// everywhere.
 static std::string progname;
 
-/// PrintAndReturn - Prints a message to standard error and returns true.
+/// PrintAndExit - Prints a message to standard error and exits with error code
 ///
 /// Inputs:
-///  progname - The name of the program (i.e. argv[0]).
 ///  Message  - The message to print to standard error.
 ///
-static int PrintAndReturn(const std::string &Message) {
-  std::cerr << progname << ": " << Message << "\n";
-  return 1;
+static void PrintAndExit(const std::string &Message, int errcode = 1) {
+  cerr << progname << ": " << Message << "\n";
+  llvm_shutdown();
+  exit(errcode);
 }
 
 /// CopyEnv - This function takes an array of environment variables and makes a
@@ -198,17 +205,16 @@ void GenerateBytecode(Module* M, const std::string& FileName) {
   std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
                                std::ios::binary;
   std::ofstream Out(FileName.c_str(), io_mode);
-  if (!Out.good()) {
-    PrintAndReturn("error opening '" + FileName + "' for writing!");
-    return;
-  }
+  if (!Out.good())
+    PrintAndExit("error opening '" + FileName + "' for writing!");
 
   // Ensure that the bytecode file gets removed from the disk if we get a
   // terminating signal.
   sys::RemoveFileOnSignal(sys::Path(FileName));
 
   // Write it out
-  WriteBytecodeToFile(M, Out, !DisableCompression);
+  OStream L(Out);
+  WriteBytecodeToFile(M, L, !DisableCompression);
 
   // Close the bytecode file.
   Out.close();
@@ -238,7 +244,7 @@ static int GenerateAssembly(const std::string &OutputFilename,
   args.push_back(InputFilename.c_str());
   args.push_back(0);
 
-  return sys::Program::ExecuteAndWait(llc,&args[0],0,0,0,&ErrMsg);
+  return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
 }
 
 /// GenerateCFile - generates a C source file from the specified bytecode file.
@@ -255,7 +261,7 @@ static int GenerateCFile(const std::string &OutputFile,
   args.push_back(OutputFile.c_str());
   args.push_back(InputFile.c_str());
   args.push_back(0);
-  return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
+  return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
 }
 
 /// GenerateNative - generates a native object file from the
@@ -264,7 +270,7 @@ static int GenerateCFile(const std::string &OutputFile,
 /// Inputs:
 ///  InputFilename  - The name of the input bytecode file.
 ///  OutputFilename - The name of the file to generate.
-///  Libraries      - The list of libraries with which to link.
+///  LinkItems      - The native libraries, files, code with which to link
 ///  LibPaths       - The list of directories in which to find libraries.
 ///  gcc            - The pathname to use for GGC.
 ///  envp           - A copy of the process's current environment.
@@ -276,7 +282,7 @@ static int GenerateCFile(const std::string &OutputFile,
 ///
 static int GenerateNative(const std::string &OutputFilename,
                           const std::string &InputFilename,
-                          const std::vector<std::string> &Libraries,
+                          const Linker::ItemList &LinkItems,
                           const sys::Path &gcc, char ** const envp,
                           std::string& ErrMsg) {
   // Remove these environment variables from the environment of the
@@ -323,17 +329,20 @@ static int GenerateNative(const std::string &OutputFilename,
   }
 
   // Add in the libraries to link.
-  for (unsigned index = 0; index < Libraries.size(); index++)
-    if (Libraries[index] != "crtend") {
-      args.push_back("-l");
-      args.push_back(Libraries[index].c_str());
+  for (unsigned index = 0; index < LinkItems.size(); index++)
+    if (LinkItems[index].first != "crtend") {
+      if (LinkItems[index].second) {
+        std::string lib_name = "-l" + LinkItems[index].first;
+        args.push_back(lib_name.c_str());
+      } else
+        args.push_back(LinkItems[index].first.c_str());
     }
 
   args.push_back(0);
 
   // Run the compiler to assembly and link together the program.
   int R = sys::Program::ExecuteAndWait(
-      gcc, &args[0], (const char**)clean_env,0,0,&ErrMsg);
+    gcc, &args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
   delete [] clean_env;
   return R;
 }
@@ -345,19 +354,21 @@ static void EmitShellScript(char **argv) {
   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
   // support windows systems, we copy the llvm-stub.exe executable from the
   // build tree to the destination file.
+  std::string ErrMsg;  
   sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
-  if (llvmstub.isEmpty()) {
-    std::cerr << "Could not find llvm-stub.exe executable!\n";
-    exit(1);
-  }
-  sys::CopyFile(sys::Path(OutputFilename), llvmstub);
+  if (llvmstub.isEmpty())
+    PrintAndExit("Could not find llvm-stub.exe executable!");
+
+  if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
+    PrintAndExit(ErrMsg);
+
   return;
 #endif
 
   // Output the script to start the program...
   std::ofstream Out2(OutputFilename.c_str());
   if (!Out2.good())
-    exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
+    PrintAndExit("error opening '" + OutputFilename + "' for writing!");
 
   Out2 << "#!/bin/sh\n";
   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
@@ -424,16 +435,21 @@ extern void Optimize(Module*);
 }
 
 int main(int argc, char **argv, char **envp) {
+  llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
   try {
     // Initial global variable above for convenience printing of program name.
     progname = sys::Path(argv[0]).getBasename();
-    Linker TheLinker(progname, OutputFilename, Verbose);
 
     // Parse the command line options
     cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
     sys::PrintStackTraceOnErrorSignal();
 
-    // Set up the library paths for the Linker
+    // Construct a Linker (now that Verbose is set)
+    Linker TheLinker(progname, OutputFilename, Verbose);
+    // Keep track of the native link items (vice the bytecode items)
+    Linker::ItemList LinkItems;
+
+    // Add library paths to the linker
     TheLinker.addPaths(LibPaths);
     TheLinker.addSystemPaths();
 
@@ -457,12 +473,11 @@ int main(int argc, char **argv, char **envp) {
     } else {
       // Build a list of the items from our command line
       Linker::ItemList Items;
-      Linker::ItemList NativeItems;
       BuildLinkItems(Items, InputFilenames, Libraries);
 
       // Link all the items together
-      if (TheLinker.LinkInItems(Items,NativeItems) )
-        return 1;
+      if (TheLinker.LinkInItems(Items,LinkItems) )
+        return 1; // Error already printed
     }
 
     std::auto_ptr<Module> Composite(TheLinker.releaseModule());
@@ -487,34 +502,30 @@ int main(int argc, char **argv, char **envp) {
           if (!prog.canExecute()) {
             prog = sys::Program::FindProgramByName(*I);
             if (prog.isEmpty())
-              return PrintAndReturn(std::string("Optimization program '") + *I +
+              PrintAndExit(std::string("Optimization program '") + *I +
                 "' is not found or not executable.");
           }
           // Get the program arguments
           sys::Path tmp_output("opt_result");
           std::string ErrMsg;
-          if (tmp_output.createTemporaryFileOnDisk(&ErrMsg)) {
-            return PrintAndReturn(ErrMsg);
-          }
+          if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
+            PrintAndExit(ErrMsg);
+
           const char* args[4];
           args[0] = I->c_str();
           args[1] = RealBytecodeOutput.c_str();
           args[2] = tmp_output.c_str();
           args[3] = 0;
-          if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0, &ErrMsg)) {
+          if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
             if (tmp_output.isBytecodeFile()) {
               sys::Path target(RealBytecodeOutput);
               target.eraseFromDisk();
-              if (tmp_output.renamePathOnDisk(target, &ErrMsg)) {
-                std::cerr << argv[0] << ": " << ErrMsg << "\n";
-                return 2;
-              }
+              if (tmp_output.renamePathOnDisk(target, &ErrMsg))
+                PrintAndExit(ErrMsg, 2);
             } else
-              return PrintAndReturn(
-                "Post-link optimization output is not bytecode");
+              PrintAndExit("Post-link optimization output is not bytecode");
           } else {
-            std::cerr << argv[0] << ": " << ErrMsg << "\n";
-            return 2;
+            PrintAndExit(ErrMsg);
           }
         }
       }
@@ -535,27 +546,25 @@ int main(int argc, char **argv, char **envp) {
         // Determine the locations of the llc and gcc programs.
         sys::Path llc = FindExecutable("llc", argv[0]);
         if (llc.isEmpty())
-          return PrintAndReturn("Failed to find llc");
+          PrintAndExit("Failed to find llc");
 
         sys::Path gcc = FindExecutable("gcc", argv[0]);
         if (gcc.isEmpty())
-          return PrintAndReturn("Failed to find gcc");
+          PrintAndExit("Failed to find gcc");
 
         // Generate an assembly language file for the bytecode.
-        if (Verbose) std::cout << "Generating Assembly Code\n";
+        if (Verbose) 
+          cout << "Generating Assembly Code\n";
         std::string ErrMsg;
         if (0 != GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput,
-            llc, ErrMsg)) {
-          std::cerr << argv[0] << ": " << ErrMsg << "\n";
-          return 1;
-        }
+            llc, ErrMsg))
+          PrintAndExit(ErrMsg);
 
-        if (Verbose) std::cout << "Generating Native Code\n";
+        if (Verbose) 
+          cout << "Generating Native Code\n";
         if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
-            Libraries,gcc,envp,ErrMsg)) {
-          std::cerr << argv[0] << ": " << ErrMsg << "\n";
-          return 1;
-        }
+            LinkItems,gcc,envp,ErrMsg))
+          PrintAndExit(ErrMsg);
 
         // Remove the assembly language file.
         AssemblyFile.eraseFromDisk();
@@ -570,27 +579,25 @@ int main(int argc, char **argv, char **envp) {
         // Determine the locations of the llc and gcc programs.
         sys::Path llc = FindExecutable("llc", argv[0]);
         if (llc.isEmpty())
-          return PrintAndReturn("Failed to find llc");
+          PrintAndExit("Failed to find llc");
 
         sys::Path gcc = FindExecutable("gcc", argv[0]);
         if (gcc.isEmpty())
-          return PrintAndReturn("Failed to find gcc");
+          PrintAndExit("Failed to find gcc");
 
         // Generate an assembly language file for the bytecode.
-        if (Verbose) std::cout << "Generating Assembly Code\n";
+        if (Verbose) 
+          cout << "Generating Assembly Code\n";
         std::string ErrMsg;
         if (0 != GenerateCFile(
-            CFile.toString(), RealBytecodeOutput, llc, ErrMsg)) {
-          std::cerr << argv[0] << ": " << ErrMsg << "\n";
-          return 1;
-        }
+            CFile.toString(), RealBytecodeOutput, llc, ErrMsg))
+          PrintAndExit(ErrMsg);
 
-        if (Verbose) std::cout << "Generating Native Code\n";
-        if (0 != GenerateNative(OutputFilename, CFile.toString(), Libraries, 
-            gcc, envp, ErrMsg)) {
-          std::cerr << argv[0] << ": " << ErrMsg << "\n";
-          return 1;
-        }
+        if (Verbose) 
+          cout << "Generating Native Code\n";
+        if (0 != GenerateNative(OutputFilename, CFile.toString(), LinkItems, 
+            gcc, envp, ErrMsg))
+          PrintAndExit(ErrMsg);
 
         // Remove the assembly language file.
         CFile.eraseFromDisk();
@@ -601,27 +608,22 @@ int main(int argc, char **argv, char **envp) {
 
       // Make the script executable...
       std::string ErrMsg;
-      if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg)) {
-        std::cerr << argv[0] << ": " << ErrMsg << "\n";
-        return 1;
-      }
+      if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
+        PrintAndExit(ErrMsg);
 
       // Make the bytecode file readable and directly executable in LLEE as well
-      if (sys::Path(RealBytecodeOutput).makeExecutableOnDisk(&ErrMsg)) {
-        std::cerr << argv[0] << ": " << ErrMsg << "\n";
-        return 1;
-      }
-      if (sys::Path(RealBytecodeOutput).makeReadableOnDisk(&ErrMsg)) {
-        std::cerr << argv[0] << ": " << ErrMsg << "\n";
-        return 1;
-      }
-    }
+      if (sys::Path(RealBytecodeOutput).makeExecutableOnDisk(&ErrMsg))
+        PrintAndExit(ErrMsg);
 
-    return 0;
+      if (sys::Path(RealBytecodeOutput).makeReadableOnDisk(&ErrMsg))
+        PrintAndExit(ErrMsg);
+    }
   } catch (const std::string& msg) {
-    std::cerr << argv[0] << ": " << msg << "\n";
+    PrintAndExit(msg,2);
   } catch (...) {
-    std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
+    PrintAndExit("Unexpected unknown exception occurred.", 2);
   }
-  return 1;
+
+  // Graceful exit
+  return 0;
 }