void NullDerefProtectionTransformer::handleNonNullArgCall(llvm::Module& M,
    const std::string& name, const std::bitset<32>& ArgIndexs) {

    // Get the function by the name.
    llvm::Function* func = M.getFunction(name);
    if (!func)
      return;

    // Find all the instructions that calls the function.
    std::vector<llvm::Instruction*> WorkList;
    for (llvm::Value::use_iterator I = func->use_begin(), E = func->use_end();
          I != E; ++I) {
      llvm::CallSite CS(*I);
      if (!CS || CS.getCalledValue() != func)
        continue;
      WorkList.push_back(CS.getInstruction());
    }

    // There is no call instructions that call the function and return.
    if (WorkList.empty())
      return;

    // Instrument all the call instructions that call the function.
    for (std::vector<llvm::Instruction*>::iterator I = WorkList.begin(),
           E = WorkList.end(); I != E; ++I) {
      Inst = *I;
      Builder->SetInsertPoint(Inst);
      instrumentCallInst(Inst, ArgIndexs);
    }
    return;
  }
Esempio n. 2
0
bool TimeProfiler::runOnModule(llvm::Module &M)
{
  Function *Main = M.getFunction("main");
  if (Main == 0) {
    errs() << "WARNING: cannot insert edge profiling into a module"
           << " with no main function!\n";
    return false;  // No main, no instrumentation!
  }

  std::vector<CallInst*> Traped;
  Function* wtime = NULL;
  for(auto F = M.begin(), E = M.end(); F!=E; ++F){
     if((*F).getName() == "mpi_wtime_")
        wtime = &*F;
     for(auto I = inst_begin(*F), IE = inst_end(*F); I!=IE; ++I){
        CallInst* CI = dyn_cast<CallInst>(&*I);
        if(CI == NULL) continue;
        Value* CV = const_cast<CallInst*>(CI)->getCalledValue();
        Function* func = dyn_cast<Function>(castoff(CV));
        if(func == NULL)
          errs()<<"No func!\n";
        StringRef str = func->getName();
        if(str.startswith("mpi_"))
        {
           if(str.startswith("mpi_init_")||str.startswith("mpi_comm_rank_")||str.startswith("mpi_comm_size_"))
              continue;
           Traped.push_back(CI);
        }
     }
  }

  IRBuilder<> Builder(M.getContext());

  Type* DoubleTy = Type::getDoubleTy(M.getContext());

  Type*ATy = ArrayType::get(DoubleTy, Traped.size());
  GlobalVariable* Counters = new GlobalVariable(M, ATy, false,
        GlobalVariable::InternalLinkage, Constant::getNullValue(ATy),
        "TimeCounters");

  unsigned I=0;
  for(auto P : Traped){
     ArrayRef<Value*> args;
     CallInst* callTime = CallInst::Create(wtime, args, "", P);

     IncrementTimeCounter(callTime, wtime, I++, Counters, Builder, P);
  }

  InsertPredProfilingInitCall(Main, "llvm_start_time_profiling", Counters);
  return true;
}
Esempio n. 3
0
bool
IRDynamicChecks::runOnModule(llvm::Module &M)
{
    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));

    llvm::Function* function = M.getFunction(StringRef(m_func_name.c_str()));

    if (!function)
    {
        if (log)
            log->Printf("Couldn't find %s() in the module", m_func_name.c_str());

        return false;
    }

    if (m_checker_functions.m_valid_pointer_check)
    {
        ValidPointerChecker vpc(M, m_checker_functions);

        if (!vpc.Inspect(*function))
            return false;

        if (!vpc.Instrument())
            return false;
    }

    if (m_checker_functions.m_objc_object_check)
    {
        ObjcObjectChecker ooc(M, m_checker_functions);

        if (!ooc.Inspect(*function))
            return false;

        if (!ooc.Instrument())
            return false;
    }

    if (log && log->GetVerbose())
    {
        std::string s;
        raw_string_ostream oss(s);

        M.print(oss, nullptr);

        oss.flush();

        log->Printf ("Module after dynamic checks: \n%s", s.c_str());
    }

    return true;
}
Esempio n. 4
0
bool DeclareAssumePass::runOnModule(llvm::Module &M){
  bool modified_M = false;
  CheckModule::check_assume(&M);
  llvm::Function *F_assume = M.getFunction("__VERIFIER_assume");
  if(!F_assume){
    llvm::FunctionType *assumeTy;
    {
      llvm::Type *voidTy = llvm::Type::getVoidTy(M.getContext());
      llvm::Type *i1Ty = llvm::Type::getInt1Ty(M.getContext());
      assumeTy = llvm::FunctionType::get(voidTy,{i1Ty},false);
    }
    llvm::AttributeSet assumeAttrs =
      llvm::AttributeSet::get(M.getContext(),llvm::AttributeSet::FunctionIndex,
                              std::vector<llvm::Attribute::AttrKind>({llvm::Attribute::NoUnwind}));
    F_assume = llvm::dyn_cast<llvm::Function>(M.getOrInsertFunction("__VERIFIER_assume",assumeTy,assumeAttrs));
    assert(F_assume);
    modified_M = true;
  }
  return modified_M;
}
bool UnsafeTypeCastingCheck::doInitialization(llvm::Module &mod) { 
  errs() << "initialization... \n"; 
  
  for (Module::global_iterator git = mod.global_begin() ;
       git != mod.global_end() ; 
       git++) {
    GlobalValue *gv = dyn_cast<GlobalValue>(git);
    string gv_name = gv->getName().str(); 
    if (gv_name.compare("blockDim") == 0 || 
	gv_name.compare("gridDim") == 0 || 
	gv_name.compare("blockIdx") == 0 || 
	gv_name.compare("threadIdx") == 0) {
      setPointedType(gv, UINT_UT); 
    }
  }

  // get utcc_assert function call (assertion) 
  code_modified = false; 
  assert_func = mod.getFunction("utcc_assert"); 
  assert(assert_func != NULL); 

  return false; 
}
Esempio n. 6
0
void Prepare::deleteAsmBodies(llvm::Module &M) {
  static const char *toDelete[] = {
    "atomic_inc", "atomic_dec", "atomic_add", "atomic_sub",
    "atomic_dec_and_test", "atomic_add_return",
    "atomic64_inc", "atomic64_dec", "atomic64_add", "atomic64_sub",
    "local_inc", "local_dec",
    "__fswab16", "__fswab32", "__fswab64",
    "__xchg", "__cmpxchg",
    "__set_bit", "__clear_bit", "set_bit", "clear_bit",
    "variable_test_bit",
    "__test_and_set_bit", "__test_and_clear_bit",
    "test_and_set_bit", "test_and_clear_bit",
    "__fls", "fls", "__ffs", "ffs", "ffz",
    "inb", "inw", "inl",
    "insb", "insw", "insl",
    "inb_p", "inw_p", "inl_p",
    "readb", "readw", "readl", "readq",
    "__readb", "__readw", "__readl", "__readq",

    "___arch__swab32", "___arch__swab64" // generates false positives in stats
  };
  static const char *_makeNop[] = {
    "pagefault_disable",
    "__raw_local_save_flags", "raw_local_irq_restore",
    "raw_local_irq_enable", "raw_local_irq_disable",
    "__raw_spin_is_contended",
    "local_bh_enable", "local_bh_disable",
    "schedule", "schedule_timeout", "schedule_timeout_interruptible",
    "schedule_timeout_uninterruptible",
    "preempt_schedule",
    "msleep", "msleep_interruptible", "__udelay", "__const_udelay",
    "printk_ratelimit", "warn_slowpath", "warn_on_slowpath", "dump_stack",
    "printk", "vprintk", "snd_verbose_printk",
    "rep_nop",
    "outb", "outw", "outl",
    "outsb", "outsw", "outsl",
    "outb_p", "outw_p", "outl_p",
    "writeb", "writew", "writel", "writeq",
    "__writeb", "__writew", "__writel", "__writeq",

    "mod_timer", "__mod_timer", "del_timer", "del_timer_sync",
    "complete", "wait_for_completion",
    "interruptible_sleep_on",
    "add_wait_queue", "remove_wait_queue", "prepare_to_wait", "finish_wait",
    "__tasklet_schedule",
    "queue_work", "schedule_work", "flush_scheduled_work",
    "schedule_delayed_work",
    "__wake_up", "wake_up_process", "wake_up_state", "kill_fasync"
  };
  unsigned int i;

  for (i = 0; i < ARRAY_SIZE(toDelete); i++) {
    Function *F = M.getFunction(toDelete[i]);
    if (F)
      F->deleteBody();
  }
  for (i = 0; i < ARRAY_SIZE(_makeNop); i++) {
    Function *F = M.getFunction(_makeNop[i]);
    if (F)
      makeNop(F);
  }
}
Esempio n. 7
0
bool swift::immediate::IRGenImportedModules(
    CompilerInstance &CI,
    llvm::Module &Module,
    llvm::SmallPtrSet<swift::Module *, 8> &ImportedModules,
    SmallVectorImpl<llvm::Function*> &InitFns,
    IRGenOptions &IRGenOpts,
    const SILOptions &SILOpts) {
  swift::Module *M = CI.getMainModule();

  // Perform autolinking.
  SmallVector<LinkLibrary, 4> AllLinkLibraries(IRGenOpts.LinkLibraries);
  auto addLinkLibrary = [&](LinkLibrary linkLib) {
    AllLinkLibraries.push_back(linkLib);
  };

  M->forAllVisibleModules({}, /*includePrivateTopLevel=*/true,
                          [&](Module::ImportedModule import) {
    import.second->collectLinkLibraries(addLinkLibrary);
  });

  // Hack to handle thunks eagerly synthesized by the Clang importer.
  swift::Module *prev = nullptr;
  for (auto external : CI.getASTContext().ExternalDefinitions) {
    swift::Module *next = external->getModuleContext();
    if (next == prev)
      continue;
    next->collectLinkLibraries(addLinkLibrary);
    prev = next;
  }

  tryLoadLibraries(AllLinkLibraries, CI.getASTContext().SearchPathOpts,
                   CI.getDiags());

  ImportedModules.insert(M);
  if (!CI.hasSourceImport())
    return false;

  // IRGen the modules this module depends on. This is only really necessary
  // for imported source, but that's a very convenient thing to do in -i mode.
  // FIXME: Crawling all loaded modules is a hack.
  // FIXME: And re-doing SILGen, SIL-linking, SIL diagnostics, and IRGen is
  // expensive, because it's not properly being limited to new things right now.
  bool hadError = false;
  for (auto &entry : CI.getASTContext().LoadedModules) {
    swift::Module *import = entry.second;
    if (!ImportedModules.insert(import).second)
      continue;

    std::unique_ptr<SILModule> SILMod = performSILGeneration(import,
                                                             CI.getSILOptions());
    performSILLinking(SILMod.get());
    if (runSILDiagnosticPasses(*SILMod)) {
      hadError = true;
      break;
    }

    // FIXME: We shouldn't need to use the global context here, but
    // something is persisting across calls to performIRGeneration.
    auto SubModule = performIRGeneration(IRGenOpts, import, SILMod.get(),
                                         import->getName().str(),
                                         llvm::getGlobalContext());

    if (CI.getASTContext().hadError()) {
      hadError = true;
      break;
    }

    if (!linkLLVMModules(&Module, std::move(SubModule)
                         // TODO: reactivate the linker mode if it is
                         // supported in llvm again. Otherwise remove the
                         // commented code completely.
                         /*, llvm::Linker::DestroySource */)) {
      hadError = true;
      break;
    }

    // FIXME: This is an ugly hack; need to figure out how this should
    // actually work.
    SmallVector<char, 20> NameBuf;
    StringRef InitFnName = (import->getName().str() + ".init").toStringRef(NameBuf);
    llvm::Function *InitFn = Module.getFunction(InitFnName);
    if (InitFn)
      InitFns.push_back(InitFn);
  }

  return hadError;
}
Esempio n. 8
0
void Simulator::Simulate()
{
  llvm::SMDiagnostic error;
  //std::unique_ptr<llvm::Module> M = llvm::ParseIRFile("Behavior.bc", error, context);
  //MyModule = M.get();
  MyModule = llvm::ParseIRFile("Behavior.bc", error, context);
  string err_str;
/*
    OwningPtr<MemoryBuffer> result;
    MemoryBuffer *mb;
    llvm::error_code ec = MemoryBuffer::getFile("Behavior.bc", result);
    mb = result.take();
    err_str = ec.message();
    if (!mb) {
      error() <<"Cannot open \"" <<bitcode_file() <<"\": " <<err_str <<endl;
      exit(1);
    }
    MyModule = llvm::ParseBitcodeFile(mb,context,&err_str);
    if (!MyModule) {
      error() <<"Failed to load module from bitcode file: " <<err_str <<endl;
      exit(1);
    }
    delete mb;
*/
/*
    for (llvm::Module::iterator f = MyModule->begin(), ef = MyModule->end(); f!=ef; ++f) 
    {
      f->addFnAttr(Attributes::AlwaysInline);
    }
*/
    for (int32_t i = 0; i < (int32_t)OPCODE::INVALID; i++) {
      OPCODE op = (OPCODE) i;
      llvm::Function *func = MyModule->getFunction(GetFuncName(op));
      func->addFnAttr(llvm::Attribute::AlwaysInline);
      OpFunctionMap[op] = func; 
    }
    test_type = MyModule->getFunction("test")->getFunctionType();


    std::string ErrStr;
    passManager = new llvm::PassManager();
    passManager->add(llvm::createAlwaysInlinerPass());
    fPassManager = new llvm::FunctionPassManager(MyModule);
    //fPassManager->add(new DataLayout(*EE->getDataLayout()));
    //fPassManager->add(new DataLayout(*EE->getDataLayout()));
    fPassManager->add(llvm::createGVNPass());
    fPassManager->add(llvm::createInstructionCombiningPass());
    fPassManager->add(llvm::createCFGSimplificationPass());
    fPassManager->add(llvm::createDeadStoreEliminationPass());

/*
    llvm::EngineBuilder builder(MyModule);
    builder.setErrorStr(&ErrStr);
    builder.setEngineKind(llvm::EngineKind::JIT);
    builder.setOptLevel(llvm::CodeGenOpt::Default); // None/Less/Default/Aggressive
    //llvm::TargetOptions options;
    //options.JITExceptionHandling = 1;
    //builder.setTargetOptions(options);
    EE = builder.create();
*/
  //StringRef MCPU = llvm::sys::getHostCPUName()
  EE = llvm::EngineBuilder(MyModule).create(); 
/*
    EE =
      llvm::EngineBuilder(std::move(M))
          .setErrorStr(&ErrStr)
          .setMCJITMemoryManager(llvm::make_unique<llvm::SectionMemoryManager>())
          .create();
*/
/*
    EE = llvm::EngineBuilder(M)
                .setErrorStr(&ErrStr)
                .setMCJITMemoryManager(llvm::SectionMemoryManager())
                .create();
    EE = llvm::EngineBuilder(std::move(M)).setErrorStr(&ErrStr).create();

*/
    if (!EE) {
      fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
      exit(1);
    }
    EE->DisableLazyCompilation(true);


/*
    //atexit(llvm_shutdown);  // Call llvm_shutdown() on exit.
    //llvm::EngineBuilder builder(MyModule);
    llvm::EngineBuilder builder(std::move(M));
    //llvm::EngineBuilder builder(MyModule);
    builder.setErrorStr(&err_str);
    builder.setEngineKind(llvm::EngineKind::JIT);
    builder.setOptLevel(llvm::CodeGenOpt::Default); // None/Less/Default/Aggressive
    //TargetOptions options;
    //options.JITExceptionHandling = 1;
    //builder.setTargetOptions(options);
    EE = builder.create();
    if (!EE) {
      std::cout <<"failed to create execution engine: " <<err_str <<"\n";
      exit(1);
    }
*/
/*
    //MyModule->dump();
    EE = llvm::EngineBuilder(std::move(M)).create();
*/
    //string ErrStr;
    //EE = llvm::EngineBuilder(std::move(M)).setErrorStr(&ErrStr).setMCPU("i386").create();


  //context = llvm::getGlobalContext();
  int32_t index = 0;
  Blocks = new HostBlock[1000];
  int32_t block_index = 0;
  while(index < total_inst) {

    Blocks[block_index].pc = index;  
    ostringstream f_name;
    f_name << "func";
    f_name << block_index;
    //string f_name = string("func");// + string(index);
/*
    llvm::Function *func =
      llvm::cast<llvm::Function>(MyModule->getOrInsertFunction(f_name.str(), 
            llvm::Type::getVoidTy(context), (llvm::Type *)0));
*/
  // Make the function type:  double(double,double) etc.
    //std::vector<Type*> Doubles(Args.size(),
    //                         Type::getDoubleTy(getGlobalContext()));
    llvm::FunctionType *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(context), false);
    llvm::Function *func = llvm::Function::Create(FT, 
                                                  llvm::Function::ExternalLinkage,
                                                  f_name.str(),
                                                  MyModule);

//Function *F = Function::Create(FT, Function::ExternalLinkage, FnName, M);
    // Add a basic block to the function. As before, it automatically inserts
    // because of the last argument.
    llvm::BasicBlock *BB = llvm::BasicBlock::Create(context, "EntryBlock", func);

    // Create a basic block builder with default parameters.  The builder will
    // automatically append instructions to the basic block `BB'.
    IRB.SetInsertPoint(BB);
    llvm::Function *sim_func; 
    CInst *inst; 
    int b_size = 0;
    do {
        inst = &instructions[index];
        llvm::Value *dst = IRB.getInt32(inst->dst_reg);
        llvm::Value *src0 = IRB.getInt32(inst->src0_reg);
        llvm::Value *src1 = IRB.getInt32(inst->src1_reg);
        sim_func = OpFunctionMap[inst->opcode];
        llvm::Value *oprnds[] = {dst, src0, src1};
        llvm::ArrayRef <llvm::Value *> ref(oprnds, 3);
        IRB.CreateCall(sim_func, ref);
        index++;
        b_size++;
        //cout << "Index " << index << endl;
    //} while(b_size < 10 || inst->opcode != OPCODE::JMP);
    } while(b_size < 10  && index < total_inst);
    IRB.CreateRetVoid();  
    passManager->run(*MyModule); 
    fPassManager->run(*func);
    EE->finalizeObject();
    //std::vector<llvm::GenericValue> noargs;
    //std::cout << "calling " << f_name.str() << endl;
    //EE->runFunction(func, noargs);
    //Blocks[block_index].func_ptr = reinterpret_cast<HostFunction>(EE->getPointerToFunction(func));
    Blocks[block_index].func_ptr = (void *)(EE->getPointerToFunction(func));
    //Blocks[block_index].func_ptr = reinterpret_cast<decltype(HostFunction())>(EE->getPointerToNamedFunction(f_name.str()));
    //(Blocks[block_index].func_ptr)(); 
    block_index++;
    //cout << "BlockIndex " << block_index << endl;
  }
  total_blocks = block_index;
  MyModule->dump();
/*
  cout << "calling add32" << endl;
  void (*add32)(int32_t, int32_t, int32_t) = 
    reinterpret_cast<void (*)(int32_t, int32_t, int32_t)>(EE->getFunctionAddress("add32")); 
  add32(0, 2, 3);
*/
/*
  void (*func0)() = 
    reinterpret_cast<void (*)()>(EE->getFunctionAddress("func1")); 
  func0();
*/
/*
  struct timeval tp;
  gettimeofday(&tp, NULL);
  long int start = tp.tv_sec * 1000 + tp.tv_usec / 1000;
  for (int32_t i = 0; i < 100; i++) {
    for (int32_t j = 0 ; j < total_blocks; j++) {
      ((HostFunction)(Blocks[j].func_ptr))();
    }
  }
  gettimeofday(&tp, NULL);
  long int end = tp.tv_sec * 1000 + tp.tv_usec / 1000;
  cout << "Time = " << end - start << endl; 
*/
}