Exemplo n.º 1
0
bool DebugIR::runOnModule(Module &M) {
  OwningPtr<int> fd;

  if (isMissingPath() && !getSourceInfo(M)) {
    if (!WriteSourceToDisk)
      report_fatal_error("DebugIR unable to determine file name in input. "
                         "Ensure Module contains an identifier, a valid "
                         "DICompileUnit, or construct DebugIR with "
                         "non-empty Filename/Directory parameters.");
    else
      generateFilename(fd);
  }

  if (!GeneratedPath && WriteSourceToDisk)
    updateExtension(".debug-ll");

  // Clear line numbers. Keep debug info (if any) if we were able to read the
  // file name from the DICompileUnit descriptor.
  DebugMetadataRemover::process(M, !ParsedPath);

  OwningPtr<Module> DisplayM;
  createDebugInfo(M, DisplayM);
  if (WriteSourceToDisk) {
    Module *OutputM = DisplayM.get() ? DisplayM.get() : &M;
    writeDebugBitcode(OutputM, fd.get());
  }

  DEBUG(M.dump());
  return true;
}
Exemplo n.º 2
0
bool ToolInvocation::run() {
  std::vector<const char*> Argv;
  for (int I = 0, E = CommandLine.size(); I != E; ++I)
    Argv.push_back(CommandLine[I].c_str());
  const char *const BinaryName = Argv[0];
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  TextDiagnosticPrinter DiagnosticPrinter(
      llvm::errs(), &*DiagOpts);
  DiagnosticsEngine Diagnostics(
    IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
    &*DiagOpts, &DiagnosticPrinter, false);

  const OwningPtr<clang::driver::Driver> Driver(
      newDriver(&Diagnostics, BinaryName));
  // Since the input might only be virtual, don't check whether it exists.
  Driver->setCheckInputsExist(false);
  const OwningPtr<clang::driver::Compilation> Compilation(
      Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
  const clang::driver::ArgStringList *const CC1Args = getCC1Arguments(
      &Diagnostics, Compilation.get());
  if (CC1Args == NULL) {
    return false;
  }
  OwningPtr<clang::CompilerInvocation> Invocation(
      newInvocation(&Diagnostics, *CC1Args));
  return runInvocation(BinaryName, Compilation.get(), Invocation.take());
}
Exemplo n.º 3
0
static void clang_indexTranslationUnit_Impl(void *UserData) {
  IndexTranslationUnitInfo *ITUI =
    static_cast<IndexTranslationUnitInfo*>(UserData);
  CXTranslationUnit TU = ITUI->TU;
  CXClientData client_data = ITUI->client_data;
  IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks;
  unsigned index_callbacks_size = ITUI->index_callbacks_size;
  unsigned index_options = ITUI->index_options;
  ITUI->result = 1; // init as error.

  if (!TU)
    return;
  if (!client_index_callbacks || index_callbacks_size == 0)
    return;

  CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
    setThreadBackgroundPriority();

  IndexerCallbacks CB;
  memset(&CB, 0, sizeof(CB));
  unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
                                  ? index_callbacks_size : sizeof(CB);
  memcpy(&CB, client_index_callbacks, ClientCBSize);

  OwningPtr<IndexingContext> IndexCtx;
  IndexCtx.reset(new IndexingContext(client_data, CB, index_options, TU));

  // Recover resources if we crash before exiting this method.
  llvm::CrashRecoveryContextCleanupRegistrar<IndexingContext>
    IndexCtxCleanup(IndexCtx.get());

  OwningPtr<IndexingConsumer> IndexConsumer;
  IndexConsumer.reset(new IndexingConsumer(*IndexCtx));

  // Recover resources if we crash before exiting this method.
  llvm::CrashRecoveryContextCleanupRegistrar<IndexingConsumer>
    IndexConsumerCleanup(IndexConsumer.get());

  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
  if (!Unit)
    return;

  ASTUnit::ConcurrencyCheck Check(*Unit);

  FileManager &FileMgr = Unit->getFileManager();

  if (Unit->getOriginalSourceFileName().empty())
    IndexCtx->enteredMainFile(0);
  else
    IndexCtx->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName()));

  IndexConsumer->Initialize(Unit->getASTContext());

  indexPreprocessingRecord(*Unit, *IndexCtx);
  indexTranslationUnit(*Unit, *IndexCtx);
  indexDiagnostics(TU, *IndexCtx);

  ITUI->result = 0;
}
Exemplo n.º 4
0
// Returns true on error.
static bool format(std::string FileName) {
  FileManager Files((FileSystemOptions()));
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  OwningPtr<MemoryBuffer> Code;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
    llvm::errs() << ec.message() << "\n";
    return true;
  }
  if (Code->getBufferSize() == 0)
    return true; // Empty files are formatted correctly.
  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
  std::vector<CharSourceRange> Ranges;
  if (fillRanges(Sources, ID, Code.get(), Ranges))
    return true;

  FormatStyle FormatStyle = getStyle(Style, FileName);
  Lexer Lex(ID, Sources.getBuffer(ID), Sources,
            getFormattingLangOpts(FormatStyle.Standard));
  tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
  if (OutputXML) {
    llvm::outs()
        << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
    for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                               E = Replaces.end();
         I != E; ++I) {
      llvm::outs() << "<replacement "
                   << "offset='" << I->getOffset() << "' "
                   << "length='" << I->getLength() << "'>"
                   << I->getReplacementText() << "</replacement>\n";
    }
    llvm::outs() << "</replacements>\n";
  } else {
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Replaces.size() == 0)
        return false; // Nothing changed, don't touch the file.

      std::string ErrorInfo;
      llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
                                      llvm::sys::fs::F_Binary);
      if (!ErrorInfo.empty()) {
        llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
        return true;
      }
      Rewrite.getEditBuffer(ID).write(FileStream);
      FileStream.flush();
    } else {
      if (Cursor.getNumOccurrences() != 0)
        outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
                                          Replaces, Cursor) << " }\n";
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
  return false;
}
Exemplo n.º 5
0
    virtual void HandleTranslationUnit(ASTContext &C) {
      {
        PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
        if (llvm::TimePassesIsEnabled)
          LLVMIRGeneration.startTimer();

        Gen->HandleTranslationUnit(C);

        if (llvm::TimePassesIsEnabled)
          LLVMIRGeneration.stopTimer();
      }

      // Silently ignore if we weren't initialized for some reason.
      if (!TheModule)
        return;

      // Make sure IR generation is happy with the module. This is released by
      // the module provider.
      llvm::Module *M = Gen->ReleaseModule();
      if (!M) {
        // The module has been released by IR gen on failures, do not double
        // free.
        TheModule.take();
        return;
      }

      assert(TheModule.get() == M &&
             "Unexpected module change during IR generation");

      // Link LinkModule into this module if present, preserving its validity.
      if (LinkModule) {
        std::string ErrorMsg;
        if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
                                &ErrorMsg)) {
          Diags.Report(diag::err_fe_cannot_link_module)
            << LinkModule->getModuleIdentifier() << ErrorMsg;
          return;
        }
      }

      // Install an inline asm handler so that diagnostics get printed through
      // our diagnostics hooks.
      LLVMContext &Ctx = TheModule->getContext();
      LLVMContext::InlineAsmDiagHandlerTy OldHandler =
        Ctx.getInlineAsmDiagnosticHandler();
      void *OldContext = Ctx.getInlineAsmDiagnosticContext();
      Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);

      EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
                        TheModule.get(), Action, AsmOutStream);
      
      Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
    }
Exemplo n.º 6
0
int main()
{
    InitializeNativeTarget();
    llvm_start_multithreaded();
    LLVMContext context;
    string error;
    OwningPtr<llvm::MemoryBuffer> fileBuf;
    MemoryBuffer::getFile("hw.bc", fileBuf);
    ErrorOr<Module*> m = parseBitcodeFile(fileBuf.get(), context);
    ExecutionEngine *ee = ExecutionEngine::create(m.get());

    Function* func = ee->FindFunctionNamed("main");
    std::cout << "hop " << m.get()  << " ee " << ee << " f " << func << std::endl;

    typedef void (*PFN)();
    PFN pfn = reinterpret_cast<PFN>(ee->getPointerToFunction(func));
    pfn();

    Function* f = ee->FindFunctionNamed("fib");
    std::cout << "big " << f << std::endl;

    //    typedef std::function<int(int)> fibType;
    typedef int (*fibType)(int);
    fibType ffib = reinterpret_cast<fibType>(ee->getPointerToFunction(f));
    std::cout << "fib " << ffib(7) << std::endl;



    delete ee;
}
Exemplo n.º 7
0
image* create(const char* data, std::size_t size) {
    StringRef data_ref(data, size);
    MemoryBuffer* buff(MemoryBuffer::getMemBufferCopy(data_ref, "binary"));
    OwningPtr<object::Binary> binary;
    if (error_code ec = createBinary(buff, binary))
        llvm_binary_fail(ec);
    return create_image(binary.get());
}
Exemplo n.º 8
0
int main(int argc, char **argv) {
  atexit(llvm_shutdown); // Call llvm_shutdown() on exit.
  lav::parseArguments(argc, argv);
  sys::PrintStackTraceOnErrorSignal();

  // Load the bytecode...
//  std::cout << std::endl << "Loading the bytecode..." << std::endl;
  std::string ErrorMsg;

  Module *mainModule = 0;

  OwningPtr<MemoryBuffer> BufferPtr;
  llvm::error_code ec =
      MemoryBuffer::getFileOrSTDIN(InputFileName.c_str(), BufferPtr);
  if (ec) {
    lav::exit_error((std::string) "error loading program '%s': %s" +
                    InputFileName.c_str() + ec.message().c_str());
  }
  mainModule =
      getLazyBitcodeModule(BufferPtr.get(), getGlobalContext(), &ErrorMsg);

  if (mainModule) {
    if (mainModule->MaterializeAllPermanently(&ErrorMsg)) {
      delete mainModule;
      mainModule = 0;
    }
  }
  if (!mainModule)
    lav::exit_error((std::string) "error loading program '%s': %s" +
                    InputFileName.c_str() + ErrorMsg.c_str());

  std::cout << "Loading the bytecode... Completed " << std::endl << std::endl;

  PassManager Passes;
  Passes.add(new llvm::DataLayout(mainModule));
  Passes.add(createFCFGSimplificationPass()); // Clean up after IPCP & DAE
//  Passes.add(createLoopInfoPass()); // 
  Passes.add(llvm::createLoopSimplifyPass());
  Passes.add(lav::createPetljePass()); // 

  if (EnableInline)
    Passes.add(createAllInlinerPass(
        Threshold)); //Inline malo vece funkcije, parametar inlininga od 200 do
                     //milijardu, ako je bez argumenta postavljeno je na
                     //milijardu

  Passes.run(*mainModule);

  Podaci p(mainModule);
  p.UradiPosao();
  BufferPtr.take();
  std::cout << "Finished " << std::endl << std::endl;

  return 0;
}
Exemplo n.º 9
0
int main(int argc, const char *argv[]) {
  cl::ParseCommandLineOptions(argc, argv, "SPIR verifier");

  if (InputFilename.empty()) {
    errs() << HelpMessage;
    return 1;
  }

  StringRef Path = InputFilename;
  LLVMContext Ctx;
  OwningPtr<MemoryBuffer> result;

  // Parse the bitcode file into a module.
  error_code ErrCode = MemoryBuffer::getFile(Path, result);

  if (!result.get()) {
    errs() << "Buffer Creation Error. " << ErrCode.message() << "\n";
    return 1;
  }

  std::string ErrMsg;
  Module *M = ParseBitcodeFile(result.get(), Ctx, &ErrMsg);
  if (!M) {
    outs() << "According to this SPIR Verifier, " << Path << " is an invalid SPIR module.\n";
    errs() << "Bitcode parsing error. " << ErrMsg << "\n";
    return 1;
  }

  // Run the verification pass, and report errors if necessary.
  SpirValidation Validation;
  Validation.runOnModule(*M);
  const ErrorPrinter *EP = Validation.getErrorPrinter();
  if (EP->hasErrors()) {
    outs() << "According to this SPIR Verifier, " << Path << " is an invalid SPIR module.\n";
    errs() << "The module contains the following errors:\n\n";
    EP->print(errs(), LITMode.getValue());
    return 1;
  }

  outs() << "According to this SPIR Verifier, " << Path << " is a valid SPIR module.\n";
  return 0;
}
Exemplo n.º 10
0
SpecialCaseList *SpecialCaseList::create(
    const StringRef Path, std::string &Error) {
  if (Path.empty())
    return new SpecialCaseList();
  OwningPtr<MemoryBuffer> File;
  if (error_code EC = MemoryBuffer::getFile(Path, File)) {
    Error = (Twine("Can't open file '") + Path + "': " + EC.message()).str();
    return 0;
  }
  return create(File.get(), Error);
}
Exemplo n.º 11
0
void DebugIR::createDebugInfo(Module &M, OwningPtr<Module> &DisplayM) {
  if (M.getFunctionList().size() == 0)
    // no functions -- no debug info needed
    return;

  OwningPtr<ValueToValueMapTy> VMap;

  if (WriteSourceToDisk && (HideDebugIntrinsics || HideDebugMetadata)) {
    VMap.reset(new ValueToValueMapTy);
    DisplayM.reset(CloneModule(&M, *VMap));

    if (HideDebugIntrinsics)
      DebugIntrinsicsRemover::process(*DisplayM);

    if (HideDebugMetadata)
      DebugMetadataRemover::process(*DisplayM);
  }

  DIUpdater R(M, Filename, Directory, DisplayM.get(), VMap.get());
}
Exemplo n.º 12
0
/// @brief Opens \a File and dumps it.
static void dumpInput(StringRef File) {
  // If file isn't stdin, check that it exists.
  if (File != "-" && !sys::fs::exists(File)) {
    reportError(File, readobj_error::file_not_found);
    return;
  }

  // Attempt to open the binary.
  OwningPtr<Binary> Binary;
  if (error_code EC = createBinary(File, Binary)) {
    reportError(File, EC);
    return;
  }

  if (Archive *Arc = dyn_cast<Archive>(Binary.get()))
    dumpArchive(Arc);
  else if (ObjectFile *Obj = dyn_cast<ObjectFile>(Binary.get()))
    dumpObject(Obj);
  else
    reportError(File, readobj_error::unrecognized_file_format);
}
Exemplo n.º 13
0
/// @brief Print the section sizes for @p file. If @p file is an archive, print
///        the section sizes for each archive member.
static void PrintFileSectionSizes(StringRef file) {
  // If file is not stdin, check that it exists.
  if (file != "-") {
    bool exists;
    if (sys::fs::exists(file, exists) || !exists) {
      errs() << ToolName << ": '" << file << "': " << "No such file\n";
      return;
    }
  }

  // Attempt to open the binary.
  ErrorOr<Binary *> BinaryOrErr = createBinary(file);
  if (error_code EC = BinaryOrErr.getError()) {
    errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
    return;
  }
  OwningPtr<Binary> binary(BinaryOrErr.get());

  if (Archive *a = dyn_cast<Archive>(binary.get())) {
    // This is an archive. Iterate over each member and display its sizes.
    for (object::Archive::child_iterator i = a->child_begin(),
                                         e = a->child_end(); i != e; ++i) {
      OwningPtr<Binary> child;
      if (error_code ec = i->getAsBinary(child)) {
        errs() << ToolName << ": " << file << ": " << ec.message() << ".\n";
        continue;
      }
      if (ObjectFile *o = dyn_cast<ObjectFile>(child.get())) {
        if (OutputFormat == sysv)
          outs() << o->getFileName() << "   (ex " << a->getFileName()
                  << "):\n";
        PrintObjectSectionSizes(o);
        if (OutputFormat == berkeley)
          outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
      }
    }
  } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
    if (OutputFormat == sysv)
      outs() << o->getFileName() << "  :\n";
    PrintObjectSectionSizes(o);
    if (OutputFormat == berkeley)
      outs() << o->getFileName() << "\n";
  } else {
    errs() << ToolName << ": " << file << ": " << "Unrecognized file type.\n";
  }
  // System V adds an extra newline at the end of each file.
  if (OutputFormat == sysv)
    outs() << "\n";
}
Exemplo n.º 14
0
Module *LoadModule(const char *filename)
{
    LLVMContext &Context = getGlobalContext();
    std::string ErrMsg;
    OwningPtr<MemoryBuffer> Buffer;
    std::string fname(filename);
    if (error_code ec = MemoryBuffer::getFile(fname, Buffer)) {
        std::cout << "Could not open file" << ec.message() << std::endl;
    }
    Module *m = ParseBitcodeFile(Buffer.get(), Context, &ErrMsg);
    if (!m) {
        std::cout << "error" << ErrMsg << std::endl;
    }
    return m;
}
void CompilerInstance::createPCHExternalASTSource(StringRef Path,
                                                  bool DisablePCHValidation,
                                                bool AllowPCHWithCompilerErrors,
                                                 void *DeserializationListener){
  OwningPtr<ExternalASTSource> Source;
  bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
                                          DisablePCHValidation,
                                          AllowPCHWithCompilerErrors,
                                          getPreprocessor(), getASTContext(),
                                          DeserializationListener,
                                          Preamble));
  ModuleManager = static_cast<ASTReader*>(Source.get());
  getASTContext().setExternalSource(Source);
}
Exemplo n.º 16
0
int main(int argc, char **argv)
{
    LLVMContext &Context = getGlobalContext();
    std::string ErrMsg;
    OwningPtr<MemoryBuffer> Buffer;
    std::string fname(argv[1]);
    if (error_code ec = MemoryBuffer::getFile(fname+".bc", Buffer)) {
        std::cout << "Could not open file" << ec.message() << std::endl;
    }
    Module *m = ParseBitcodeFile(Buffer.get(), Context, &ErrMsg);
    if (!m) {
        std::cout << "error" << ErrMsg << std::endl;
        return 1;
    }
    (*m).dump();
    return 0;
}
Exemplo n.º 17
0
int main(int argc, char **argv)
{
	if(argc < 2)
		error("Missing file name.");

	LLVMContext context;
	SMDiagnostic diag;
	OwningPtr<Module> module;
	
	module.reset(ParseIRFile(argv[1], diag, context));
	if(!module.get())
		error("Failed to load IR.");

	for(Module::iterator iter = module->begin(); iter != module->end(); iter++) {
		Function *func = iter;

		char *name = (char *)malloc(1024);
		size_t len = 1024;
		int err;

		name = abi::__cxa_demangle(func->getName().data(), name, &len, &err);
		if(err)
			continue;

		name[strlen(name)-2] = '\0';

		for(Function::iterator iter = func->begin(); iter != func->end(); iter++) {
			BasicBlock *block = iter;

			for(BasicBlock::iterator iter = block->begin(); iter != block->end(); iter++) {
				Instruction *inst = iter;

				if(inst->getOpcode() != Instruction::PtrToInt)
					continue;

				DILocation loc(inst->getMetadata("dbg"));

				printf("%s:%u\n", loc.getFilename().data(), loc.getLineNumber());
			}
		}
		free(name);
	}

	return 0;
}
Exemplo n.º 18
0
/// @brief Dumps each object file in \a Arc;
static void dumpArchive(const Archive *Arc) {
  for (Archive::child_iterator ArcI = Arc->begin_children(),
                               ArcE = Arc->end_children();
                               ArcI != ArcE; ++ArcI) {
    OwningPtr<Binary> child;
    if (error_code EC = ArcI->getAsBinary(child)) {
      // Ignore non-object files.
      if (EC != object_error::invalid_file_type)
        reportError(Arc->getFileName(), EC.message());
      continue;
    }

    if (ObjectFile *Obj = dyn_cast<ObjectFile>(child.get()))
      dumpObject(Obj);
    else
      reportError(Arc->getFileName(), readobj_error::unrecognized_file_format);
  }
}
Exemplo n.º 19
0
// LoadObject - Read in and parse the bitcode file named by FN and return the
// module it contains (wrapped in an auto_ptr), or auto_ptr<Module>() and set
// Error if an error occurs.
std::auto_ptr<Module>
Linker::LoadObject(const sys::Path &FN) {
  std::string ParseErrorMessage;
  Module *Result = 0;

  OwningPtr<MemoryBuffer> Buffer;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FN.c_str(), Buffer))
    ParseErrorMessage = "Error reading file '" + FN.str() + "'" + ": "
                      + ec.message();
  else
    Result = ParseBitcodeFile(Buffer.get(), Context, &ParseErrorMessage);

  if (Result)
    return std::auto_ptr<Module>(Result);
  Error = "Bitcode file '" + FN.str() + "' could not be loaded";
  if (ParseErrorMessage.size())
    Error += ": " + ParseErrorMessage;
  return std::auto_ptr<Module>();
}
Exemplo n.º 20
0
/// addPassesToEmitMC - Add passes to the specified pass manager to get
/// machine code emitted with the MCJIT. This method returns true if machine
/// code is not supported. It fills the MCContext Ctx pointer which can be
/// used to build custom MCStreamer.
///
bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
                                          MCContext *&Ctx,
                                          raw_ostream &Out,
                                          bool DisableVerify) {
  // Add common CodeGen passes.
  Ctx = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
  if (!Ctx)
    return true;

  if (hasMCSaveTempLabels())
    Ctx->setAllowTemporaryLabels(false);

  // Create the code emitter for the target if it exists.  If not, .o file
  // emission fails.
  const MCRegisterInfo &MRI = *getRegisterInfo();
  const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
  MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
                                                       STI, *Ctx);
  MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
                                                     TargetCPU);
  if (MCE == 0 || MAB == 0)
    return true;

  OwningPtr<MCStreamer> AsmStreamer;
  AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
                                                       *MAB, Out, MCE,
                                                       hasMCRelaxAll(),
                                                       hasMCNoExecStack()));
  AsmStreamer.get()->InitSections();

  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
  FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
  if (Printer == 0)
    return true;

  // If successful, createAsmPrinter took ownership of AsmStreamer.
  AsmStreamer.take();

  PM.add(Printer);

  return false; // success!
}
Exemplo n.º 21
0
Module* createModuleFromFile(const std::string & fileName) {

    std::string errorMessage;

    //create memory buffer for file

    OwningPtr<MemoryBuffer> fileBuffer;
    error_code e = MemoryBuffer::getFile(fileName.c_str(), fileBuffer);

    if (e) {
        errs() << "Error reading file '"
            << fileName << "': " << e.message() << "\n";
        return NULL;
    }

    if (!fileBuffer) {
        errs() << "Error reading file '" << fileName << "'.\n";
        return NULL;
    }

    if (fileBuffer->getBufferSize() & 3) {
        errs() << "Error: Bitcode stream should be "
            << "a multiple of 4 bytes in length\n";
        return NULL;
    }

    //parse file

    Module* mod = ParseBitcodeFile(fileBuffer.get(), getGlobalContext(), &errorMessage);

    if (errorMessage != "") {
        errs() << "Error reading bitcode file: " << errorMessage << "\n";
        return NULL;
    }

    if (!mod) {
        errs() << "Error reading bitcode file.\n";
        return NULL;
    }

    return mod;
}
Exemplo n.º 22
0
void MCJIT::loadObject(Module *M) {

  // Get a thread lock to make sure we aren't trying to load multiple times
  MutexGuard locked(lock);

  // FIXME: Track compilation state on a per-module basis when multiple modules
  //        are supported.
  // Re-compilation is not supported
  if (IsLoaded)
    return;

  OwningPtr<ObjectBuffer> ObjectToLoad;
  // Try to load the pre-compiled object from cache if possible
  if (0 != ObjCache) {
    OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObjectCopy(M));
    if (0 != PreCompiledObject.get())
      ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
  }

  // If the cache did not contain a suitable object, compile the object
  if (!ObjectToLoad) {
    ObjectToLoad.reset(emitObject(M));
    assert(ObjectToLoad.get() && "Compilation did not produce an object.");
  }

  // Load the object into the dynamic linker.
  // handing off ownership of the buffer
  LoadedObject.reset(Dyld.loadObject(ObjectToLoad.take()));
  if (!LoadedObject)
    report_fatal_error(Dyld.getErrorString());

  // Resolve any relocations.
  Dyld.resolveRelocations();

  // FIXME: Make this optional, maybe even move it to a JIT event listener
  LoadedObject->registerWithDebugger();

  NotifyObjectEmitted(*LoadedObject);

  // FIXME: Add support for per-module compilation state
  IsLoaded = true;
}
Exemplo n.º 23
0
bool FixItRecompile::BeginInvocation(CompilerInstance &CI) {

  std::vector<std::pair<std::string, std::string> > RewrittenFiles;
  bool err = false;
  {
    const FrontendOptions &FEOpts = CI.getFrontendOpts();
    OwningPtr<FrontendAction> FixAction(new SyntaxOnlyAction());
    if (FixAction->BeginSourceFile(CI, FEOpts.Inputs[0])) {
      OwningPtr<FixItOptions> FixItOpts;
      if (FEOpts.FixToTemporaries)
        FixItOpts.reset(new FixItRewriteToTemp());
      else
        FixItOpts.reset(new FixItRewriteInPlace());
      FixItOpts->Silent = true;
      FixItOpts->FixWhatYouCan = FEOpts.FixWhatYouCan;
      FixItOpts->FixOnlyWarnings = FEOpts.FixOnlyWarnings;
      FixItRewriter Rewriter(CI.getDiagnostics(), CI.getSourceManager(),
                             CI.getLangOpts(), FixItOpts.get());
      FixAction->Execute();
  
      err = Rewriter.WriteFixedFiles(&RewrittenFiles);
    
      FixAction->EndSourceFile();
      CI.setSourceManager(0);
      CI.setFileManager(0);
    } else {
      err = true;
    }
  }
  if (err)
    return false;
  CI.getDiagnosticClient().clear();
  CI.getDiagnostics().Reset();

  PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
  PPOpts.RemappedFiles.insert(PPOpts.RemappedFiles.end(),
                              RewrittenFiles.begin(), RewrittenFiles.end());
  PPOpts.RemappedFilesKeepOriginalName = false;

  return true;
}
Exemplo n.º 24
0
void MCJIT::generateCodeForModule(Module *M) {
  // This must be a module which has already been added to this MCJIT instance.
  assert(std::find(Modules.begin(), Modules.end(), M) != Modules.end());
  assert(ModuleStates.find(M) != ModuleStates.end());

  // Get a thread lock to make sure we aren't trying to load multiple times
  MutexGuard locked(lock);

  // Re-compilation is not supported
  if (ModuleStates[M].hasBeenLoaded())
    return;

  OwningPtr<ObjectBuffer> ObjectToLoad;
  // Try to load the pre-compiled object from cache if possible
  if (0 != ObjCache) {
    OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
    if (0 != PreCompiledObject.get())
      ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
  }

  // If the cache did not contain a suitable object, compile the object
  if (!ObjectToLoad) {
    ObjectToLoad.reset(emitObject(M));
    assert(ObjectToLoad.get() && "Compilation did not produce an object.");
  }

  // Load the object into the dynamic linker.
  // MCJIT now owns the ObjectImage pointer (via its LoadedObjects map).
  ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.take());
  LoadedObjects[M] = LoadedObject;
  if (!LoadedObject)
    report_fatal_error(Dyld.getErrorString());

  // FIXME: Make this optional, maybe even move it to a JIT event listener
  LoadedObject->registerWithDebugger();

  NotifyObjectEmitted(*LoadedObject);

  ModuleStates[M] = ModuleLoaded;
}
Exemplo n.º 25
0
bool
SimplePrinterConsumer::HandleTopLevelDecl(DeclGroupRef D) {
	if(D.begin() == D.end()) {
		return true;
	}
	Decl *firstD = *(D.begin());
	if(compInst->getSourceManager().isInSystemHeader(firstD->getLocation())) {
		return true;
	}

	PrintingPolicy policy = compInst->getASTContext().getPrintingPolicy();
	NullStmt *nullSt = new (compInst->getASTContext()) NullStmt(SourceLocation());

	for(DeclGroupRef::iterator 
		   I = D.begin(), E = D.end();
		   I != E; ++I) {
		Decl *dd = *I;

		DPRINT("PrintingPolicy: %d %d %d %d %d", policy.SuppressSpecifiers, policy.SuppressScope, policy.SuppressTag, policy.SuppressUnwrittenScope, policy.SuppressSpecifiers);
		
		dd->print(out, policy);
		nullSt->printPretty(out, NULL, policy);
		if(dd->hasBody()) {
			Stmt *ss = dd->getBody();
			// Print Stmts
			//dd->dump();
			//StmtPrinter(compInst, dd->getBody()).TraverseDecl(dd);

			// CFG
			
			OwningPtr<CFG> cfg;
			cfg.reset(CFG::buildCFG((const Decl*)dd, (Stmt*)(dd->getBody()), &compInst->getASTContext(), CFG::BuildOptions()));
			assert(cfg.get() != NULL && "build CFG failed.");
			cfg->dump(compInst->getLangOpts(), true);
			cfg->viewCFG(compInst->getLangOpts());
		}
	}
	return true;
};
Exemplo n.º 26
0
int main(int argc, char **argv) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
  
  cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");

  // Read in the bitcode file...
  std::string ErrorMessage;
  OwningPtr<MemoryBuffer> Buffer;
  error_code ec;
  Module *M = 0;
  if (!(ec = MemoryBuffer::getFileOrSTDIN(BitcodeFile, Buffer))) {
    M = ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage);
  } else
    ErrorMessage = ec.message();
  if (M == 0) {
    errs() << argv[0] << ": " << BitcodeFile << ": "
      << ErrorMessage << "\n";
    return 1;
  }

  // Read the profiling information. This is redundant since we load it again
  // using the standard profile info provider pass, but for now this gives us
  // access to additional information not exposed via the ProfileInfo
  // interface.
  ProfileInfoLoader PIL(argv[0], ProfileDataFile);

  // Run the printer pass.
  PassManager PassMgr;
  PassMgr.add(createProfileLoaderPass(ProfileDataFile));
  PassMgr.add(new ProfileInfoPrinterPass(PIL));
  PassMgr.run(*M);

  return 0;
}
Exemplo n.º 27
0
// Get just the externally visible defined symbols from the bitcode
bool llvm::GetBitcodeSymbols(const sys::Path& fName,
                             LLVMContext& Context,
                             std::vector<std::string>& symbols,
                             std::string* ErrMsg) {
  OwningPtr<MemoryBuffer> Buffer;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(fName.c_str(), Buffer)) {
    if (ErrMsg) *ErrMsg = "Could not open file '" + fName.str() + "'" + ": "
                        + ec.message();
    return true;
  }

  Module *M = ParseBitcodeFile(Buffer.get(), Context, ErrMsg);
  if (!M)
    return true;

  // Get the symbols
  getSymbols(M, symbols);

  // Done with the module.
  delete M;
  return true;
}
Exemplo n.º 28
0
/// addPassesToEmitMC - Add passes to the specified pass manager to get
/// machine code emitted with the MCJIT. This method returns true if machine
/// code is not supported. It fills the MCContext Ctx pointer which can be
/// used to build custom MCStreamer.
///
bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
                                          MCContext *&Ctx,
                                          raw_ostream &Out,
                                          CodeGenOpt::Level OptLevel,
                                          bool DisableVerify) {
  // Add common CodeGen passes.
  if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
    return true;

  // Create the code emitter for the target if it exists.  If not, .o file
  // emission fails.
  MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Ctx);
  TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
  if (MCE == 0 || TAB == 0)
    return true;

  OwningPtr<MCStreamer> AsmStreamer;
  AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Ctx,
                                                     *TAB, Out, MCE,
                                                     hasMCRelaxAll(),
                                                     hasMCNoExecStack()));
  AsmStreamer.get()->InitSections();

  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
  FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
  if (Printer == 0)
    return true;

  // If successful, createAsmPrinter took ownership of AsmStreamer.
  AsmStreamer.take();

  PM.add(Printer);

  // Make sure the code model is set.
  setCodeModelForJIT();

  return false; // success!
}
Exemplo n.º 29
0
static void DumpSymbolNamesFromFile(std::string &Filename) {
  if (Filename != "-" && !sys::fs::exists(Filename)) {
    errs() << ToolName << ": '" << Filename << "': " << "No such file\n";
    return;
  }

  OwningPtr<MemoryBuffer> Buffer;
  if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
    return;

  sys::fs::file_magic magic = sys::fs::identify_magic(Buffer->getBuffer());

  LLVMContext &Context = getGlobalContext();
  std::string ErrorMessage;
  if (magic == sys::fs::file_magic::bitcode) {
    Module *Result = 0;
    Result = ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage);
    if (Result) {
      DumpSymbolNamesFromModule(Result);
      delete Result;
    } else {
      error(ErrorMessage, Filename);
      return;
    }
  } else if (magic == sys::fs::file_magic::archive) {
    OwningPtr<Binary> arch;
    if (error(object::createBinary(Buffer.take(), arch), Filename))
      return;

    if (object::Archive *a = dyn_cast<object::Archive>(arch.get())) {
      if (ArchiveMap) {
        outs() << "Archive map" << "\n";
        for (object::Archive::symbol_iterator i = a->begin_symbols(), 
             e = a->end_symbols(); i != e; ++i) {
          object::Archive::child_iterator c;
          StringRef symname;
          StringRef filename;
          if (error(i->getMember(c))) 
              return;
          if (error(i->getName(symname)))
              return;
          if (error(c->getName(filename)))
              return;
          outs() << symname << " in " << filename << "\n";
        }
        outs() << "\n";
      }

      for (object::Archive::child_iterator i = a->begin_children(),
                                           e = a->end_children(); i != e; ++i) {
        OwningPtr<Binary> child;
        if (i->getAsBinary(child)) {
          // Try opening it as a bitcode file.
          OwningPtr<MemoryBuffer> buff(i->getBuffer());
          Module *Result = 0;
          if (buff)
            Result = ParseBitcodeFile(buff.get(), Context, &ErrorMessage);

          if (Result) {
            DumpSymbolNamesFromModule(Result);
            delete Result;
          }
          continue;
        }
        if (object::ObjectFile *o = dyn_cast<ObjectFile>(child.get())) {
          outs() << o->getFileName() << ":\n";
          DumpSymbolNamesFromObject(o);
        }
      }
    }
  } else if (magic.is_object()) {
    OwningPtr<Binary> obj;
    if (error(object::createBinary(Buffer.take(), obj), Filename))
      return;
    if (object::ObjectFile *o = dyn_cast<ObjectFile>(obj.get()))
      DumpSymbolNamesFromObject(o);
  } else {
    errs() << ToolName << ": " << Filename << ": "
           << "unrecognizable file type\n";
    return;
  }
}
Exemplo n.º 30
0
//===----------------------------------------------------------------------===//
// main for opt
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
  LLVMContext &Context = getGlobalContext();

  InitializeAllTargets();
  InitializeAllTargetMCs();

  // Initialize passes
  PassRegistry &Registry = *PassRegistry::getPassRegistry();
  initializeCore(Registry);
  initializeScalarOpts(Registry);
  initializeObjCARCOpts(Registry);
  initializeVectorization(Registry);
  initializeIPO(Registry);
  initializeAnalysis(Registry);
  initializeIPA(Registry);
  initializeTransformUtils(Registry);
  initializeInstCombine(Registry);
  initializeInstrumentation(Registry);
  initializeTarget(Registry);
  // @LOCALMOD-BEGIN
  initializeAddPNaClExternalDeclsPass(Registry);
  initializeCanonicalizeMemIntrinsicsPass(Registry);
  initializeExpandArithWithOverflowPass(Registry);
  initializeExpandByValPass(Registry);
  initializeExpandConstantExprPass(Registry);
  initializeExpandCtorsPass(Registry);
  initializeExpandGetElementPtrPass(Registry);
  initializeExpandSmallArgumentsPass(Registry);
  initializeExpandStructRegsPass(Registry);
  initializeExpandTlsConstantExprPass(Registry);
  initializeExpandTlsPass(Registry);
  initializeExpandVarArgsPass(Registry);
  initializeFlattenGlobalsPass(Registry);
  initializeGlobalCleanupPass(Registry);
  initializeInsertDivideCheckPass(Registry);
  initializePNaClABIVerifyFunctionsPass(Registry);
  initializePNaClABIVerifyModulePass(Registry);
  initializePNaClSjLjEHPass(Registry);
  initializePromoteI1OpsPass(Registry);
  initializePromoteIntegersPass(Registry);
  initializeRemoveAsmMemoryPass(Registry);
  initializeReplacePtrsWithIntsPass(Registry);
  initializeResolveAliasesPass(Registry);
  initializeResolvePNaClIntrinsicsPass(Registry);
  initializeRewriteAtomicsPass(Registry);
  initializeRewriteLLVMIntrinsicsPass(Registry);
  initializeRewritePNaClLibraryCallsPass(Registry);
  initializeStripAttributesPass(Registry);
  initializeStripMetadataPass(Registry);
  initializeExpandI64Pass(Registry);
  // @LOCALMOD-END

  cl::ParseCommandLineOptions(argc, argv,
    "llvm .bc -> .bc modular optimizer and analysis printer\n");

  if (AnalyzeOnly && NoOutput) {
    errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
    return 1;
  }

  SMDiagnostic Err;

  // Load the input module...
  OwningPtr<Module> M;
  M.reset(ParseIRFile(InputFilename, Err, Context));

  if (M.get() == 0) {
    Err.print(argv[0], errs());
    return 1;
  }

  // If we are supposed to override the target triple, do so now.
  if (!TargetTriple.empty())
    M->setTargetTriple(Triple::normalize(TargetTriple));

  // Figure out what stream we are supposed to write to...
  OwningPtr<tool_output_file> Out;
  if (NoOutput) {
    if (!OutputFilename.empty())
      errs() << "WARNING: The -o (output filename) option is ignored when\n"
                "the --disable-output option is used.\n";
  } else {
    // Default to standard output.
    if (OutputFilename.empty())
      OutputFilename = "-";

    std::string ErrorInfo;
    Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
                                   raw_fd_ostream::F_Binary));
    if (!ErrorInfo.empty()) {
      errs() << ErrorInfo << '\n';
      return 1;
    }
  }

  // If the output is set to be emitted to standard out, and standard out is a
  // console, print out a warning message and refuse to do it.  We don't
  // impress anyone by spewing tons of binary goo to a terminal.
  if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
    if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
      NoOutput = true;

  // Create a PassManager to hold and optimize the collection of passes we are
  // about to build.
  //
  PassManager Passes;

  // Add an appropriate TargetLibraryInfo pass for the module's triple.
  TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));

  // The -disable-simplify-libcalls flag actually disables all builtin optzns.
  if (DisableSimplifyLibCalls)
    TLI->disableAllFunctions();
  Passes.add(TLI);

  // Add an appropriate DataLayout instance for this module.
  DataLayout *TD = 0;
  const std::string &ModuleDataLayout = M.get()->getDataLayout();
  if (!ModuleDataLayout.empty())
    TD = new DataLayout(ModuleDataLayout);
  else if (!DefaultDataLayout.empty())
    TD = new DataLayout(DefaultDataLayout);

  if (TD)
    Passes.add(TD);

  Triple ModuleTriple(M->getTargetTriple());
  TargetMachine *Machine = 0;
  if (ModuleTriple.getArch())
    Machine = GetTargetMachine(Triple(ModuleTriple));
  OwningPtr<TargetMachine> TM(Machine);

  // Add internal analysis passes from the target machine.
  if (TM.get())
    TM->addAnalysisPasses(Passes);

  OwningPtr<FunctionPassManager> FPasses;
  if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
    FPasses.reset(new FunctionPassManager(M.get()));
    if (TD)
      FPasses->add(new DataLayout(*TD));
  }

  if (PrintBreakpoints) {
    // Default to standard output.
    if (!Out) {
      if (OutputFilename.empty())
        OutputFilename = "-";

      std::string ErrorInfo;
      Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
                                     raw_fd_ostream::F_Binary));
      if (!ErrorInfo.empty()) {
        errs() << ErrorInfo << '\n';
        return 1;
      }
    }
    Passes.add(new BreakpointPrinter(Out->os()));
    NoOutput = true;
  }

  // If the -strip-debug command line option was specified, add it.  If
  // -std-compile-opts was also specified, it will handle StripDebug.
  if (StripDebug && !StandardCompileOpts)
    addPass(Passes, createStripSymbolsPass(true));

  // Create a new optimization pass for each one specified on the command line
  for (unsigned i = 0; i < PassList.size(); ++i) {
    // Check to see if -std-compile-opts was specified before this option.  If
    // so, handle it.
    if (StandardCompileOpts &&
        StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
      AddStandardCompilePasses(Passes);
      StandardCompileOpts = false;
    }

    if (StandardLinkOpts &&
        StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
      AddStandardLinkPasses(Passes);
      StandardLinkOpts = false;
    }

    if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
      AddOptimizationPasses(Passes, *FPasses, 1, 0);
      OptLevelO1 = false;
    }

    if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
      AddOptimizationPasses(Passes, *FPasses, 2, 0);
      OptLevelO2 = false;
    }

    if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
      AddOptimizationPasses(Passes, *FPasses, 2, 1);
      OptLevelOs = false;
    }

    if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
      AddOptimizationPasses(Passes, *FPasses, 2, 2);
      OptLevelOz = false;
    }

    if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
      AddOptimizationPasses(Passes, *FPasses, 3, 0);
      OptLevelO3 = false;
    }

    // @LOCALMOD-BEGIN
    if (PNaClABISimplifyPreOpt &&
        PNaClABISimplifyPreOpt.getPosition() < PassList.getPosition(i)) {
      PNaClABISimplifyAddPreOptPasses(Passes);
      PNaClABISimplifyPreOpt = false;
    }

    if (PNaClABISimplifyPostOpt &&
        PNaClABISimplifyPostOpt.getPosition() < PassList.getPosition(i)) {
      PNaClABISimplifyAddPostOptPasses(Passes);
      PNaClABISimplifyPostOpt = false;
    }
    // @LOCALMOD-END

    const PassInfo *PassInf = PassList[i];
    Pass *P = 0;
    if (PassInf->getNormalCtor())
      P = PassInf->getNormalCtor()();
    else
      errs() << argv[0] << ": cannot create pass: "******"\n";
    if (P) {
      PassKind Kind = P->getPassKind();
      addPass(Passes, P);

      if (AnalyzeOnly) {
        switch (Kind) {
        case PT_BasicBlock:
          Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
          break;
        case PT_Region:
          Passes.add(new RegionPassPrinter(PassInf, Out->os()));
          break;
        case PT_Loop:
          Passes.add(new LoopPassPrinter(PassInf, Out->os()));
          break;
        case PT_Function:
          Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
          break;
        case PT_CallGraphSCC:
          Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
          break;
        default:
          Passes.add(new ModulePassPrinter(PassInf, Out->os()));
          break;
        }
      }
    }

    if (PrintEachXForm)
      Passes.add(createPrintModulePass(&errs()));
  }

  // If -std-compile-opts was specified at the end of the pass list, add them.
  if (StandardCompileOpts) {
    AddStandardCompilePasses(Passes);
    StandardCompileOpts = false;
  }

  if (StandardLinkOpts) {
    AddStandardLinkPasses(Passes);
    StandardLinkOpts = false;
  }

  if (OptLevelO1)
    AddOptimizationPasses(Passes, *FPasses, 1, 0);

  if (OptLevelO2)
    AddOptimizationPasses(Passes, *FPasses, 2, 0);

  if (OptLevelOs)
    AddOptimizationPasses(Passes, *FPasses, 2, 1);

  if (OptLevelOz)
    AddOptimizationPasses(Passes, *FPasses, 2, 2);

  if (OptLevelO3)
    AddOptimizationPasses(Passes, *FPasses, 3, 0);

  if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
    FPasses->doInitialization();
    for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
      FPasses->run(*F);
    FPasses->doFinalization();
  }

  // @LOCALMOD-BEGIN
  if (PNaClABISimplifyPreOpt)
    PNaClABISimplifyAddPreOptPasses(Passes);

  if (PNaClABISimplifyPostOpt)
    PNaClABISimplifyAddPostOptPasses(Passes);
  // @LOCALMOD-END

  // Check that the module is well formed on completion of optimization
  if (!NoVerify && !VerifyEach)
    Passes.add(createVerifierPass());

  // Write bitcode or assembly to the output as the last step...
  if (!NoOutput && !AnalyzeOnly) {
    if (OutputAssembly)
      Passes.add(createPrintModulePass(&Out->os()));
    // @LOCALMOD
  }

  // Before executing passes, print the final values of the LLVM options.
  cl::PrintOptionValues();

  // Now that we have all of the passes ready, run them.
  Passes.run(*M.get());

// @LOCALMOD-BEGIN
  // Write bitcode to the output.
  if (!NoOutput && !AnalyzeOnly && !OutputAssembly) {
    switch (OutputFileFormat) {
      case LLVMFormat:
        WriteBitcodeToFile(M.get(), Out->os());
        break;
      case PNaClFormat:
        NaClWriteBitcodeToFile(M.get(), Out->os());
        break;
      default:
        errs() << "Don't understand bitcode format for generated bitcode.\n";
        return 1;
    }
  }
// @LOCALMOD-END

  // Declare success.
  if (!NoOutput || PrintBreakpoints)
    Out->keep();

  return 0;
}