+ std::string ErrInfo;
+ 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.os());
+ InFile.os().close();
+ if (InFile.os().has_error()) {
+ errs() << "Error writing bitcode file: " << inputFilename.str() << "\n";
+ InFile.os().clear_error();
+ return 1;
+ }
+
+ sys::Path tool = PrependMainExecutablePath("opt", getToolName(),
+ (void*)"opt");
+ if (tool.empty()) {
+ errs() << "Cannot find `opt' in executable directory!\n";
+ return 1;
+ }
+
+ // Ok, everything that could go wrong before running opt is done.
+ InFile.keep();
+
+ // setup the child process' arguments
+ SmallVector<const char*, 8> Args;
+ std::string Opt = tool.str();
+ 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("-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<std::string>::const_iterator I = Passes.begin(),
+ E = Passes.end(); I != E; ++I )
+ 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());
+ Args.push_back(inputFilename.c_str());
+ for (unsigned i = 0; i < NumExtraArgs; ++i)
+ Args.push_back(*ExtraArgs);
+ Args.push_back(0);
+
+ DEBUG(errs() << "\nAbout to run:\t";
+ for (unsigned i = 0, e = Args.size()-1; i != e; ++i)
+ errs() << " " << Args[i];
+ errs() << "\n";
+ );
+
+ sys::Path prog;
+ if (UseValgrind)
+ prog = sys::Program::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);
+
+ // 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.
+ if (DeleteOutput || result != 0)
+ sys::Path(OutputFilename).eraseFromDisk();
+
+ // Remove the temporary input file as well
+ inputFilename.eraseFromDisk();