Example #1
1
static void addStaticGEPCheckingPass(PassManager & Passes) {
#if 0
	switch (SCConfig.staticCheckType()) {
		case SAFECodeConfiguration::ABC_CHECK_NONE:
			Passes.add(new ArrayBoundsCheckDummy());
			break;
		case SAFECodeConfiguration::ABC_CHECK_LOCAL:
#if 0
      if (SCConfig.getPAType() == SAFECodeConfiguration::PA_APA) {
        Passes.add(new ArrayBoundsCheckStruct());
      }
#endif
			Passes.add(new ArrayBoundsCheckLocal());
			break;
		case SAFECodeConfiguration::ABC_CHECK_FULL:
#if 0
      if (SCConfig.getPAType() == SAFECodeConfiguration::PA_APA) {
        Passes.add(new ArrayBoundsCheckStruct());
      }
#endif
#if 0
			Passes.add(new ArrayBoundsCheck());
#else
			assert (0 && "Omega pass is not working right now!");
#endif
			break;
	}
#endif
}
Example #2
0
int
main (int argc, char **argv, const char **env) {
  // This boilerplate provides convenient stack traces and clean LLVM exit
  // handling. It also initializes the built in support for convenient
  // command line option handling.
  sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram X{argc, argv};
  llvm_shutdown_obj shutdown;
  cl::ParseCommandLineOptions(argc, argv);

  // Construct an IR file from the filename passed on the command line.
  LLVMContext &context = getGlobalContext();
  SMDiagnostic err;
  unique_ptr<Module> module = parseIRFile(inPath.getValue(), err, context);

  if (!module.get()) {
    errs() << "Error reading bitcode file.\n";
    err.print(argv[0], errs());
    return -1;
  }

  // Build up all of the passes that we want to run on the module.
  PassManager pm;
  pm.add(new callgraphs::CallGraphPass);
  pm.add(new callgraphs::WeightedCallGraphPass);
  pm.add(new CallGraphPrinter<callgraphs::WeightedCallGraphPass>(outs()));
  pm.run(*module);

  return 0;
}
Example #3
0
int main(int argc, char **argv) {
  // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
  llvm::PrettyStackTraceProgram X(argc, argv);
  cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
  llvm_shutdown_obj Y;

  std::auto_ptr<Module> M(new Module("/tmp/autogen.bc", getGlobalContext()));
  Function *F = GenEmptyFunction(M.get());
  FillFunction(F);
  IntroduceControlFlow(F);

  // Figure out what stream we are supposed to write to...
  OwningPtr<tool_output_file> Out;
  // 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;
  }

  PassManager Passes;
  Passes.add(createVerifierPass());
  Passes.add(createPrintModulePass(&Out->os()));
  Passes.run(*M.get());
  Out->keep();

  return 0;
}
static void AddTargetTranslationPass(PassManager &PM) {
  ExpandVAArgPass *VAArgPass = NULL;
  ReplaceUnwindHeaderSizePass *UnwindPass = NULL;

  if (ArchName == "arm") {
    VAArgPass = createARMExpandVAArgPass();
    UnwindPass = createARMReplaceUnwindHeaderSizePass();
  } else if (ArchName == "x86") {
    VAArgPass = createX86ExpandVAArgPass();
    UnwindPass = createX86ReplaceUnwindHeaderSizePass();
  } else if (ArchName == "mips") {
    VAArgPass = createMipsExpandVAArgPass();
    UnwindPass = createMipsReplaceUnwindHeaderSizePass();
  } else if (ArchName == "arm64") {
    VAArgPass = createArm64ExpandVAArgPass();
    UnwindPass = createX86ReplaceUnwindHeaderSizePass();  // the same as x86
  } else if (ArchName == "x86_64") {
    VAArgPass = createX86_64ExpandVAArgPass();
    UnwindPass = createX86ReplaceUnwindHeaderSizePass();  // the same as x86
  } else if (ArchName == "mips64") {
    VAArgPass = createMips64ExpandVAArgPass();
    UnwindPass = createX86ReplaceUnwindHeaderSizePass();  // the same as x86
  } else {
    errs() << "'" << ArchName << "' is not supported!\n";
    exit(1);
  }

  // Add target specific pass
  PM.add(new DataLayoutPass());
  if (VAArgPass)
    PM.add(VAArgPass);
  if (UnwindPass)
    PM.add(UnwindPass);
}
Example #5
0
/// Optimize merged modules using various IPO passes
bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
                                          bool DisableOpt,
                                          bool DisableInline,
                                          bool DisableGVNLoadPRE,
                                          std::string &errMsg) {
  if (!this->determineTarget(errMsg))
    return false;

  Module *mergedModule = Linker.getModule();

  // Mark which symbols can not be internalized
  this->applyScopeRestrictions();

  // Instantiate the pass manager to organize the passes.
  PassManager passes;

  // Start off with a verification pass.
  passes.add(createVerifierPass());

  // Add an appropriate DataLayout instance for this module...
  passes.add(new DataLayout(*TargetMach->getDataLayout()));
  TargetMach->addAnalysisPasses(passes);

  // Enabling internalize here would use its AllButMain variant. It
  // keeps only main if it exists and does nothing for libraries. Instead
  // we create the pass ourselves with the symbol list provided by the linker.
  if (!DisableOpt)
    PassManagerBuilder().populateLTOPassManager(passes,
                                              /*Internalize=*/false,
                                              !DisableInline,
                                              DisableGVNLoadPRE);

  // Make sure everything is still good.
  passes.add(createVerifierPass());

  PassManager codeGenPasses;

  codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
  TargetMach->addAnalysisPasses(codeGenPasses);

  formatted_raw_ostream Out(out);

  // If the bitcode files contain ARC code and were compiled with optimization,
  // the ObjCARCContractPass must be run, so do it unconditionally here.
  codeGenPasses.add(createObjCARCContractPass());

  if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
                                      TargetMachine::CGFT_ObjectFile)) {
    errMsg = "target file type not supported";
    return false;
  }

  // Run our queue of passes all at once now, efficiently.
  passes.run(*mergedModule);

  // Run the code generator, and write assembly file
  codeGenPasses.run(*mergedModule);

  return true;
}
Example #6
0
void LTOCodeGenerator::applyScopeRestrictions() {
  if (ScopeRestrictionsDone)
    return;
  Module *mergedModule = Linker.getModule();

  // Start off with a verification pass.
  PassManager passes;
  passes.add(createVerifierPass());

  // mark which symbols can not be internalized
  Mangler Mangler(TargetMach);
  std::vector<const char*> MustPreserveList;
  SmallPtrSet<GlobalValue*, 8> AsmUsed;
  std::vector<StringRef> Libcalls;
  TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
  accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());

  for (Module::iterator f = mergedModule->begin(),
         e = mergedModule->end(); f != e; ++f)
    applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
  for (Module::global_iterator v = mergedModule->global_begin(),
         e = mergedModule->global_end(); v !=  e; ++v)
    applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
  for (Module::alias_iterator a = mergedModule->alias_begin(),
         e = mergedModule->alias_end(); a != e; ++a)
    applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);

  GlobalVariable *LLVMCompilerUsed =
    mergedModule->getGlobalVariable("llvm.compiler.used");
  findUsedValues(LLVMCompilerUsed, AsmUsed);
  if (LLVMCompilerUsed)
    LLVMCompilerUsed->eraseFromParent();

  if (!AsmUsed.empty()) {
    llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
    std::vector<Constant*> asmUsed2;
    for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
           e = AsmUsed.end(); i !=e; ++i) {
      GlobalValue *GV = *i;
      Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
      asmUsed2.push_back(c);
    }

    llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
    LLVMCompilerUsed =
      new llvm::GlobalVariable(*mergedModule, ATy, false,
                               llvm::GlobalValue::AppendingLinkage,
                               llvm::ConstantArray::get(ATy, asmUsed2),
                               "llvm.compiler.used");

    LLVMCompilerUsed->setSection("llvm.metadata");
  }

  passes.add(createInternalizePass(MustPreserveList));

  // apply scope restrictions
  passes.run(*mergedModule);

  ScopeRestrictionsDone = true;
}
Example #7
0
void MipsLinkingContext::addPasses(PassManager &pm) {
    auto pass = createMipsRelocationPass(*this);
    if (pass)
        pm.add(std::move(pass));
    ELFLinkingContext::addPasses(pm);
    pm.add(llvm::make_unique<elf::MipsCtorsOrderPass>());
}
void LTOCodeGenerator::applyScopeRestrictions() {
  if (_scopeRestrictionsDone) return;
  Module *mergedModule = _linker.getModule();

  // Start off with a verification pass.
  PassManager passes;
  passes.add(createVerifierPass());

  // mark which symbols can not be internalized 
  if (!_mustPreserveSymbols.empty()) {
    MCContext Context(*_target->getMCAsmInfo(), NULL);
    Mangler mangler(Context, *_target->getTargetData());
    std::vector<const char*> mustPreserveList;
    for (Module::iterator f = mergedModule->begin(),
         e = mergedModule->end(); f != e; ++f) {
      if (!f->isDeclaration() &&
          _mustPreserveSymbols.count(mangler.getNameWithPrefix(f)))
        mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
    }
    for (Module::global_iterator v = mergedModule->global_begin(), 
         e = mergedModule->global_end(); v !=  e; ++v) {
      if (!v->isDeclaration() &&
          _mustPreserveSymbols.count(mangler.getNameWithPrefix(v)))
        mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
    }
    passes.add(createInternalizePass(mustPreserveList));
  }
  
  // apply scope restrictions
  passes.run(*mergedModule);
  
  _scopeRestrictionsDone = true;
}
Example #9
0
void LTOCodeGenerator::applyScopeRestrictions() {
  if (_scopeRestrictionsDone) return;
  Module *mergedModule = _linker.getModule();

  // Start off with a verification pass.
  PassManager passes;
  passes.add(createVerifierPass());

  // mark which symbols can not be internalized
  MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
  Mangler mangler(Context, *_target->getTargetData());
  std::vector<const char*> mustPreserveList;
  SmallPtrSet<GlobalValue*, 8> asmUsed;

  for (Module::iterator f = mergedModule->begin(),
         e = mergedModule->end(); f != e; ++f)
    applyRestriction(*f, mustPreserveList, asmUsed, mangler);
  for (Module::global_iterator v = mergedModule->global_begin(),
         e = mergedModule->global_end(); v !=  e; ++v)
    applyRestriction(*v, mustPreserveList, asmUsed, mangler);
  for (Module::alias_iterator a = mergedModule->alias_begin(),
         e = mergedModule->alias_end(); a != e; ++a)
    applyRestriction(*a, mustPreserveList, asmUsed, mangler);

  GlobalVariable *LLVMCompilerUsed =
    mergedModule->getGlobalVariable("llvm.compiler.used");
  findUsedValues(LLVMCompilerUsed, asmUsed);
  if (LLVMCompilerUsed)
    LLVMCompilerUsed->eraseFromParent();

  llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
  std::vector<Constant*> asmUsed2;
  for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
         e = asmUsed.end(); i !=e; ++i) {
    GlobalValue *GV = *i;
    Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
    asmUsed2.push_back(c);
  }

  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
  LLVMCompilerUsed =
    new llvm::GlobalVariable(*mergedModule, ATy, false,
                             llvm::GlobalValue::AppendingLinkage,
                             llvm::ConstantArray::get(ATy, asmUsed2),
                             "llvm.compiler.used");

  LLVMCompilerUsed->setSection("llvm.metadata");

  // Add prerequisite passes needed by SAFECode
  PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/ false,
                                              !DisableInline);

  passes.add(createInternalizePass(mustPreserveList));

  // apply scope restrictions
  passes.run(*mergedModule);

  _scopeRestrictionsDone = true;
}
/// Optimize merged modules using various IPO passes
bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
                                            std::string& errMsg)
{
    if ( this->determineTarget(errMsg) ) 
        return true;

    // mark which symbols can not be internalized 
    this->applyScopeRestrictions();

    Module* mergedModule = _linker.getModule();

    // if options were requested, set them
    if ( !_codegenOptions.empty() )
        cl::ParseCommandLineOptions(_codegenOptions.size(), 
                                    const_cast<char **>(&_codegenOptions[0]));

    // Instantiate the pass manager to organize the passes.
    PassManager passes;

    // Start off with a verification pass.
    passes.add(createVerifierPass());

    // Add an appropriate TargetData instance for this module...
    passes.add(new TargetData(*_target->getTargetData()));
    
    createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
                            /*VerifyEach=*/ false);

    // Make sure everything is still good.
    passes.add(createVerifierPass());

    FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);

    codeGenPasses->add(new TargetData(*_target->getTargetData()));

    formatted_raw_ostream Out(out);

    if (_target->addPassesToEmitFile(*codeGenPasses, Out,
                                     TargetMachine::CGFT_AssemblyFile,
                                     CodeGenOpt::Aggressive)) {
      errMsg = "target file type not supported";
      return true;
    }

    // Run our queue of passes all at once now, efficiently.
    passes.run(*mergedModule);

    // Run the code generator, and write assembly file
    codeGenPasses->doInitialization();

    for (Module::iterator
           it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
      if (!it->isDeclaration())
        codeGenPasses->run(*it);

    codeGenPasses->doFinalization();

    return false; // success
}
Example #11
0
/// Optimize merged modules using various IPO passes
bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
                                          bool DisableOpt,
                                          bool DisableInline,
                                          bool DisableGVNLoadPRE,
                                          bool DisableVectorization,
                                          std::string &errMsg) {
  if (!this->determineTarget(errMsg))
    return false;

  Module *mergedModule = IRLinker.getModule();

  // Mark which symbols can not be internalized
  this->applyScopeRestrictions();

  // Instantiate the pass manager to organize the passes.
  PassManager passes;

  // Add an appropriate DataLayout instance for this module...
  mergedModule->setDataLayout(TargetMach->getSubtargetImpl()->getDataLayout());

  Triple TargetTriple(TargetMach->getTargetTriple());
  PassManagerBuilder PMB;
  PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
  PMB.LoopVectorize = !DisableVectorization;
  PMB.SLPVectorize = !DisableVectorization;
  if (!DisableInline)
    PMB.Inliner = createFunctionInliningPass();
  PMB.LibraryInfo = new TargetLibraryInfo(TargetTriple);
  if (DisableOpt)
    PMB.OptLevel = 0;
  PMB.VerifyInput = true;
  PMB.VerifyOutput = true;

  PMB.populateLTOPassManager(passes, TargetMach);

  PassManager codeGenPasses;

  codeGenPasses.add(new DataLayoutPass());

  formatted_raw_ostream Out(out);

  // If the bitcode files contain ARC code and were compiled with optimization,
  // the ObjCARCContractPass must be run, so do it unconditionally here.
  codeGenPasses.add(createObjCARCContractPass());

  if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
                                      TargetMachine::CGFT_ObjectFile)) {
    errMsg = "target file type not supported";
    return false;
  }

  // Run our queue of passes all at once now, efficiently.
  passes.run(*mergedModule);

  // Run the code generator, and write assembly file
  codeGenPasses.run(*mergedModule);

  return true;
}
Example #12
0
void PECOFFLinkingContext::addPasses(PassManager &pm) {
  pm.add(llvm::make_unique<pecoff::PDBPass>(*this));
  pm.add(llvm::make_unique<pecoff::EdataPass>(*this));
  pm.add(llvm::make_unique<pecoff::IdataPass>(*this));
  pm.add(llvm::make_unique<pecoff::OrderPass>());
  pm.add(llvm::make_unique<pecoff::LoadConfigPass>(*this));
  pm.add(llvm::make_unique<pecoff::InferSubsystemPass>(*this));
}
Example #13
0
static void
countStaticCalls(Module &m) {
  // Build up all of the passes that we want to run on the module.
  PassManager pm;
  pm.add(new callcounter::StaticCallCounter());
  pm.add(new StaticCountPrinter(outs()));
  pm.run(m);
}
Example #14
0
// A utility function that adds a pass to the pass manager but will also add
// a verifier pass after if we're supposed to verify.
static inline void addPass(PassManager &PM, Pass *P) {
  // Add the pass to the pass manager...
  PM.add(P);

  // If we are verifying all of the intermediate steps, add the verifier...
  if (VerifyEach)
    PM.add(createVerifierPass());
}
Example #15
0
void Optimize(llvm::Module *M, int OptLevel, int SizeLevel, int Verify) {

    // 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.
    const DataLayout *DL = M->getDataLayout();
    if (DL)
      Passes.add(new DataLayoutPass());

    Triple ModuleTriple(M->getTargetTriple());
    TargetMachine *Machine = nullptr;
    if (ModuleTriple.getArch())
      Machine = GetTargetMachine(Triple(ModuleTriple), OptLevel);
    std::unique_ptr<TargetMachine> TM(Machine);

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

    std::unique_ptr<FunctionPassManager> FPasses;
    if (OptLevel > 0 || SizeLevel > 0) {
      FPasses.reset(new FunctionPassManager(M));
      if (DL)
        FPasses->add(new DataLayoutPass());
      if (TM.get())
        TM->addAnalysisPasses(*FPasses);

    }

    AddOptimizationPasses(Passes, *FPasses, OptLevel, SizeLevel);

    if (OptLevel > 0 || SizeLevel > 0) {
      FPasses->doInitialization();
      for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
        FPasses->run(*F);
      FPasses->doFinalization();
    }

    // Check that the module is well formed on completion of optimization
    if (Verify) {
      Passes.add(createVerifierPass());
      Passes.add(createDebugInfoVerifierPass());
    }

    // Now that we have all of the passes ready, run them.
    Passes.run(*M);
}
Example #16
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;
}
Example #17
0
Module * llvmutil_extractmodule(Module * OrigMod, TargetMachine * TM, std::vector<llvm::GlobalValue*> * livevalues, std::vector<std::string> * symbolnames, bool internalizeandoptimize) {
        assert(symbolnames == NULL || livevalues->size() == symbolnames->size());
        ValueToValueMapTy VMap;
        #if LLVM_VERSION >= 34
        Module * M = llvmutil_extractmodulewithproperties(OrigMod->getModuleIdentifier(), OrigMod, (llvm::GlobalValue **)&(*livevalues)[0], livevalues->size(), AlwaysCopy, NULL, VMap);
        #else
        Module * M = CloneModule(OrigMod, VMap);
        internalizeandoptimize = true; //we need to do this regardless of the input because it is the only way we can extract just the needed functions from the module
        #endif

        //rename values to symbolsnames
        std::vector<const char *> names;
        for(size_t i = 0; i < livevalues->size(); i++) {
            GlobalValue * fn = cast<GlobalValue>(VMap[(*livevalues)[i]]);
            const std::string & name = (*symbolnames)[i];
            GlobalValue * gv = M->getNamedValue(name);
            if(gv) { //if there is already a symbol with this name, rename it
                gv->setName(Twine((*symbolnames)[i],"_renamed"));
            }
            fn->setName(name); //and set our function to this name
            assert(fn->getName() == name);
            names.push_back(name.c_str()); //internalize pass has weird interface, so we need to copy the names here
        }
        
        if (!internalizeandoptimize)
            return M;
    
        //at this point we run optimizations on the module
        //first internalize all functions not mentioned in "names" using an internalize pass and then perform 
        //standard optimizations
        PassManager MPM;
        llvmutil_addtargetspecificpasses(&MPM, TM);
    
        MPM.add(createVerifierPass()); //make sure we haven't messed stuff up yet
        MPM.add(createInternalizePass(names));
        MPM.add(createGlobalDCEPass()); //run this early since anything not in the table of exported functions is still in this module
                                         //this will remove dead functions
        
        PassManagerBuilder PMB;
        PMB.OptLevel = 3;
        PMB.SizeLevel = 0;
    
#if LLVM_VERSION >= 35
        PMB.LoopVectorize = true;
        PMB.SLPVectorize = true;
#endif

        PMB.populateModulePassManager(MPM);
    
        MPM.run(*M);
    

        return M;
}
Example #18
0
int main(int argc, char **argv) {

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

  // Load the input module...
  std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));


    if (M.get() == 0) {
    cerr << "bytecode didn't read correctly.\n";
    return 1;
  }

  // Figure out what stream we are supposed to write to...

  std::ostream *Out = &std::cout;  // Default to printing to stdout...


  if (OutputFilename != "") {
    Out = new std::ofstream(OutputFilename.c_str());
    

    if (!Out->good()) {
      cerr << "Error opening " << OutputFilename << "!\n";
      return 1;
    }
    
  }
    
    
  //
  PassManager Passes;
  Passes.add(new DataLayout("embec", M.get()));
  
  //Add passes
  Passes.add(createCZeroUninitPtrPass());
  /*
  Passes.add(createABCPreProcessPass());
  Passes.add(createArrayBoundsCheckPass());
  Passes.add(createStackSafetyPass());
  */
  Passes.add(createEmbeCFreeRemovalPass());
 
  // Now that we have all of the passes ready, run them.
  if (Passes.run(*M.get()))
    cerr << "Program modified.\n";
  (*Out) << M.get();
  //  WriteToC(M.get(), *Out, false);

  return 0;
}
Example #19
0
bool ReduceCrashingInstructions::TestInsts(std::vector<const Instruction*>
                                           &Insts) {
  // Clone the program to try hacking it apart...
  ValueToValueMapTy VMap;
  Module *M = CloneModule(BD.getProgram(), VMap);

  // Convert list to set for fast lookup...
  SmallPtrSet<Instruction*, 64> Instructions;
  for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
    assert(!isa<TerminatorInst>(Insts[i]));
    Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
  }

  outs() << "Checking for crash with only " << Instructions.size();
  if (Instructions.size() == 1)
    outs() << " instruction: ";
  else
    outs() << " instructions: ";

  for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
    for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
      for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
        Instruction *Inst = I++;
        if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
            !isa<LandingPadInst>(Inst)) {
          if (!Inst->getType()->isVoidTy())
            Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
          Inst->eraseFromParent();
        }
      }

  // Verify that this is still valid.
  PassManager Passes;
  Passes.add(createVerifierPass());
  Passes.add(createDebugInfoVerifierPass());
  Passes.run(*M);

  // Try running on the hacked up program...
  if (TestFn(BD, M)) {
    BD.setNewProgram(M);      // It crashed, keep the trimmed version...

    // Make sure to use instruction pointers that point into the now-current
    // module, and that they don't include any deleted blocks.
    Insts.clear();
    for (SmallPtrSet<Instruction*, 64>::const_iterator I = Instructions.begin(),
             E = Instructions.end(); I != E; ++I)
      Insts.push_back(*I);
    return true;
  }
  delete M;  // It didn't crash, try something else.
  return false;
}
Example #20
0
	bool SimpleTargetMachine::
	    addPassesToEmitWholeFile(PassManager & PM,
				     formatted_raw_ostream & o,
				     CodeGenFileType FileType,
				     CodeGenOpt::Level OptLevel,
				     bool DisableVerify) {
		PM.add(createGCLoweringPass());
		PM.add(createLowerInvokePass());
		PM.add(createCFGSimplificationPass());	// clean up after lower invoke.
		PM.add(new SimpleBackendNameAllUsedStructsAndMergeFunctions());
		PM.add(new SimpleWriter(o));
		pinavm::addGCInfoDeleter(PM);
		return false;
}}
Example #21
0
int main(int argc, char * argv[]) {
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
  LLVMContext &Context = getGlobalContext();
  
  cl::ParseCommandLineOptions(argc, argv, "Anteater compiler\n");

  SMDiagnostic Err;

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

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

  // Figure out what stream we are supposed to write to...
  // FIXME: outs() is not binary!
  raw_ostream *Out = &outs();  // Default to printing to stdout...
  if (OutputFilename != "-") {
    std::string ErrorInfo;
    Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
                               raw_fd_ostream::F_Binary);
    if (!ErrorInfo.empty()) {
      errs() << ErrorInfo << '\n';
      delete Out;
      return 1;
    }
  }

  PassManager Passes;
  if (Backend == "yices") {
    Passes.add(anteater::createXorEliminationPass(&Context));
    Passes.add(anteater::createAnteaterInstructionNamerPass());
    Passes.add(anteater::createYicesWriter(Out));
    
  } else {
    Passes.add(anteater::createAnteaterInstructionNamerPass());
    Passes.add(anteater::createSMT12Writer(Out));    
  }
  Passes.run(*M.get());


  // Delete the raw_fd_ostream.
  if (Out != &outs())
    delete Out;
  
  return 0;
}
Example #22
0
Module * llvmutil_extractmodule(Module * OrigMod, TargetMachine * TM, std::vector<Function*> * livefns, std::vector<std::string> * symbolnames) {
        assert(symbolnames == NULL || livefns->size() == symbolnames->size());
        ValueToValueMapTy VMap;
        Module * M = CloneModule(OrigMod, VMap);
        PassManager * MPM = new PassManager();
        
        llvmutil_addtargetspecificpasses(MPM, TM);
        
        std::vector<const char *> names;
        for(size_t i = 0; i < livefns->size(); i++) {
            Function * fn = cast<Function>(VMap[(*livefns)[i]]);
            const char * name;
            if(symbolnames) {
                GlobalAlias * ga = new GlobalAlias(fn->getType(), Function::ExternalLinkage, (*symbolnames)[i], fn, M);
                name = copyName(ga->getName());
            } else {
                name = copyName(fn->getName());
            }
            names.push_back(name); //internalize pass has weird interface, so we need to copy the names here
        }
        
        //at this point we run optimizations on the module
        //first internalize all functions not mentioned in "names" using an internalize pass and then perform 
        //standard optimizations
        
        MPM->add(createVerifierPass()); //make sure we haven't messed stuff up yet
        MPM->add(createInternalizePass(names));
        MPM->add(createGlobalDCEPass()); //run this early since anything not in the table of exported functions is still in this module
                                         //this will remove dead functions
        
        //clean up the name list
        for(size_t i = 0; i < names.size(); i++) {
            free((char*)names[i]);
            names[i] = NULL;
        }
        
        PassManagerBuilder PMB;
        PMB.OptLevel = 3;
        PMB.DisableUnrollLoops = true;
        
        PMB.populateModulePassManager(*MPM);
        //PMB.populateLTOPassManager(*MPM, false, false); //no need to re-internalize, we already did it
    
        MPM->run(*M);
        
        delete MPM;
        MPM = NULL;
    
        return M;
}
Example #23
0
/// Optimize - Perform link time optimizations. This will run the scalar
/// optimizations, any loaded plugin-optimization modules, and then the
/// inter-procedural optimizations if applicable.
void Optimize(Module *M) {

    // Instantiate the pass manager to organize the passes.
    PassManager Passes;

    // If we're verifying, start off with a verification pass.
    if (VerifyEach)
        Passes.add(createVerifierPass());

    // Add an appropriate TargetData instance for this module...
    addPass(Passes, new TargetData(M));

    if (!DisableOptimizations)
        PassManagerBuilder().populateLTOPassManager(Passes, !DisableInternalize,
                !DisableInline);

    // If the -s or -S command line options were specified, strip the symbols out
    // of the resulting program to make it smaller.  -s and -S are GNU ld options
    // that we are supporting; they alias -strip-all and -strip-debug.
    if (Strip || StripDebug)
        addPass(Passes, createStripSymbolsPass(StripDebug && !Strip));

    // Create a new optimization pass for each one specified on the command line
    std::auto_ptr<TargetMachine> target;
    for (unsigned i = 0; i < OptimizationList.size(); ++i) {
        const PassInfo *Opt = OptimizationList[i];
        if (Opt->getNormalCtor())
            addPass(Passes, Opt->getNormalCtor()());
        else
            errs() << "llvm-ld: cannot create pass: "******"\n";
    }

    // The user's passes may leave cruft around. Clean up after them them but
    // only if we haven't got DisableOptimizations set
    if (!DisableOptimizations) {
        addPass(Passes, createInstructionCombiningPass());
        addPass(Passes, createCFGSimplificationPass());
        addPass(Passes, createAggressiveDCEPass());
        addPass(Passes, createGlobalDCEPass());
    }

    // Make sure everything is still good.
    if (!DontVerify)
        Passes.add(createVerifierPass());

    // Run our queue of passes all at once now, efficiently.
    Passes.run(*M);
}
Example #24
0
void CodeGenContext::generateCode(NBlock& root)
{
	std::cout << "Generating code...\n";

	vector<Type*> argTypes;
	FunctionType* ftype = FunctionType::get(Type::getVoidTy(getGlobalContext()), makeArrayRef(argTypes), false);
	mainFunction = Function::Create(ftype, GlobalValue::InternalLinkage, "main", module);
	BasicBlock* bblock = BasicBlock::Create(getGlobalContext(), "entry", mainFunction, 0);

	pushBlock(bblock);
	root.codeGen(*this);
	ReturnInst::Create(getGlobalContext(), bblock);
	popBlock();

	std::cout << "Code generation complete.\n";

	PassManager pm;
	pm.add(createPrintModulePass(outs()));
	pm.run(*module);

	//Pass* printer = createPrintModulePass(outs());
	//ModulePassManager pm;
	//pm.addPass(printer);
	//pm.run(module);
}
Example #25
0
void minipascal::CodeGenContext::generateCode(minipascal::Node* root)
{
	vector<llvm::Type*> argTypes;
	FunctionType *ftype = FunctionType::get(llvm::Type::getVoidTy(getGlobalContext()), makeArrayRef(argTypes), false);
	Function* mainfunc = Function::Create(ftype, GlobalValue::InternalLinkage, "main", mmodule);
	BasicBlock* mainblock = BasicBlock::Create(getGlobalContext(), "entry", mainfunc, 0);
		
	pushFunction(mainfunc);
	pushBlock(mainblock);
	// root->print();
	root->codeGen(*this);
	// printConstVal();
	// printTypeDefs();
	// printVarTypes();
	// printLocalVal();

	ReturnInst::Create(getGlobalContext(), currentBlock());
	popBlock();

	mmodule->dump();

	cout << "write to file out.ll start\n";
	string errorstr("Can not open the file");
	raw_fd_ostream outfile("out.ll", errorstr, 0);
  	verifyModule(*mmodule, PrintMessageAction);
  	PassManager passman;
  	passman.add(createPrintModulePass(&outfile));
  	passman.run(*mmodule);

	// WriteBitcodeToFile(mmodule, outfile);
	cout << "write to file out.ll end\n";
}
bool LTOCodeGenerator::writeMergedModules(const char *path,
                                          std::string &errMsg) {
  if (!determineTarget(errMsg))
    return false;

  // Run the verifier on the merged modules.
  PassManager passes;
  passes.add(createVerifierPass());
  passes.run(*_linker.getModule());

  // create output file
  std::string ErrInfo;
  tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
  if (!ErrInfo.empty()) {
    errMsg = "could not open bitcode file for writing: ";
    errMsg += path;
    return false;
  }

  // write bitcode to it
  WriteBitcodeToFile(_linker.getModule(), Out.os());
  Out.os().close();

  if (Out.os().has_error()) {
    errMsg = "could not write bitcode file: ";
    errMsg += path;
    Out.os().clear_error();
    return false;
  }

  Out.keep();
  return true;
}
Example #27
0
void outputLLVM(llvm::Module &module, raw_pwrite_stream &os) {
	PassManager pm;
	addOptPasses(pm);
	pm.add(createPrintModulePass(os));
	pm.run(module);
	os.flush();
}
int main(int argc, char **argv) {
  if (argc < 2) {
    errs() << "Usage: " << argv[0] << " <IR file>\n";
    return 1;
  }

  // Parse the input LLVM IR file into a module.
  SMDiagnostic Err;
  std::unique_ptr<Module> Mod(parseIRFile(argv[1], Err, getGlobalContext()));
  if (!Mod) {
    Err.print(argv[0], errs());
    return 1;
  }

  // Create a function declarations for _tidx, _tidy, _tidz
  FunctionType *TidFuncTy =
      FunctionType::get(Type::getInt32Ty(Mod->getContext()), false);
  Function *Tidx = Function::Create(TidFuncTy, GlobalValue::InternalLinkage,
                                    "_tidx", Mod.get());
  Function *Tidy = Function::Create(TidFuncTy, GlobalValue::InternalLinkage,
                                    "_tidy", Mod.get());
  Function *Tidz = Function::Create(TidFuncTy, GlobalValue::InternalLinkage,
                                    "_tidz", Mod.get());

  // Create a pass manager and fill it with the passes we want to run.
  PassManager PM;
  PM.add(new ReplaceThreadIdxRefs(Tidx, Tidy, Tidz));
  PM.run(*Mod);

  outs() << "Dumping the module after the pass has run:\n";
  Mod->dump();

  return 0;
}
Example #29
0
extern "C" void
LLVMRustRunRestrictionPass(LLVMModuleRef M, char **symbols, size_t len) {
    PassManager passes;
    ArrayRef<const char*> ref(symbols, len);
    passes.add(llvm::createInternalizePass(ref));
    passes.run(*unwrap(M));
}
Example #30
0
bool LLVMOptimizeModule(LLVMModuleRef Mod) {
    Module* M = unwrap(Mod);

  // 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()));

  // Add an appropriate DataLayout instance for this module.
  // const std::string &ModuleDataLayout = M->getDataLayout();
  // if (!ModuleDataLayout.empty()) {
  //   DataLayout *TD = NULL; // new DataLayout(ModuleDataLayout);
  //   Passes.add(TD);
  // }


  Passes.add(createVerifierPass());  // Verify that input is correct

  // -std-compile-opts adds the same module passes as -O3.
  PassManagerBuilder Builder;
  Builder.Inliner = createFunctionInliningPass();
  Builder.OptLevel = 3;
  Builder.populateModulePassManager(Passes);


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

  return change;
}