Have sys::FindProgramByName return a std::string.
[oota-llvm.git] / tools / bugpoint / OptimizerDriver.cpp
index d83f7f33dc43ec20abc893abfbf6781da5b7dd7c..4c9219a71b7007180d07d154385e5f4ab9d4b512 100644 (file)
 //
 //===----------------------------------------------------------------------===//
 
-// Note: as a short term hack, the old Unix-specific code and platform-
-// independent code co-exist via conditional compilation until it is verified
-// that the new code works correctly on Unix.
-
 #include "BugDriver.h"
-#include "llvm/Module.h"
-#include "llvm/PassManager.h"
 #include "llvm/Analysis/Verifier.h"
 #include "llvm/Bitcode/ReaderWriter.h"
-#include "llvm/Target/TargetData.h"
-#include "llvm/Support/FileUtilities.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/Module.h"
+#include "llvm/PassManager.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
-#include "llvm/Support/raw_ostream.h"
-#include "llvm/System/Path.h"
-#include "llvm/System/Program.h"
+#include "llvm/Support/FileUtilities.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/SystemUtils.h"
+#include "llvm/Support/ToolOutputFile.h"
 
 #define DONT_GET_PLUGIN_LOADER_OPTION
 #include "llvm/Support/PluginLoader.h"
@@ -54,12 +51,18 @@ namespace {
 bool BugDriver::writeProgramToFile(const std::string &Filename,
                                    const Module *M) const {
   std::string ErrInfo;
-  raw_fd_ostream Out(Filename.c_str(), ErrInfo,
-                     raw_fd_ostream::F_Binary);
-  if (!ErrInfo.empty()) return true;
-  
-  WriteBitcodeToFile(M, Out);
-  return false;
+  tool_output_file Out(Filename.c_str(), ErrInfo,
+                       raw_fd_ostream::F_Binary);
+  if (ErrInfo.empty()) {
+    WriteBitcodeToFile(M, Out.os());
+    Out.os().close();
+    if (!Out.os().has_error()) {
+      Out.keep();
+      return false;
+    }
+  }
+  Out.os().clear_error();
+  return true;
 }
 
 
@@ -82,11 +85,19 @@ void BugDriver::EmitProgressBitcode(const Module *M,
   if (NoFlyer || PassesToRun.empty()) return;
   outs() << "\n*** You can reproduce the problem with: ";
   if (UseValgrind) outs() << "valgrind ";
-  outs() << "opt " << Filename << " ";
-  outs() << getPassesString(PassesToRun) << "\n";
+  outs() << "opt " << Filename;
+  for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
+    outs() << " -load " << PluginLoader::getPlugin(i);
+  }
+  outs() << " " << getPassesString(PassesToRun) << "\n";
 }
 
-cl::opt<bool> SilencePasses("silence-passes", cl::desc("Suppress output of running passes (both stdout and stderr)"));
+cl::opt<bool> SilencePasses("silence-passes",
+        cl::desc("Suppress output of running passes (both stdout and stderr)"));
+
+static cl::list<std::string> OptArgs("opt-args", cl::Positional,
+                                     cl::desc("<opt arguments>..."),
+                                     cl::ZeroOrMore, cl::PositionalEatsArgs);
 
 /// runPasses - Run the specified passes on Program, outputting a bitcode file
 /// and writing the filename into OutputFile if successful.  If the
@@ -97,7 +108,7 @@ cl::opt<bool> SilencePasses("silence-passes", cl::desc("Suppress output of runni
 /// or failed.
 ///
 bool BugDriver::runPasses(Module *Program,
-                          const std::vector<const PassInfo*> &Passes,
+                          const std::vector<std::string> &Passes,
                           std::string &OutputFilename, bool DeleteOutput,
                           bool Quiet, unsigned NumExtraArgs,
                           const char * const *ExtraArgs) const {
@@ -119,49 +130,55 @@ bool BugDriver::runPasses(Module *Program,
            << ErrMsg << "\n";
     return(1);
   }
-  
+
   std::string ErrInfo;
-  raw_fd_ostream InFile(inputFilename.c_str(), ErrInfo,
-                        raw_fd_ostream::F_Binary);
-  
-  
+  tool_output_file InFile(inputFilename.c_str(), ErrInfo,
+                          raw_fd_ostream::F_Binary);
+
+
   if (!ErrInfo.empty()) {
     errs() << "Error opening bitcode file: " << inputFilename.str() << "\n";
     return 1;
   }
-  WriteBitcodeToFile(Program, InFile);
-  InFile.close();
+  WriteBitcodeToFile(Program, InFile.os());
+  InFile.os().close();
+  if (InFile.os().has_error()) {
+    errs() << "Error writing bitcode file: " << inputFilename.str() << "\n";
+    InFile.os().clear_error();
+    return 1;
+  }
 
-  // setup the child process' arguments
-  SmallVector<const char*, 8> Args;
-  std::string Opt;
-  llvm::StringRef TN(ToolName);
-  if (TN.find('/') == llvm::StringRef::npos) {
-    Opt = ToolName;
-  } else {
-    std::pair<llvm::StringRef, llvm::StringRef> P = TN.rsplit('/');
-    Opt = P.first.str() + "/" + "opt";
+  std::string tool = sys::FindProgramByName("opt");
+  if (tool.empty()) {
+    errs() << "Cannot find `opt' in PATH!\n";
+    return 1;
   }
 
-  sys::Path tool = sys::Program::FindProgramByName(Opt);
+  // Ok, everything that could go wrong before running opt is done.
+  InFile.keep();
+
+  // setup the child process' arguments
+  SmallVector<const char*, 8> Args;
   if (UseValgrind) {
     Args.push_back("valgrind");
     Args.push_back("--error-exitcode=1");
     Args.push_back("-q");
     Args.push_back(tool.c_str());
   } else
-    Args.push_back(Opt.c_str());
+    Args.push_back(tool.c_str());
 
   Args.push_back("-o");
   Args.push_back(OutputFilename.c_str());
+  for (unsigned i = 0, e = OptArgs.size(); i != e; ++i)
+    Args.push_back(OptArgs[i].c_str());
   std::vector<std::string> pass_args;
   for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
     pass_args.push_back( std::string("-load"));
     pass_args.push_back( PluginLoader::getPlugin(i));
   }
-  for (std::vector<const PassInfo*>::const_iterator I = Passes.begin(),
+  for (std::vector<std::string>::const_iterator I = Passes.begin(),
        E = Passes.end(); I != E; ++I )
-    pass_args.push_back( std::string("-") + (*I)->getPassArgument() );
+    pass_args.push_back( std::string("-") + (*I) );
   for (std::vector<std::string>::const_iterator I = pass_args.begin(),
        E = pass_args.end(); I != E; ++I )
     Args.push_back(I->c_str());
@@ -178,17 +195,17 @@ bool BugDriver::runPasses(Module *Program,
 
   sys::Path prog;
   if (UseValgrind)
-    prog = sys::Program::FindProgramByName("valgrind");
+    prog = sys::FindProgramByName("valgrind");
   else
     prog = tool;
-  
+
   // Redirect stdout and stderr to nowhere if SilencePasses is given
   sys::Path Nowhere;
   const sys::Path *Redirects[3] = {0, &Nowhere, &Nowhere};
 
-  int result = sys::Program::ExecuteAndWait(prog, Args.data(), 0,
-                                            (SilencePasses ? Redirects : 0),
-                                            Timeout, MemoryLimit, &ErrMsg);
+  int result =
+      sys::ExecuteAndWait(prog, Args.data(), 0, (SilencePasses ? Redirects : 0),
+                          Timeout, MemoryLimit, &ErrMsg);
 
   // If we are supposed to delete the bitcode file or if the passes crashed,
   // remove it now.  This may fail if the file was never created, but that's ok.
@@ -207,7 +224,7 @@ bool BugDriver::runPasses(Module *Program,
       if (result == -1)
         outs() << "Execute failed: " << ErrMsg << "\n";
       else
-        outs() << "Crashed with signal #" << abs(result) << "\n";
+        outs() << "Crashed: " << ErrMsg << "\n";
     }
     if (result & 0x01000000)
       outs() << "Dumped core\n";
@@ -222,7 +239,7 @@ bool BugDriver::runPasses(Module *Program,
 /// module, returning the transformed module on success, or a null pointer on
 /// failure.
 Module *BugDriver::runPassesOn(Module *M,
-                               const std::vector<const PassInfo*> &Passes,
+                               const std::vector<std::string> &Passes,
                                bool AutoDebugCrashes, unsigned NumExtraArgs,
                                const char * const *ExtraArgs) {
   std::string BitcodeResult;