std::string getMangledName(FunctionDecl* FD) {
      // Copied from Interpreter.cpp;
      if (!m_MangleCtx)
        m_MangleCtx.reset(FD->getASTContext().createMangleContext());

      std::string mangledName;
      if (m_MangleCtx->shouldMangleDeclName(FD)) {
        llvm::raw_string_ostream RawStr(mangledName);
        switch(FD->getKind()) {
        case Decl::CXXConstructor:
          //Ctor_Complete,          // Complete object ctor
          //Ctor_Base,              // Base object ctor
          //Ctor_CompleteAllocating // Complete object allocating ctor (unused)
          m_MangleCtx->mangleCXXCtor(cast<CXXConstructorDecl>(FD),
                                     Ctor_Complete, RawStr);
          break;

        case Decl::CXXDestructor:
          //Dtor_Deleting, // Deleting dtor
          //Dtor_Complete, // Complete object dtor
          //Dtor_Base      // Base object dtor
          m_MangleCtx->mangleCXXDtor(cast<CXXDestructorDecl>(FD),
                                     Dtor_Complete, RawStr);
          break;

        default :
          m_MangleCtx->mangleName(FD, RawStr);
          break;
        }
        RawStr.flush();
      } else {
        mangledName = FD->getNameAsString();
      }
      return mangledName;
    }
    virtual void Initialize(ASTContext &Ctx) {
      Context = &Ctx;

      if (llvm::TimePassesIsEnabled)
        LLVMIRGeneration.startTimer();

      Gen->Initialize(Ctx);

      TheModule.reset(Gen->GetModule());

      if (llvm::TimePassesIsEnabled)
        LLVMIRGeneration.stopTimer();
    }
Esempio n. 3
0
llvm::Module *NodeCompiler::compile(const char *fileName)
{
    // Add filename as the last argument of the compiler
    char globfilename[512];
    strcpy(globfilename, SRC_DIR"/");
    strcat(globfilename, fileName);
    m_args.push_back(globfilename);
    const llvm::OwningPtr<Compilation>
        Compilation(
            //m_driver->BuildCompilation(llvm::makeArrayRef(m_args)));
            m_driver->BuildCompilation(m_args));

    // Compilation Job to get the correct arguments
    const JobList &Jobs = Compilation->getJobs();
    const Command *Cmd = llvm::cast<Command>(*Jobs.begin());
    const ArgStringList *const CC1Args = &Cmd->getArguments();

    //m_driver->PrintActions(*Compilation);

    llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
    CompilerInvocation::CreateFromArgs(
        *CI, CC1Args->data() + 1, CC1Args->data() + CC1Args->size(), *m_diagEngine);

    // Show the invocation, with -v.
    // TO debug the -fvectorize issue
    //if (CI->getHeaderSearchOpts().Verbose) {
    //    llvm::errs() << "clang invocation:\n";
    //    Compilation->PrintJob(llvm::errs(), Jobs, "\n", true);
    //    llvm::errs() << "\n";
    //}

    // Create the compiler instance
    m_clang->setInvocation(CI.take());

    // Diagnostics
    m_clang->createDiagnostics();
    //m_args.pop_back(); // Remove filename for future compilation
    if (!m_clang->hasDiagnostics())
        return NULL;

    // Emit only llvm code
    llvm::Module *mod=NULL;
    std::cout << "emitting llvm code" << "\n";
    if (!m_clang->ExecuteAction(*m_action)) {
        std::cout << "unable to generate llvm code" << "\n";
    } else {
        mod = m_action->takeModule();
    }
    std::cout << "code generated\n";
    return mod;
}
Esempio n. 4
0
    aravdebug(const char * userfile, int lineno, const char *PATH) {

        dataPath = getenv("DLOG_OUTPUT_FOLDER") + std::string(PATH);

        //llvm::errs()<<"Data path ::"<<dataPath;
        datatempPath = dataPath + ".temp";
//		tagPath = dataPath + ".tag";

        std::string syscall = "rm -f " + dataPath;

        int status = system(syscall.c_str());
        if (status < 0)
            std::cout << "DLOG Error: " << strerror(errno) << '\n';

        OS.reset((new llvm::raw_fd_ostream(datatempPath.c_str(), ErrorInfo)));

        llvm::errs() << ErrorInfo;

        id = gid++;

        //llvm::errs()<<"created DLOG with id "<<id<<"\n";
        tagset.insert("SYSTEM");
        (*OS) << DIV("SYSTEM")<< "Created Debugger " << GREEN(id)
              << CALLINFO
              << EDIV;

        tagset.insert("CALLINFO");

        (*OS).flush();
    }
Esempio n. 5
0
File: main.cpp Progetto: qyqx/moc-ng
    void HandleDiagnostic(clang::DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic& Info) override {

        /* Moc ignores most of the errors since it even can operate on non self-contained headers.
         * So try to change errors into warning.
         */

        auto DiagId = Info.getID();
        auto Cat = Info.getDiags()->getDiagnosticIDs()->getCategoryNumberForDiag(DiagId);

        bool ShouldReset = false;

        if (DiagLevel >= clang::DiagnosticsEngine::Error ) {
            if (Cat == 2 || Cat == 4
                || DiagId == clang::diag::err_param_redefinition
                || DiagId == clang::diag::err_pp_expr_bad_token_binop ) {
                if (!HadRealError)
                    ShouldReset = true;
                DiagLevel = clang::DiagnosticsEngine::Warning;
            } else {
                HadRealError++;
            }
        }

        DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
        Proxy->HandleDiagnostic(DiagLevel, Info);

        if (ShouldReset) {
            // FIXME:  is there another way to ignore errors?
            const_cast<clang::DiagnosticsEngine *>(Info.getDiags())->Reset();
        }
    }
Esempio n. 6
0
static clang::CompilerInvocation *newCompilerInvocation(std::string &mainExecutable,
        std::vector<std::string> &unadjustedCmdLine, bool runClangChecker = false)
{
    // Prepare for command lines, and convert to old-school argv
    llvm::OwningPtr<clang::tooling::ArgumentsAdjuster> argumentsAdjusterPtr(
        new clang::tooling::ClangSyntaxOnlyAdjuster());
    std::vector<std::string> commandLine = argumentsAdjusterPtr->Adjust(unadjustedCmdLine);
    assert(!commandLine.empty());
    commandLine[0] = mainExecutable;

    std::vector<const char*> argv;
    int start = 0, end = commandLine.size();
    if (runClangChecker)
    {
        argv.push_back(commandLine[0].c_str());
        argv.push_back("--analyze");
        start = 1;
        end -= 1;
    }
    for (int cmdIndex = start; cmdIndex != end; cmdIndex++)
    {
        argv.push_back(commandLine[cmdIndex].c_str());
    }

    // create diagnostic engine
    llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagOpts =
        new clang::DiagnosticOptions();
    clang::DiagnosticsEngine diagnosticsEngine(
        llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(new clang::DiagnosticIDs()),
        &*diagOpts,
        new clang::DiagnosticConsumer(),
        false);

    // create driver
    const char *const mainBinaryPath = argv[0];
    const llvm::OwningPtr<clang::driver::Driver> driver(
        newDriver(&diagnosticsEngine, mainBinaryPath));
    driver->setCheckInputsExist(false);

    // create compilation invocation
    const llvm::OwningPtr<clang::driver::Compilation> compilation(
        driver->BuildCompilation(llvm::makeArrayRef(argv)));
    const llvm::opt::ArgStringList *const cc1Args = getCC1Arguments(compilation.get());
    return newInvocation(&diagnosticsEngine, *cc1Args);
}
Esempio n. 7
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];
  DiagnosticOptions DefaultDiagnosticOptions;
  TextDiagnosticPrinter DiagnosticPrinter(
      llvm::errs(), DefaultDiagnosticOptions);
  DiagnosticsEngine Diagnostics(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(
      new DiagnosticIDs()), &DiagnosticPrinter, false);

  const llvm::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 llvm::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;
  }
  llvm::OwningPtr<clang::CompilerInvocation> Invocation(
      newInvocation(&Diagnostics, *CC1Args));
  return runInvocation(BinaryName, Compilation.get(),
                       Invocation.take(), *CC1Args, ToolAction.take());
}
    virtual void HandleTopLevelDecl(DeclGroupRef D) {
      PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
                                     Context->getSourceManager(),
                                     "LLVM IR generation of declaration");

      if (llvm::TimePassesIsEnabled)
        LLVMIRGeneration.startTimer();

      Gen->HandleTopLevelDecl(D);

      if (llvm::TimePassesIsEnabled)
        LLVMIRGeneration.stopTimer();
    }
Esempio n. 9
0
static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
                              unsigned argc, char **argv,
                              llvm::OwningPtr<DiagnosticClient> &DiagClient) {
  std::string ErrorInfo;
  llvm::raw_ostream *OS =
    new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo);
  if (!ErrorInfo.empty()) {
    // FIXME: Do not fail like this.
    llvm::errs() << "error opening -dump-build-information file '"
                 << DiagOpts.DumpBuildInformation << "', option ignored!\n";
    delete OS;
    return;
  }

  (*OS) << "clang -cc1 command line arguments: ";
  for (unsigned i = 0; i != argc; ++i)
    (*OS) << argv[i] << ' ';
  (*OS) << '\n';

  // Chain in a diagnostic client which will log the diagnostics.
  DiagnosticClient *Logger =
    new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
  DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
}
llvm::error_code FileOutputBuffer::create(FileHandle& pFileHandle,
    size_t pSize, llvm::OwningPtr<FileOutputBuffer>& pResult)
{
  llvm::error_code EC;
  llvm::OwningPtr<mapped_file_region> mapped_file(new mapped_file_region(
      pFileHandle.handler(),
      false,
      mapped_file_region::readwrite,
      pSize,
      0,
      EC));

  if (EC)
    return EC;

  pResult.reset(new FileOutputBuffer(mapped_file.get(), pFileHandle));
  if (pResult)
    mapped_file.take();
  return llvm::error_code::success();
}
    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.
      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");

      // 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);
    }
 virtual void CompleteTentativeDefinition(VarDecl *D) {
   Gen->CompleteTentativeDefinition(D);
 }
Esempio n. 13
0
File: main.cpp Progetto: qyqx/moc-ng
 void finish() override {
     Proxy->finish();
 }
Esempio n. 14
0
File: main.cpp Progetto: qyqx/moc-ng
 void EndSourceFile() override {
     Proxy->EndSourceFile();
 }
Esempio n. 15
0
File: main.cpp Progetto: qyqx/moc-ng
 void clear() override {
     Proxy->clear();
 }
Esempio n. 16
0
File: main.cpp Progetto: qyqx/moc-ng
 void BeginSourceFile(const clang::LangOptions& LangOpts, const clang::Preprocessor* PP = 0) override {
     Proxy->BeginSourceFile(LangOpts, PP);
 }
 virtual void HandleTagDeclDefinition(TagDecl *D) {
   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
                                  Context->getSourceManager(),
                                  "LLVM IR generation of declaration");
   Gen->HandleTagDeclDefinition(D);
 }
 virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
   Gen->HandleVTable(RD, DefinitionRequired);
 }
 llvm::Module *takeModule() { return TheModule.take(); }
Esempio n. 20
0
    ~aravdebug() {

        //llvm::errs()<<"Datapath "<<dataPath.c_str()<<"\n";
        //llvm::errs()<<"datatempPath "<<datatempPath.c_str()<<"\n";

        int status;
        std::fstream fwrite;
        fwrite.open(dataPath.c_str(), std::fstream::out);

        fwrite
                << "<head>\n"
                "<script type='text/javascript' src='js/aravind.js' ></script>\n"
                "<script type='text/javascript' src='js/jquery-2.0.3.min.js'></script>\n";

        fwrite
                << "<script type=\"text/javascript\">"
                "$(document).ready(function() {"
                "$(\"ar_menu\").click(function(){"
                "$(this).toggleClass(\"active\");"
                "$(this).next(\"div\").stop('true','true').slideToggle(\"500\");"
                "});"
                "});"
                "</script>\n";
        fwrite << "\n</head>\n ";
        fwrite
                << "<body>\n"
                "<style>div.floating-menu {background:#fff4c8;border:1px solid #ffcc00;width:150px;margin-top:5px;margin-bottom:10px; } "
                "div.floating-menu a, div.floating-menu h3 {display:block;margin:0 0.5em;} </style>";

        fwrite
                << "<style>"
                "div.floating-container{top:35%;left:75%;position:fixed;z-index:100;}\n"
                "div.floating-container ar_menu:hover{background:#FFFFE0}\n"
                "div.floating-container ar_menu{list-style-type:none; cursor:pointer; border-top:2px solid #666666; border-bottom:2px solid #666666;padding:2px 2px 2px 2px;margin-top:10px;}\n"
                "div.floating-container ar_menu div:hover{text-decoration:none !important;}\n"
                "div.floating-container ar_menu:before {content: \" + \"; \n"
                "padding:0px 5px 1px 5px; color:red; font-weight:bold;background:#4A5A6D}\n"
                "div.floating-container ar_menu.active:before {content: \" - \";\n"
                " padding:0px 5px 1px 5px; color:red; font-weight:bold;background:#4A5A6D}\n"
                ".floating-topic{background:#B7B8B5;display: inline-block; width:125px;margin-bottom:5px;}\n"
                "</style>\n";

        fwrite << DIV("floating-container");
        auto it = tagset.begin();

        //for callinfo
        fwrite
                << "<ar_menu><span class=\"floating-topic\"><b>&nbsp;&nbsp;Extra info</b></span></ar_menu>\n";

        fwrite << "<div class=\"floating-menu\">" << CHKBOX(*it) << EDIV;

        //for avoiding collapsing problem
        fwrite << DIV("") << EDIV;

        //tags begin here
        fwrite
                << "<ar_menu><span class=\"floating-topic\"><b>&nbsp;&nbsp;Tags</b></span></ar_menu>\n";

        fwrite << "<div class=\"floating-menu\">";
        ++it;
        for (; it != tagset.end(); ++it) {
            fwrite << CHKBOX(*it);

        }

        fwrite
                << "<input id=\"clickMe\" type=\"button\" value=\"ALL\" onclick=\"toggle_chk_true(this);\" />\n";

        fwrite
                << "<input id=\"clickMe\" type=\"button\" value=\"NONE\" onclick=\"toggle_chk_false(this);\" />"
                << mendl;
        fwrite << EDIV;

        fwrite << EDIV; //container

        (*OS) << DIV("SYSTEM")<< br << "Destroyed Debugger " << GREEN(id)
              << EDIV;
        fwrite << "</body> </html>";
        fwrite.close();

        if (!system(NULL))
            (*OS) << RED("System command failed in debugger\n");

        OS.reset(NULL);

        std::string syscommand = "cat " + datatempPath + " >> " + dataPath;

//llvm::errs()<<syscommand;

        status = system(syscommand.c_str());
        if (status < 0)
            std::cout << "DLOG Error: " << strerror(errno) << '\n';

        syscommand = "rm -f " + datatempPath;
        status = system(syscommand.c_str());
        if (status < 0)
            std::cout << "DLOG Error: " << strerror(errno) << '\n';

        unsigned found = datatempPath.find_last_of("/\\");

        syscommand = "cp -r $DLOG_PATH/js "
                     + datatempPath.substr(0, found);
        status = system(syscommand.c_str());
        if (status < 0)
            std::cout << "DLOG Error: " << strerror(errno) << '\n';



//system("echo `pwd`");

    }
Esempio n. 21
0
static inline void LazyInitialize(llvm::OwningPtr<BugType> &BT,
                                  const char *name) {
  if (BT)
    return;
  BT.reset(new BugType(name, "Unix API"));
}
Esempio n. 22
0
File: main.cpp Progetto: qyqx/moc-ng
 DiagnosticConsumer* clone(clang::DiagnosticsEngine& Diags) const override {
     return new MocDiagConsumer { Proxy->clone(Diags) };
 }
Esempio n. 23
0
bool CallAndMessageChecker::PreVisitProcessArg(CheckerContext &C,
                                               SVal V, SourceRange argRange,
                                               const Expr *argEx,
                                               const char *BT_desc,
                                               llvm::OwningPtr<BugType> &BT) {

  if (V.isUndef()) {
    if (ExplodedNode *N = C.generateSink()) {
      LazyInit_BT(BT_desc, BT);

      // Generate a report for this bug.
      BugReport *R = new BugReport(*BT, BT->getName(), N);
      R->addRange(argRange);
      if (argEx)
        R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, argEx));
      C.EmitReport(R);
    }
    return true;
  }

  if (const nonloc::LazyCompoundVal *LV =
        dyn_cast<nonloc::LazyCompoundVal>(&V)) {

    class FindUninitializedField {
    public:
      SmallVector<const FieldDecl *, 10> FieldChain;
    private:
      ASTContext &C;
      StoreManager &StoreMgr;
      MemRegionManager &MrMgr;
      Store store;
    public:
      FindUninitializedField(ASTContext &c, StoreManager &storeMgr,
                             MemRegionManager &mrMgr, Store s)
      : C(c), StoreMgr(storeMgr), MrMgr(mrMgr), store(s) {}

      bool Find(const TypedValueRegion *R) {
        QualType T = R->getValueType();
        if (const RecordType *RT = T->getAsStructureType()) {
          const RecordDecl *RD = RT->getDecl()->getDefinition();
          assert(RD && "Referred record has no definition");
          for (RecordDecl::field_iterator I =
               RD->field_begin(), E = RD->field_end(); I!=E; ++I) {
            const FieldRegion *FR = MrMgr.getFieldRegion(*I, R);
            FieldChain.push_back(*I);
            T = (*I)->getType();
            if (T->getAsStructureType()) {
              if (Find(FR))
                return true;
            }
            else {
              const SVal &V = StoreMgr.getBinding(store, loc::MemRegionVal(FR));
              if (V.isUndef())
                return true;
            }
            FieldChain.pop_back();
          }
        }

        return false;
      }
    };

    const LazyCompoundValData *D = LV->getCVData();
    FindUninitializedField F(C.getASTContext(),
                             C.getState()->getStateManager().getStoreManager(),
                             C.getSValBuilder().getRegionManager(),
                             D->getStore());

    if (F.Find(D->getRegion())) {
      if (ExplodedNode *N = C.generateSink()) {
        LazyInit_BT(BT_desc, BT);
        llvm::SmallString<512> Str;
        llvm::raw_svector_ostream os(Str);
        os << "Passed-by-value struct argument contains uninitialized data";

        if (F.FieldChain.size() == 1)
          os << " (e.g., field: '" << *F.FieldChain[0] << "')";
        else {
          os << " (e.g., via the field chain: '";
          bool first = true;
          for (SmallVectorImpl<const FieldDecl *>::iterator
               DI = F.FieldChain.begin(), DE = F.FieldChain.end(); DI!=DE;++DI){
            if (first)
              first = false;
            else
              os << '.';
            os << **DI;
          }
          os << "')";
        }

        // Generate a report for this bug.
        BugReport *R = new BugReport(*BT, os.str(), N);
        R->addRange(argRange);

        // FIXME: enhance track back for uninitialized value for arbitrary
        // memregions
        C.EmitReport(R);
      }
      return true;
    }
  }

  return false;
}
Esempio n. 24
0
void ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
	ExternalSource.reset(Source.take());
}