// Collect file system header files.
// This function scans the file system for header files,
// starting at the directory of the module.map file,
// optionally filtering out all but the files covered by
// the include path options.
// Returns true if no errors.
bool ModuleMapChecker::collectFileSystemHeaders() {

  // Get directory containing the module.map file.
  // Might be relative to current directory, absolute, or empty.
  ModuleMapDirectory = getDirectoryFromPath(ModuleMapPath);

  // If no include paths specified, we do the whole tree starting
  // at the module.map directory.
  if (IncludePaths.size() == 0) {
    if (!collectFileSystemHeaders(StringRef("")))
      return false;
  } else {
    // Otherwise we only look at the sub-trees specified by the
    // include paths.
    for (std::vector<std::string>::const_iterator I = IncludePaths.begin(),
                                                  E = IncludePaths.end();
         I != E; ++I) {
      if (!collectFileSystemHeaders(*I))
        return false;
    }
  }

  // Sort it, because different file systems might order the file differently.
  std::sort(FileSystemHeaders.begin(), FileSystemHeaders.end());

  return true;
}
示例#2
0
int main(int argc, char **argv) {
  llvm::cl::ParseCommandLineOptions(argc, argv, "clang-wpa");
  FileManager FileMgr;
  std::vector<ASTUnit*> ASTUnits;

  if (InputFilenames.empty())
    return 0;

  DiagnosticOptions DiagOpts;
  llvm::IntrusiveRefCntPtr<Diagnostic> Diags
    = CompilerInstance::createDiagnostics(DiagOpts, argc, argv);
  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
    const std::string &InFile = InputFilenames[i];
    llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, Diags));
    if (!AST)
      return 1;

    ASTUnits.push_back(AST.take());
  }

  llvm::OwningPtr<CallGraph> CG;
  CG.reset(new CallGraph());

  for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i)
    CG->addTU(ASTUnits[i]->getASTContext());

  CG->ViewCallGraph();
}
示例#3
0
int main(int argc, char* argv[])
{
  llvm::cl::ParseCommandLineOptions(argc, argv, " globalcollect\n"
      "  This collects and prints global variables found in C programs.");

  if (!IgnoredParams.empty()) {
    cerr << "Ignoring the following parameters:";
    copy(IgnoredParams.begin(), IgnoredParams.end(),
        ostream_iterator<string>(cerr, " "));
  }

  // Create Preprocessor object
  PPContext context;

  // Add header search directories (C only, no C++ or ObjC)
  InitHeaderSearch init(context.headers);
  // user headers
  for (int i = 0; i < I_dirs.size(); ++i) {
    cerr << "adding " << I_dirs[i] << endl;
    init.AddPath(I_dirs[i], InitHeaderSearch::Angled, false, true, false);
  }
  init.AddDefaultSystemIncludePaths(context.opts);
  init.Realize();

  // Add defines passed in through parameters
  vector<char> predefineBuffer;
  for (int i = 0; i < D_macros.size(); ++i) {
    cerr << "defining " << D_macros[i] << endl;
    ::DefineBuiltinMacro(predefineBuffer, D_macros[i].c_str());
  }
  predefineBuffer.push_back('\0');
  context.pp.setPredefines(&predefineBuffer[0]);


  // Add input file
  const FileEntry* File = context.fm.getFile(InputFilename);
  if (!File) {
    cerr << "Failed to open \'" << InputFilename << "\'" << endl;
    return EXIT_FAILURE;
  }
  context.sm.createMainFileID(File, SourceLocation());


  // Parse it
  cout << "<h2><code>" << InputFilename << "</code></h2>" << endl << endl;
  cout << "<pre><code>";

  MyASTConsumer c;
  ParseAST(context.pp, &c);

  cout << "</code></pre>" << endl << endl;

  cout << endl;

  unsigned NumDiagnostics = context.diags.getNumDiagnostics();
  
  if (NumDiagnostics)
    fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
            (NumDiagnostics == 1 ? "" : "s"));
}
示例#4
0
文件: ygas.cpp 项目: 8l/yasm-nextgen
// main function
int
main(int argc, char* argv[])
{
    llvm::llvm_shutdown_obj llvm_manager(false);

    cl::SetVersionPrinter(&PrintVersion);
    cl::ParseCommandLineOptions(argc, argv, "", true);

    // Handle special exiting options
    if (show_license)
    {
        for (std::size_t i=0; i<sizeof(license_msg)/sizeof(license_msg[0]); i++)
            llvm::outs() << license_msg[i] << '\n';
        return EXIT_SUCCESS;
    }

    DiagnosticOptions diag_opts;
    diag_opts.ShowOptionNames = 1;
    diag_opts.ShowSourceRanges = 1;
    TextDiagnosticPrinter diag_printer(llvm::errs(), diag_opts);
    IntrusiveRefCntPtr<DiagnosticIDs> diagids(new DiagnosticIDs);
    DiagnosticsEngine diags(diagids, &diag_printer, false);
    FileSystemOptions opts;
    FileManager file_mgr(opts);
    SourceManager source_mgr(diags, file_mgr);
    diags.setSourceManager(&source_mgr);
    diag_printer.setPrefix("ygas");

    for (std::vector<std::string>::const_iterator i=unknown_options.begin(),
         end=unknown_options.end(); i != end; ++i)
    {
        diags.Report(diag::warn_unknown_command_line_option) << *i;
    }

    // Load standard modules
    if (!LoadStandardPlugins())
    {
        diags.Report(diag::fatal_standard_modules);
        return EXIT_FAILURE;
    }

#ifndef BUILD_STATIC
    // Load plugins
    for (std::vector<std::string>::const_iterator i=plugin_names.begin(),
         end=plugin_names.end(); i != end; ++i)
    {
        if (!LoadPlugin(*i))
            diags.Report(diag::warn_plugin_load) << *i;
    }
#endif

    // Default to stdin if no filename specified.
    if (in_filename.empty())
        in_filename = "-";

    return do_assemble(source_mgr, diags);
}
示例#5
0
int main(int argc, const char **argv) {
  void *MainAddr = (void*) (intptr_t) GetExecutablePath;
  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);

  std::string
    resourcesPath = CompilerInvocation::GetResourcesPath(argv[0], MainAddr);

  int optargc = 0;
  for (; optargc != argc; ++optargc) {
    if (StringRef(argv[optargc]) == "--args")
      break;
  }
  llvm::cl::ParseCommandLineOptions(optargc, argv, "arcmt-test");

  if (VerifyTransformedFiles) {
    if (ResultFiles.empty()) {
      llvm::cl::PrintHelpMessage();
      return 1;
    }
    return verifyTransformedFiles(ResultFiles);
  }

  if (optargc == argc) {
    llvm::cl::PrintHelpMessage();
    return 1;
  }

  ArrayRef<const char*> Args(argv+optargc+1, argc-optargc-1);

  if (CheckOnly)
    return checkForMigration(resourcesPath, Args);

  return performTransformations(resourcesPath, Args);
}
CompilationDatabase *autoDetectCompilations(std::string &ErrorMessage) {
  // Auto-detect a compilation database from BuildPath.
  if (BuildPath.getNumOccurrences() > 0)
    return CompilationDatabase::autoDetectFromDirectory(BuildPath,
                                                        ErrorMessage);
  // Try to auto-detect a compilation database from the first source.
  if (!SourcePaths.empty()) {
    if (CompilationDatabase *Compilations =
            CompilationDatabase::autoDetectFromSource(SourcePaths[0],
                                                      ErrorMessage)) {
      // FIXME: just pass SourcePaths[0] once getCompileCommands supports
      // non-absolute paths.
      SmallString<64> Path(SourcePaths[0]);
      llvm::sys::fs::make_absolute(Path);
      std::vector<CompileCommand> Commands =
          Compilations->getCompileCommands(Path);
      // Ignore a detected compilation database that doesn't contain source0
      // since it is probably an unrelated compilation database.
      if (!Commands.empty())
        return Compilations;
    }
    // Reset ErrorMessage since a fix compilation database will be created if
    // it fails to detect one from source.
    ErrorMessage = "";
    // If no compilation database can be detected from source then we create a
    // fixed compilation database with c++11 support.
    std::string CommandLine[] = { "-std=c++11" };
    return new FixedCompilationDatabase(".", CommandLine);
  }

  ErrorMessage = "Could not determine sources to transform";
  return 0;
}
示例#7
0
文件: Options.cpp 项目: oclint/oclint
static void processConfigFile(const std::string &path)
{
    oclint::option::ConfigFile config(path);
    for (const oclint::option::RuleConfigurationPair &ruleConfig : config.ruleConfigurations())
    {
        consumeRuleConfiguration(ruleConfig.key(), ruleConfig.value());
    }
    for (const llvm::StringRef &rulePath : config.rulePaths())
    {
        argRulesPath.push_back(rulePath.str());
    }
    std::vector<std::string> enableRules;
    for (auto rule : config.rules())
    {
        enableRules.push_back(rule.str());
    }
    filter.enableRules(enableRules.begin(), enableRules.end());
    std::vector<std::string> disableRules;
    for (auto rule : config.disableRules())
    {
        disableRules.push_back(rule.str());
    }
    filter.disableRules(disableRules.begin(), disableRules.end());

    updateArgIfSet(argOutput, config.output());
    updateArgIfSet(argReportType, config.reportType());
    updateArgIfSet(argMaxP1, config.maxP1());
    updateArgIfSet(argMaxP2, config.maxP2());
    updateArgIfSet(argMaxP3, config.maxP3());
    updateArgIfSet(argGlobalAnalysis, config.enableGlobalAnalysis());
    updateArgIfSet(argClangChecker, config.clangChecker());
    updateArgIfSet(argDuplications, config.allowDuplicatedViolations());
}
示例#8
0
int main(int argc, char **argv) {
#if defined(__CYGWIN__)
  // Cygwin clang 3.5.2 with '-O3' generates CRASHING BINARY,
  // if main()'s first function call is passing argv[0].
  std::rand();
#endif
  llvm::cl::ParseCommandLineOptions(argc, argv);

  swift::Demangle::DemangleOptions options;
  options.SynthesizeSugarOnTypes = !DisableSugar;
  if (Simplified)
    options = swift::Demangle::DemangleOptions::SimplifiedUIDemangleOptions();

  if (InputNames.empty()) {
    CompactMode = true;
    return demangleSTDIN(options);
  } else {
    swift::Demangle::Context DCtx;
    for (llvm::StringRef name : InputNames) {
      demangle(llvm::outs(), name, DCtx, options);
      llvm::outs() << '\n';
    }

    return EXIT_SUCCESS;
  }
}
示例#9
0
文件: Options.cpp 项目: oclint/oclint
std::vector<std::string> oclint::option::rulesPath()
{
    if (argRulesPath.size() > 0)
    {
        return argRulesPath;
    }
    std::string defaultRulePath = libPath() + "/oclint/rules";
    std::vector<std::string> defaultRulesPath { defaultRulePath };
    return defaultRulesPath;
}
示例#10
0
文件: Options.cpp 项目: oclint/oclint
void oclint::option::process(const char *argv)
{
    preserveWorkingPath();
    preserveExecutablePath(argv);

    processConfigFiles();
    for (unsigned i = 0; i < argRuleConfiguration.size(); ++i)
    {
        std::string configuration = argRuleConfiguration[i];
        int indexOfSeparator = configuration.find_last_of("=");
        std::string key = configuration.substr(0, indexOfSeparator);
        std::string value = configuration.substr(indexOfSeparator + 1,
            configuration.size() - indexOfSeparator - 1);
        consumeRuleConfiguration(key, value);
    }

    filter.enableRules(argEnabledRules.begin(), argEnabledRules.end());
    filter.disableRules(argDisabledRules.begin(), argDisabledRules.end());
}
示例#11
0
文件: ygas.cpp 项目: 8l/yasm-nextgen
static std::string
GetBitsSetting()
{
    std::string bits = YGAS_OBJFMT_BITS;

    // Walk through bits_32 and bits_64 in parallel, ordering by command line
    // argument position.
    unsigned int bits32_pos = 0, bits32_num = 0;
    unsigned int bits64_pos = 0, bits64_num = 0;
    for (;;)
    {
        if (bits32_num < bits_32.size())
            bits32_pos = bits_32.getPosition(bits32_num);
        else
            bits32_pos = 0;
        if (bits64_num < bits_64.size())
            bits64_pos = bits_64.getPosition(bits64_num);
        else
            bits64_pos = 0;

        if (bits32_pos != 0 && (bits64_pos == 0 || bits32_pos < bits64_pos))
        {
            // Handle bits32 option
            ++bits32_num;
            bits = "32";
        }
        else if (bits64_pos != 0 &&
                 (bits32_pos == 0 || bits64_pos < bits32_pos))
        {
            // Handle bits64 option
            ++bits64_num;
            bits = "64";
        }
        else
            break; // we're done with the list
    }
    return bits;
}
示例#12
0
文件: ygas.cpp 项目: 8l/yasm-nextgen
static void
ConfigureObject(Object& object)
{
    Object::Config& config = object.getConfig();

    // Walk through execstack and noexecstack in parallel, ordering by command
    // line argument position.
    unsigned int exec_pos = 0, exec_num = 0;
    unsigned int noexec_pos = 0, noexec_num = 0;
    for (;;)
    {
        if (exec_num < execstack.size())
            exec_pos = execstack.getPosition(exec_num);
        else
            exec_pos = 0;
        if (noexec_num < noexecstack.size())
            noexec_pos = noexecstack.getPosition(noexec_num);
        else
            noexec_pos = 0;

        if (exec_pos != 0 && (noexec_pos == 0 || exec_pos < noexec_pos))
        {
            // Handle exec option
            ++exec_num;
            config.ExecStack = true;
            config.NoExecStack = false;
        }
        else if (noexec_pos != 0 && (exec_pos == 0 || noexec_pos < exec_pos))
        {
            // Handle noexec option
            ++noexec_num;
            config.ExecStack = false;
            config.NoExecStack = true;
        }
        else
            break; // we're done with the list
    }
}
示例#13
0
int main(int argc, char** argv) {
  llvm::cl::ParseCommandLineOptions(argc, argv);
  graph.structureFromFile(inputfilename);
  
  for (unsigned i = 0; i != statModeList.size(); ++i) {
    switch (statModeList[i]) {
      case summary: do_summary(); break;
      case degrees: do_degrees(); break;
      default: abort(); break;
    }
  }

  return 0;
}
示例#14
0
static void getFunctionNames(std::vector<std::string> &Names) {
  std::copy(CommandLineFunctionNames.begin(), CommandLineFunctionNames.end(),
            std::back_inserter(Names));

  if (!FunctionNameFile.empty()) {
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
        llvm::MemoryBuffer::getFileOrSTDIN(FunctionNameFile);
    if (!FileBufOrErr) {
      fprintf(stderr, "Error! Failed to open file: %s\n",
              InputFilename.c_str());
      exit(-1);
    }
    StringRef Buffer = FileBufOrErr.get()->getBuffer();
    while (!Buffer.empty()) {
      StringRef Token, NewBuffer;
      std::tie(Token, NewBuffer) = llvm::getToken(Buffer, "\n");
      if (Token.empty()) {
        break;
      }
      Names.push_back(Token);
      Buffer = NewBuffer;
    }
  }
}
示例#15
0
int main(int argc, char **argv) {
#if defined(__CYGWIN__)
  // Cygwin clang 3.5.2 with '-O3' generates CRASHING BINARY,
  // if main()'s first function call is passing argv[0].
  std::rand();
#endif  
  llvm::cl::ParseCommandLineOptions(argc, argv);

  swift::Demangle::DemangleOptions options;
  options.SynthesizeSugarOnTypes = !DisableSugar;
  if (Simplified)
    options = swift::Demangle::DemangleOptions::SimplifiedUIDemangleOptions();

  if (InputNames.empty()) {
    CompactMode = true;
    auto input = llvm::MemoryBuffer::getSTDIN();
    if (!input) {
      llvm::errs() << input.getError().message() << '\n';
      return EXIT_FAILURE;
    }
    llvm::StringRef inputContents = input.get()->getBuffer();

    // This doesn't handle Unicode symbols, but maybe that's okay.
    llvm::Regex maybeSymbol("_T[_a-zA-Z0-9$]+");
    llvm::SmallVector<llvm::StringRef, 1> matches;
    while (maybeSymbol.match(inputContents, &matches)) {
      llvm::outs() << substrBefore(inputContents, matches.front());
      demangle(llvm::outs(), matches.front(), options);
      inputContents = substrAfter(inputContents, matches.front());
    }
    llvm::outs() << inputContents;

  } else {
    for (llvm::StringRef name : InputNames) {
      demangle(llvm::outs(), name, options);
      llvm::outs() << '\n';
    }
  }

  return EXIT_SUCCESS;
}
示例#16
0
static void processConfigFile(const std::string &path)
{
    oclint::option::ConfigFile config(path);
    for (const oclint::option::RuleConfigurationPair &ruleConfig : config.ruleConfigurations())
    {
        oclint::RuleConfiguration::addConfiguration(ruleConfig.key(), ruleConfig.value());
    }
    for (const llvm::StringRef &rulePath : config.rulePaths())
    {
        argRulesPath.push_back(rulePath.str());
    }
    filter.enableRules(config.rules().begin(), config.rules().end());
    filter.disableRules(config.disableRules().begin(), config.disableRules().end());

    updateArgIfSet(argOutput, config.output());
    updateArgIfSet(argReportType, config.reportType());
    updateArgIfSet(argMaxP1, config.maxP1());
    updateArgIfSet(argMaxP2, config.maxP2());
    updateArgIfSet(argMaxP3, config.maxP3());
    updateArgIfSet(argClangChecker, config.clangChecker());
    updateArgIfSet(argDuplications, config.allowDuplicatedViolations());
}
示例#17
0
int main(int argc, char** argv) {
  llvm::llvm_shutdown_obj _ShutdownObj;
  llvm::cl::ParseCommandLineOptions(argc, argv, "P-NDK Link Tool");

  llvm::LLVMContext& Ctx = llvm::getGlobalContext();
  std::string ErrMsg;
  llvm::raw_fd_ostream FOS(OutputFilenames[0].c_str(), ErrMsg);
  assert(!FOS.has_error());

  // No need to link (just one file).
  // Output Directly.
  if (InputFilenames.size() == 1) {
    llvm::OwningPtr<llvm::Module> M(getModuleFromFilename(InputFilenames[0],
                                                           Ctx,
                                                           ErrMsg));
    llvm::WriteBitcodeToFile(M.get(), FOS);
    return 0;
  }

  llvm::OwningPtr<llvm::Module> M(linkFilesToModule(InputFilenames, Ctx));
  llvm::WriteBitcodeToFile(M.get(), FOS);
  assert(!FOS.has_error());
  return 0;
}
示例#18
0
static bool doPrintBefore(SILTransform *T, SILFunction *F) {
  if (!SILPrintOnlyFun.empty() && F && F->getName() != SILPrintOnlyFun)
    return false;

  if (!SILPrintOnlyFuns.empty() && F &&
      F->getName().find(SILPrintOnlyFuns, 0) == StringRef::npos)
    return false;

  auto MatchFun = [&](const std::string &Str) -> bool {
    return T->getName().find(Str) != StringRef::npos;
  };

  if (SILPrintBefore.end() !=
      std::find_if(SILPrintBefore.begin(), SILPrintBefore.end(), MatchFun))
    return true;

  if (SILPrintAround.end() !=
      std::find_if(SILPrintAround.begin(), SILPrintAround.end(), MatchFun))
    return true;

  return false;
}
示例#19
0
int main(int argc, char **argv) {
  INITIALIZE_LLVM(argc, argv);

  llvm::cl::ParseCommandLineOptions(argc, argv, "Swift SIL Extractor\n");

  CompilerInvocation Invocation;

  Invocation.setMainExecutablePath(llvm::sys::fs::getMainExecutable(
      argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable)));

  // Give the context the list of search paths to use for modules.
  Invocation.setImportSearchPaths(ImportPaths);
  // Set the SDK path and target if given.
  if (SDKPath.getNumOccurrences() == 0) {
    const char *SDKROOT = getenv("SDKROOT");
    if (SDKROOT)
      SDKPath = SDKROOT;
  }
  if (!SDKPath.empty())
    Invocation.setSDKPath(SDKPath);
  if (!Triple.empty())
    Invocation.setTargetTriple(Triple);
  if (!ResourceDir.empty())
    Invocation.setRuntimeResourcePath(ResourceDir);
  Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;
  Invocation.setParseStdlib();
  Invocation.getLangOptions().DisableAvailabilityChecking = true;
  Invocation.getLangOptions().EnableAccessControl = false;
  Invocation.getLangOptions().EnableObjCAttrRequiresFoundation = false;

  // Load the input file.
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
      llvm::MemoryBuffer::getFileOrSTDIN(InputFilename);
  if (!FileBufOrErr) {
    fprintf(stderr, "Error! Failed to open file: %s\n", InputFilename.c_str());
    exit(-1);
  }

  // If it looks like we have an AST, set the source file kind to SIL and the
  // name of the module to the file's name.
  Invocation.addInputBuffer(FileBufOrErr.get().get());

  serialization::ExtendedValidationInfo extendedInfo;
  auto result = serialization::validateSerializedAST(
      FileBufOrErr.get()->getBuffer(), &extendedInfo);
  bool HasSerializedAST = result.status == serialization::Status::Valid;

  if (HasSerializedAST) {
    const StringRef Stem = ModuleName.size()
                               ? StringRef(ModuleName)
                               : llvm::sys::path::stem(InputFilename);
    Invocation.setModuleName(Stem);
    Invocation.setInputKind(InputFileKind::IFK_Swift_Library);
  } else {
    Invocation.setModuleName("main");
    Invocation.setInputKind(InputFileKind::IFK_SIL);
  }

  SILOptions &SILOpts = Invocation.getSILOptions();
  SILOpts.AssumeUnqualifiedOwnershipWhenParsing =
      AssumeUnqualifiedOwnershipWhenParsing;

  CompilerInstance CI;
  PrintingDiagnosticConsumer PrintDiags;
  CI.addDiagnosticConsumer(&PrintDiags);

  if (CI.setup(Invocation))
    return 1;
  CI.performSema();

  // If parsing produced an error, don't run any passes.
  if (CI.getASTContext().hadError())
    return 1;

  // Load the SIL if we have a module. We have to do this after SILParse
  // creating the unfortunate double if statement.
  if (HasSerializedAST) {
    assert(!CI.hasSILModule() &&
           "performSema() should not create a SILModule.");
    CI.setSILModule(
        SILModule::createEmptyModule(CI.getMainModule(), CI.getSILOptions()));
    std::unique_ptr<SerializedSILLoader> SL = SerializedSILLoader::create(
        CI.getASTContext(), CI.getSILModule(), nullptr);

    if (extendedInfo.isSIB())
      SL->getAllForModule(CI.getMainModule()->getName(), nullptr);
    else
      SL->getAll();
  }

  if (CommandLineFunctionNames.empty() && FunctionNameFile.empty())
    return CI.getASTContext().hadError();

  // For efficient usage, we separate our names into two separate sorted
  // lists, one of managled names, and one of unmangled names.
  std::vector<std::string> Names;
  getFunctionNames(Names);

  // First partition our function names into mangled/demangled arrays.
  auto FirstDemangledName = std::partition(
      Names.begin(), Names.end(), [](const std::string &Name) -> bool {
        StringRef NameRef(Name);
        return NameRef.startswith("_T") ||
               NameRef.startswith(MANGLING_PREFIX_STR);
      });

  // Then grab offsets to avoid any issues with iterator invalidation when we
  // sort.
  unsigned NumMangled = std::distance(Names.begin(), FirstDemangledName);
  unsigned NumNames = Names.size();

  // Then sort the two partitioned arrays.
  std::sort(Names.begin(), FirstDemangledName);
  std::sort(FirstDemangledName, Names.end());

  // Finally construct our ArrayRefs into the sorted std::vector for our
  // mangled and demangled names.
  ArrayRef<std::string> MangledNames(&*Names.begin(), NumMangled);
  ArrayRef<std::string> DemangledNames(&*std::next(Names.begin(), NumMangled),
                                       NumNames - NumMangled);

  DEBUG(llvm::errs() << "MangledNames to keep:\n";
        std::for_each(MangledNames.begin(), MangledNames.end(),
                      [](const std::string &str) {
                        llvm::errs() << "    " << str << '\n';
                      }));
  DEBUG(llvm::errs() << "DemangledNames to keep:\n";
        std::for_each(DemangledNames.begin(), DemangledNames.end(),
                      [](const std::string &str) {
                        llvm::errs() << "    " << str << '\n';
                      }));

  removeUnwantedFunctions(CI.getSILModule(), MangledNames, DemangledNames);

  if (EmitSIB) {
    llvm::SmallString<128> OutputFile;
    if (OutputFilename.size()) {
      OutputFile = OutputFilename;
    } else if (ModuleName.size()) {
      OutputFile = ModuleName;
      llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);
    } else {
      OutputFile = CI.getMainModule()->getName().str();
      llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);
    }

    SerializationOptions serializationOpts;
    serializationOpts.OutputPath = OutputFile.c_str();
    serializationOpts.SerializeAllSIL = true;
    serializationOpts.IsSIB = true;

    serialize(CI.getMainModule(), serializationOpts, CI.getSILModule());
  } else {
    const StringRef OutputFile =
        OutputFilename.size() ? StringRef(OutputFilename) : "-";

    if (OutputFile == "-") {
      CI.getSILModule()->print(llvm::outs(), EmitVerboseSIL, CI.getMainModule(),
                               EnableSILSortOutput, !DisableASTDump);
    } else {
      std::error_code EC;
      llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_None);
      if (EC) {
        llvm::errs() << "while opening '" << OutputFile << "': " << EC.message()
                     << '\n';
        return 1;
      }
      CI.getSILModule()->print(OS, EmitVerboseSIL, CI.getMainModule(),
                               EnableSILSortOutput, !DisableASTDump);
    }
  }
}
int main(int argc, const char **argv) {
    llvm::sys::PrintStackTraceOnErrorSignal();
    Transforms TransformManager;
    ReplacementHandling ReplacementHandler;

    TransformManager.registerTransforms();

    // Hide all options we don't define ourselves. Move pre-defined 'help',
    // 'help-list', and 'version' to our general category.
    llvm::StringMap<cl::Option*> Options;
    cl::getRegisteredOptions(Options);
    const cl::OptionCategory **CategoryEnd =
        VisibleCategories + llvm::array_lengthof(VisibleCategories);
    for (llvm::StringMap<cl::Option *>::iterator I = Options.begin(),
            E = Options.end();
            I != E; ++I) {
        if (I->first() == "help" || I->first() == "version" ||
                I->first() == "help-list")
            I->second->setCategory(GeneralCategory);
        else if (std::find(VisibleCategories, CategoryEnd, I->second->Category) ==
                 CategoryEnd)
            I->second->setHiddenFlag(cl::ReallyHidden);
    }
    cl::SetVersionPrinter(&printVersion);

    // Parse options and generate compilations.
    std::unique_ptr<CompilationDatabase> Compilations(
        FixedCompilationDatabase::loadFromCommandLine(argc, argv));
    cl::ParseCommandLineOptions(argc, argv);

    // Populate the ModifiableFiles structure.
    GlobalOptions.ModifiableFiles.readListFromString(IncludePaths, ExcludePaths);
    GlobalOptions.ModifiableFiles.readListFromFile(IncludeFromFile,
            ExcludeFromFile);

    if (!Compilations) {
        std::string ErrorMessage;
        Compilations = autoDetectCompilations(ErrorMessage);
        if (!Compilations) {
            llvm::errs() << llvm::sys::path::filename(argv[0]) << ": " << ErrorMessage
                         << "\n";
            return 1;
        }
    }

    // Populate source files.
    std::vector<std::string> Sources;
    if (!SourcePaths.empty()) {
        // Use only files that are not explicitly excluded.
        std::remove_copy_if(SourcePaths.begin(), SourcePaths.end(),
                            std::back_inserter(Sources),
                            isFileExplicitlyExcludedPredicate);
    } else {
        if (GlobalOptions.ModifiableFiles.isIncludeListEmpty()) {
            llvm::errs() << llvm::sys::path::filename(argv[0])
                         << ": Use -include to indicate which files of "
                         << "the compilatiion database to transform.\n";
            return 1;
        }
        // Use source paths from the compilation database.
        // We only transform files that are explicitly included.
        Sources = Compilations->getAllFiles();
        std::vector<std::string>::iterator E = std::remove_if(
                Sources.begin(), Sources.end(), isFileNotIncludedPredicate);
        Sources.erase(E, Sources.end());
    }



    // check if line ranges are just applyed to single files
    if ( !LineRanges.empty() && Sources.size() > 1 ) {
        llvm::errs() << "error: -line can only be used for single file.\n";
        return 1;
    }

    // add the line ranges to the sources
    if ( !LineRanges.empty() ) {
    }


    std::string filename;
    int line_begin, column_begin;
    int line_end, column_end;

    if ( Target.getNumOccurrences() ) {
        // TODO parse the target data
        std::stringstream sstr(Target);
        char separator;
        sstr >>
             line_begin >> separator >>
             column_begin >> separator >>
             line_end >> separator >>
             column_end >> separator >> filename;

        llvm::errs() << filename << " " << line_begin << "-" <<
                     column_begin << ":" << line_end << "-" << column_end << "\n";

        // store it in the Transform object
    }
示例#21
0
int main(int argc, char* argv[]) {
    CodeHandler::Init(argc,argv);

    // First check if the report file exists and if not create the table header
    fstream report_file;
    const char * report_file_name = (ReportFilename.size()) ? ReportFilename[0].c_str() : "report.out";
    report_file.open(report_file_name,ios::in);
    bool file_exists = report_file.is_open();
    report_file.close();

    report_file.open(report_file_name,ofstream::out | ofstream::app);
    if ( !file_exists )
        report_file << "| " << setw(15) << "Filename" << " | " <<
        setw(10) << "Domain" << " | " <<
        setw(12) << "CanonPoint" << " | " <<
        setw(15) << "CanonStrategy" << " | " <<
        setw(6) << "#Added" << " | " <<
        setw(8) << "#Deleted" << " | " <<
        setw(12) << "#DiffPoints" << " | " <<
        setw(6) << "#Diffs" << " | " <<
        setw(15) << "Optimal #Diffs" << "|\n";

    report_file << "| "<< setw(15) << InputFilename << 
    " | " << setw(10) << string(ManagerType[0]) << 
    " | " << setw(12) << string((PartitionPoint.size() > 0) ? PartitionPoint[0] : "none") << 
    " | " << setw(15) << string((PartitionStrategy.size() > 0) ? PartitionStrategy[0] : "equiv") <<
    " | ";

    string filename = InputFilename, patched_filname = PatchedFilename[0];
    // Start by guarding both files

    GuardFilename.addValue(filename);
    cout << "GuardFilename = " << GuardFilename[0] << endl;
    InputFilename = GuardFilename[0];
    UnionCompiler().GuardedInstructionsTransform();
    // Ignore this option from now own (the condition is size() == 1)
    GuardFilename.addValue("");

    GuardTaggedFilename.addValue(patched_filname);
    cout << "GuardTaggedFilename = " << GuardTaggedFilename[0] << endl;
    InputFilename = GuardTaggedFilename[0];
    UnionCompiler().GuardedInstructionsTransform();
    // Ignore this option from now own (the condition is size() == 1)
    GuardTaggedFilename.addValue("");

    // Now tag the patched file
    TagFilename.addValue(Defines::kGuardedFilenamePrefix + patched_filname);
    cout << "TagFilename = " << TagFilename[0] << endl;
    InputFilename = TagFilename[0];
    UnionCompiler().TagInstructionsTransform();
    // Ignore this option from now own (the condition is size() == 1)
    TagFilename.addValue("");

    // Now union the files
    InputFilename.setValue(Defines::kGuardedFilenamePrefix + filename);
    PatchedFilename[0] = Defines::kTaggedFilenamePrefix + Defines::kGuardedFilenamePrefix + patched_filname;
    cout << "InputFilename = " << InputFilename << ",PatchedFilename = " << PatchedFilename[0] << endl;
    UnionCompiler().UnionTransform(report_file);
    // Ignore this option from now own (the condition is size() == 1)
    PatchedFilename.addValue("");

    // Now analyze it
    InputFilename.setValue(Defines::kUnionedFilenamePrefix + filename);
    cout << "InputFilename = " << InputFilename << endl;
    Analyzer().RunAnalysis(report_file);

    report_file << setw(15) <<" |\n";
    report_file.close();

    return 0;

}
示例#22
0
bool clang::ProcessWarningOptions(Diagnostic &Diags) {
  Diags.setSuppressSystemWarnings(true);  // Default to -Wno-system-headers
  Diags.setIgnoreAllWarnings(OptNoWarnings);

  // If -pedantic or -pedantic-errors was specified, then we want to map all
  // extension diagnostics onto WARNING or ERROR unless the user has futz'd
  // around with them explicitly.
  if (OptPedanticErrors)
    Diags.setExtensionHandlingBehavior(Diagnostic::Ext_Error);
  else if (OptPedantic)
    Diags.setExtensionHandlingBehavior(Diagnostic::Ext_Warn);
  else
    Diags.setExtensionHandlingBehavior(Diagnostic::Ext_Ignore);
  
  // FIXME: -Wfatal-errors / -Wfatal-errors=foo

  for (unsigned i = 0, e = OptWarnings.size(); i != e; ++i) {
    const std::string &Opt = OptWarnings[i];
    const char *OptStart = &Opt[0];
    const char *OptEnd = OptStart+Opt.size();
    assert(*OptEnd == 0 && "Expect null termination for lower-bound search");
    
    // Check to see if this warning starts with "no-", if so, this is a negative
    // form of the option.
    bool isPositive = true;
    if (OptEnd-OptStart > 3 && memcmp(OptStart, "no-", 3) == 0) {
      isPositive = false;
      OptStart += 3;
    }

    // Figure out how this option affects the warning.  If -Wfoo, map the
    // diagnostic to a warning, if -Wno-foo, map it to ignore.
    diag::Mapping Mapping = isPositive ? diag::MAP_WARNING : diag::MAP_IGNORE;

    // -Wsystem-headers is a special case, not driven by the option table.  It
    // cannot be controlled with -Werror.
    if (OptEnd-OptStart == 14 && memcmp(OptStart, "system-headers", 14) == 0) {
      Diags.setSuppressSystemWarnings(!isPositive);
      continue;
    }
    
    // -Werror/-Wno-error is a special case, not controlled by the option table.
    // It also has the "specifier" form of -Werror=foo.
    if (OptEnd-OptStart >= 5 && memcmp(OptStart, "error", 5) == 0) {
      const char *Specifier = 0;
      if (OptEnd-OptStart != 5) {  // Specifier must be present.
        if (OptStart[5] != '=' || OptEnd-OptStart == 6) {
          fprintf(stderr, "warning: unknown -Werror warning specifier: -W%s\n",
                  Opt.c_str());
          continue;
        }
        Specifier = OptStart+6;
      }
      
      if (Specifier == 0) {
        Diags.setWarningsAsErrors(true);
        continue;
      }
      
      // -Werror=foo maps foo to Error, -Wno-error=foo maps it to Warning.
      Mapping = isPositive ? diag::MAP_ERROR : diag::MAP_WARNING_NO_WERROR;
      OptStart = Specifier;
    }
    
    WarningOption Key = { OptStart, 0, 0 };
    const WarningOption *Found =
      std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
                       WarningOptionCompare);
    if (Found == OptionTable + OptionTableSize ||
        strcmp(Found->Name, OptStart) != 0) {
      fprintf(stderr, "warning: unknown warning option: -W%s\n", Opt.c_str());
      continue;
    }
    
    MapGroupMembers(Found, Mapping, Diags);
  }
  
  return false;
}
示例#23
0
文件: ygas.cpp 项目: 8l/yasm-nextgen
static int
do_assemble(SourceManager& source_mgr, DiagnosticsEngine& diags)
{
    // Apply warning settings
    ApplyWarningSettings(diags);

    // Determine objfmt_bits based on -32 and -64 options
    std::string objfmt_bits = GetBitsSetting();

    FileManager& file_mgr = source_mgr.getFileManager();
    Assembler assembler("x86", YGAS_OBJFMT_BASE + objfmt_bits, diags,
                        dump_object);
    HeaderSearch headers(file_mgr);

    if (diags.hasFatalErrorOccurred())
        return EXIT_FAILURE;

    // Set object filename if specified.
    if (!obj_filename.empty())
        assembler.setObjectFilename(obj_filename);

    // Set parser.
    assembler.setParser("gas", diags);

    if (diags.hasFatalErrorOccurred())
        return EXIT_FAILURE;

    // Set debug format to dwarf2pass if it's legal for this object format.
    if (assembler.isOkDebugFormat("dwarf2pass"))
    {
        assembler.setDebugFormat("dwarf2pass", diags);
        if (diags.hasFatalErrorOccurred())
            return EXIT_FAILURE;
    }

    // open the input file or STDIN (for filename of "-")
    if (in_filename == "-")
    {
        OwningPtr<MemoryBuffer> my_stdin;
        if (llvm::error_code err = MemoryBuffer::getSTDIN(my_stdin))
        {
            diags.Report(SourceLocation(), diag::fatal_file_open)
                << in_filename << err.message();
            return EXIT_FAILURE;
        }
        source_mgr.createMainFileIDForMemBuffer(my_stdin.take());
    }
    else
    {
        const FileEntry* in = file_mgr.getFile(in_filename);
        if (!in)
        {
            diags.Report(SourceLocation(), diag::fatal_file_open)
                << in_filename;
            return EXIT_FAILURE;
        }
        source_mgr.createMainFileID(in);
    }

    // Initialize the object.
    if (!assembler.InitObject(source_mgr, diags))
        return EXIT_FAILURE;

    // Configure object per command line parameters.
    ConfigureObject(*assembler.getObject());

    // Predefine symbols.
    for (std::vector<std::string>::const_iterator i=defsym.begin(),
         end=defsym.end(); i != end; ++i)
    {
        StringRef str(*i);
        size_t equalpos = str.find('=');
        if (equalpos == StringRef::npos)
        {
            diags.Report(diag::fatal_bad_defsym) << str;
            continue;
        }
        StringRef name = str.slice(0, equalpos);
        StringRef vstr = str.slice(equalpos+1, StringRef::npos);

        IntNum value;
        if (!vstr.empty())
        {
            // determine radix
            unsigned int radix;
            if (vstr[0] == '0' && vstr.size() > 1 &&
                (vstr[1] == 'x' || vstr[1] == 'X'))
            {
                vstr = vstr.substr(2);
                radix = 16;
            }
            else if (vstr[0] == '0')
            {
                vstr = vstr.substr(1);
                radix = 8;
            }
            else
                radix = 10;

            // check validity
            const char* ptr = vstr.begin();
            const char* end = vstr.end();
            if (radix == 16)
            {
                while (ptr != end && isxdigit(*ptr))
                    ++ptr;
            }
            else if (radix == 8)
            {
                while (ptr != end && (*ptr >= '0' && *ptr <= '7'))
                    ++ptr;
            }
            else
            {
                while (ptr != end && isdigit(*ptr))
                    ++ptr;
            }
            if (ptr != end)
            {
                diags.Report(diag::fatal_bad_defsym) << name;
                continue;
            }
            value.setStr(vstr, radix);
        }

        // define equ
        assembler.getObject()->getSymbol(name)->DefineEqu(Expr(value));
    }

    if (diags.hasFatalErrorOccurred())
        return EXIT_FAILURE;

    // Initialize the parser.
    assembler.InitParser(source_mgr, diags, headers);

    // Assemble the input.
    if (!assembler.Assemble(source_mgr, diags))
    {
        // An error occurred during assembly.
        return EXIT_FAILURE;
    }

    // open the object file for output
    std::string err;
    raw_fd_ostream out(assembler.getObjectFilename().str().c_str(),
                       err, raw_fd_ostream::F_Binary);
    if (!err.empty())
    {
        diags.Report(SourceLocation(), diag::err_cannot_open_file)
            << obj_filename << err;
        return EXIT_FAILURE;
    }

    if (!assembler.Output(out, diags))
    {
        // An error occurred during output.
        // If we had an error at this point, we also need to delete the output
        // object file (to make sure it's not left newer than the source).
        out.close();
        remove(assembler.getObjectFilename().str().c_str());
        return EXIT_FAILURE;
    }

    // close object file
    out.close();
    return EXIT_SUCCESS;
}
示例#24
0
文件: ygas.cpp 项目: 8l/yasm-nextgen
static void
ApplyWarningSettings(DiagnosticsEngine& diags)
{
    // Disable init-nobits and uninit-contents by default.
    diags.setDiagnosticGroupMapping("init-nobits", diag::MAP_IGNORE);
    diags.setDiagnosticGroupMapping("uninit-contents", diag::MAP_IGNORE);

    // Walk through inhibit_warnings, fatal_warnings, enable_warnings, and
    // no_signed_overflow in parallel, ordering by command line argument
    // position.
    unsigned int inhibit_pos = 0, inhibit_num = 0;
    unsigned int enable_pos = 0,  enable_num = 0;
    unsigned int fatal_pos = 0,   fatal_num = 0;
    unsigned int signed_pos = 0,  signed_num = 0;
    for (;;)
    {
        if (inhibit_num < inhibit_warnings.size())
            inhibit_pos = inhibit_warnings.getPosition(inhibit_num);
        else
            inhibit_pos = 0;
        if (enable_num < enable_warnings.size())
            enable_pos = enable_warnings.getPosition(enable_num);
        else
            enable_pos = 0;
        if (fatal_num < fatal_warnings.size())
            fatal_pos = fatal_warnings.getPosition(fatal_num);
        else
            fatal_pos = 0;
        if (signed_num < no_signed_overflow.size())
            signed_pos = no_signed_overflow.getPosition(signed_num);
        else
            signed_pos = 0;

        if (inhibit_pos != 0 &&
            (enable_pos == 0 || inhibit_pos < enable_pos) &&
            (fatal_pos == 0 || inhibit_pos < fatal_pos) &&
            (signed_pos == 0 || inhibit_pos < signed_pos))
        {
            // Handle inhibit option
            ++inhibit_num;
            diags.setIgnoreAllWarnings(true);
        }
        else if (enable_pos != 0 &&
                 (inhibit_pos == 0 || enable_pos < inhibit_pos) &&
                 (fatal_pos == 0 || enable_pos < fatal_pos) &&
                 (signed_pos == 0 || enable_pos < signed_pos))
        {
            // Handle enable option
            ++enable_num;
            diags.setIgnoreAllWarnings(false);
            diags.setWarningsAsErrors(false);
            diags.setDiagnosticGroupMapping("signed-overflow",
                                            diag::MAP_WARNING);
        }
        else if (fatal_pos != 0 &&
                 (enable_pos == 0 || fatal_pos < enable_pos) &&
                 (inhibit_pos == 0 || fatal_pos < inhibit_pos) &&
                 (signed_pos == 0 || fatal_pos < signed_pos))
        {
            // Handle fatal option
            ++fatal_num;
            diags.setWarningsAsErrors(true);
        }
        else if (signed_pos != 0 &&
                 (enable_pos == 0 || signed_pos < enable_pos) &&
                 (fatal_pos == 0 || signed_pos < fatal_pos) &&
                 (inhibit_pos == 0 || signed_pos < inhibit_pos))
        {
            // Handle signed option
            ++signed_num;
            diags.setDiagnosticGroupMapping("signed-overflow",
                                            diag::MAP_IGNORE);
        }
        else
            break; // we're done with the list
    }
}
示例#25
0
文件: Lift.cpp 项目: kumarak/mcsema
int main(int argc, char *argv[]) {
  llvm::cl::SetVersionPrinter(PrintVersion);
  llvm::cl::ParseCommandLineOptions(argc, argv, "CFG to LLVM");

  auto context = llvm::make_unique<llvm::LLVMContext>();

  if (OS.empty()) {
    if (ListSupported || ListUnsupported) {
      OS = "linux"; // just need something
    }
    else {
      std::cerr << "-os must be specified" << std::endl;
      return EXIT_FAILURE;
    }
  }

  if (!(ListSupported || ListUnsupported || ListCFGFunctions) && EntryPoints.empty()) {
    std::cerr
        << "-entrypoint must be specified" << std::endl;
        return EXIT_FAILURE;
  }

  if (!InitArch(context.get(), OS, Arch)) {
    std::cerr
        << "Cannot initialize for arch " << Arch
        << " and OS " << OS << std::endl;
    return EXIT_FAILURE;
  }

  auto M = CreateModule(context.get());
  if (!M) {
    return EXIT_FAILURE;
  }

  auto triple = M->getTargetTriple();

  if (ListSupported || ListUnsupported) {
    ListArchSupportedInstructions(triple, llvm::outs(), ListSupported, ListUnsupported);
    return EXIT_SUCCESS;
  }

  if (InputFilename.empty()) {
    std::cerr
        << "Must specify an input file." << std::endl;
    return EXIT_FAILURE;
  }

  //reproduce NativeModule from CFG input argument
  try {
    std::unique_ptr<NativeModule> mod(ReadProtoBuf(InputFilename));
    if (!mod) {
      std::cerr << "Unable to read module from CFG" << std::endl;
      return EXIT_FAILURE;
    }

    if (ListCFGFunctions) {
      PrintCFGFunctionList(mod.get(), Arch);
      return EXIT_SUCCESS;
    }

    //make sure the entry point list is correct before we start lifting the code
    const std::vector<NativeEntrySymbol> &module_entry_points = mod->getEntryPoints();

    for (const auto &entry_point : EntryPoints) {
      auto it = std::find_if(
        module_entry_points.begin(),
        module_entry_points.end(),

        [&entry_point](const NativeEntrySymbol &symbol) -> bool {
          return (symbol.getName() == entry_point);
        }
      );

      if (it == module_entry_points.end()) {
          std::cerr << "The following entry point could not be found: \"" << entry_point << "\". Aborting..." << std::endl;
          return EXIT_FAILURE;
      }
    }

    //now, convert it to an LLVM module
    ArchInitAttachDetach(M);

    if (!LiftCodeIntoModule(mod.get(), M)) {
      std::cerr << "Failure to convert to LLVM module!" << std::endl;
      return EXIT_FAILURE;
    }

    std::set<VA> entry_point_pcs;
    for (const auto &entry_point_name : EntryPoints) {
      auto entry_pc = FindSymbolInModule(mod.get(), entry_point_name);
      assert(entry_pc != static_cast<VA>( -1));

      std::cerr << "Adding entry point: " << entry_point_name << std::endl
                << entry_point_name << " is implemented by sub_" << std::hex
                << entry_pc << std::endl;

      if ( !ArchAddEntryPointDriver(M, entry_point_name, entry_pc)) {
        return EXIT_FAILURE;
      }

      entry_point_pcs.insert(entry_pc);
    }

    RenameLiftedFunctions(mod.get(), M, entry_point_pcs);

    // will abort if verification fails
    if (llvm::verifyModule( *M, &llvm::errs())) {
      std::cerr << "Could not verify module!" << std::endl;
      return EXIT_FAILURE;
    }

    std::error_code ec;
    llvm::tool_output_file Out(OutputFilename.c_str(), ec,
                               llvm::sys::fs::F_None);
    llvm::WriteBitcodeToFile(M, Out.os());
    Out.keep();

  } catch (std::exception &e) {
    std::cerr << "error: " << std::endl << e.what() << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
示例#26
0
文件: callgraph.cpp 项目: aaasz/SHP
int main(int argc, char **argv) {
  llvm::cl::ParseCommandLineOptions(argc-2, argv, "callgraph");

  FileManager FileMgr;
  std::vector<ASTUnit*> ASTUnits;

  if (InputFilenames.empty())
    return 0;

  TextDiagnosticBuffer DiagClient;

  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
    const std::string &InFile = InputFilenames[i];

    std::string ErrMsg;
    llvm::OwningPtr<ASTUnit> AST;
    clang::Diagnostic diagnostic;

    AST.reset(ASTUnit::LoadFromPCHFile(InFile,diagnostic,false,true));

    if (!AST) {
      llvm::errs() << "[" << InFile << "] error: " << ErrMsg << '\n';
      return 1;
    }

    ASTUnits.push_back(AST.take());
  }

  llvm::OwningPtr<CallGraph> CG;
  CG.reset(new CallGraph());

  for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i){
    CG->addTU(ASTUnits[i]->getASTContext());

  }

  //std::cout<<"ajuns aici\n";
  std::cout<<"start = "<<argv[argc-2]<<"\n";
  std::cout<<"end = "<<argv[argc-1]<<"\n";

  std::vector<ProcessGraph *> pg1;
  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
		const std::string &InFile = InputFilenames[i];
		Splitter splitter(InFile);

		// std::cout << "begin1\n";
		if (!splitter.hasErrors()) {
		//	 std::cout << "begin2\n";
			splitter.splitFiles(i == 0, i == 0 ? "hw" : "sw");
		//	 std::cout << "begin3\n";
			std::vector<ProcessGraph *> *pg = splitter.getConfigs();
			if (pg->size() != 0) {
				if (pg->size() != 1) {
					std::cout << "Error :(too many)/none config functions\n";
					exit(-1);
				}
				pg1 = *pg;
			}
			/*Partitioner p(ProcessGraph *pg, int populationSize, int maxIter,unsigned int maxLUTS,
			 unsigned int maxSLICES);
			 */

		}
		// std::cout << "end1\n";
	}


	GraphDataAppender gda(pg1[0], "/home/Silviu/workspace/big_test");
	Partitioner p(pg1[0], 400, 400,false,argv[argc-2],argv[argc-1]);
	bool *bestSolution = p.getBestSolution();
	ProcessGraph *pgc = pg1[0];
	std::cout<<pgc->getMaxLUTS()<<" "<<pgc->getMaxSLICES()<<"\n";
	for (int i=0; i<pgc->getNumVertices(); i++){
		ProcessGraphNode *pgn = pgc->lookupGraphNode(i);
		std::cout<<pgn->getName()<<":\n";
		VertexData vd = pgn->getVertexData();
		std::cout << vd.hadrwareExecutionTime << "\n";
		std::cout << vd.communicationTime << "\n";
		std::cout << vd.softwareExecutionTime << "\n";
		std::cout << vd.LUTS << "\n";
		std::cout << vd.SLICES << "\n";
	}

	std::cout<<"Solutia partitionarii:\n";
	for (int i=0; i<pgc->getNumVertices(); i++){
		std::cout<<pgc->lookupGraphNode(i)->getName()<<" :"<<(bestSolution[i] == HARDWARE ? "Hardware" : "Software") << "\n";
	}

}
int main(int argc, const char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  Transforms TransformManager;
  ReplacementHandling ReplacementHandler;

  TransformManager.registerTransforms();

  // Hide all options we don't define ourselves. Move pre-defined 'help',
  // 'help-list', and 'version' to our general category.
  llvm::StringMap<cl::Option*> Options;
  cl::getRegisteredOptions(Options);
  const cl::OptionCategory **CategoryEnd =
      VisibleCategories + llvm::array_lengthof(VisibleCategories);
  for (llvm::StringMap<cl::Option *>::iterator I = Options.begin(),
                                               E = Options.end();
       I != E; ++I) {
    if (I->first() == "help" || I->first() == "version" ||
        I->first() == "help-list")
      I->second->setCategory(GeneralCategory);
    else if (std::find(VisibleCategories, CategoryEnd, I->second->Category) ==
             CategoryEnd)
      I->second->setHiddenFlag(cl::ReallyHidden);
  }
  cl::SetVersionPrinter(&printVersion);

  // Parse options and generate compilations.
  std::unique_ptr<CompilationDatabase> Compilations(
      FixedCompilationDatabase::loadFromCommandLine(argc, argv));
  cl::ParseCommandLineOptions(argc, argv);

  // Populate the ModifiableFiles structure.
  GlobalOptions.ModifiableFiles.readListFromString(IncludePaths, ExcludePaths);
  GlobalOptions.ModifiableFiles.readListFromFile(IncludeFromFile,
                                                 ExcludeFromFile);

  if (!Compilations) {
    std::string ErrorMessage;
    Compilations.reset(autoDetectCompilations(ErrorMessage));
    if (!Compilations) {
      llvm::errs() << llvm::sys::path::filename(argv[0]) << ": " << ErrorMessage
                   << "\n";
      return 1;
    }
  }

  // Populate source files.
  std::vector<std::string> Sources;
  if (!SourcePaths.empty()) {
    // Use only files that are not explicitly excluded.
    std::remove_copy_if(SourcePaths.begin(), SourcePaths.end(),
                        std::back_inserter(Sources),
                        isFileExplicitlyExcludedPredicate);
  } else {
    if (GlobalOptions.ModifiableFiles.isIncludeListEmpty()) {
      llvm::errs() << llvm::sys::path::filename(argv[0])
                   << ": Use -include to indicate which files of "
                   << "the compilatiion database to transform.\n";
      return 1;
    }
    // Use source paths from the compilation database.
    // We only transform files that are explicitly included.
    Sources = Compilations->getAllFiles();
    std::vector<std::string>::iterator E = std::remove_if(
        Sources.begin(), Sources.end(), isFileNotIncludedPredicate);
    Sources.erase(E, Sources.end());
  }

  // check if line ranges are just applyed to single files
  if ( !LineRanges.empty() && Sources.size() > 1 ){
     llvm::errs() << "error: -line can only be used for single file.\n";
     return 1;
  }

  // add the line ranges to the sources 
  if ( !LineRanges.empty() ){
  }

  if (Sources.empty()) {
    llvm::errs() << llvm::sys::path::filename(argv[0])
                 << ": Could not determine sources to transform.\n";
    return 1;
  }

  // Enable timming.
  GlobalOptions.EnableTiming = TimingDirectoryName.getNumOccurrences() > 0;

  bool CmdSwitchError = false;
  CompilerVersions RequiredVersions =
      handleSupportedCompilers(argv[0], CmdSwitchError);
  if (CmdSwitchError)
    return 1;

  TransformManager.createSelectedTransforms(GlobalOptions, RequiredVersions);

  if (TransformManager.begin() == TransformManager.end()) {
    if (SupportedCompilers.empty())
      llvm::errs() << llvm::sys::path::filename(argv[0])
                   << ": no selected transforms\n";
    else
      llvm::errs() << llvm::sys::path::filename(argv[0])
                   << ": no transforms available for specified compilers\n";
    return 1;
  }

  llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> DiagOpts(
      new DiagnosticOptions());
  DiagnosticsEngine Diagnostics(
      llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
      DiagOpts.getPtr());

  // FIXME: Make this DiagnosticsEngine available to all Transforms probably via
  // GlobalOptions.

  // If SerializeReplacements is requested, then code reformatting must be
  // turned off and only one transform should be requested.
  if (SerializeOnly &&
      (std::distance(TransformManager.begin(), TransformManager.end()) > 1 ||
       DoFormat)) {
    llvm::errs() << "Serialization of replacements requested for multiple "
                    "transforms.\nChanges from only one transform can be "
                    "serialized.\n";
    return 1;
  }

  // If we're asked to apply changes to files on disk, need to locate
  // clang-apply-replacements.
  if (!SerializeOnly) {
    if (!ReplacementHandler.findClangApplyReplacements(argv[0])) {
      llvm::errs() << "Could not find clang-apply-replacements\n";
      return 1;
    }

    if (DoFormat)
      ReplacementHandler.enableFormatting(FormatStyleOpt, FormatStyleConfig);
  }

  StringRef TempDestinationDir;
  if (SerializeLocation.getNumOccurrences() > 0)
    ReplacementHandler.setDestinationDir(SerializeLocation);
  else
    TempDestinationDir = ReplacementHandler.useTempDestinationDir();

  SourcePerfData PerfData;

  for (Transforms::const_iterator I = TransformManager.begin(),
                                  E = TransformManager.end();
       I != E; ++I) {
    Transform *T = *I;

    if (T->apply(*Compilations, Sources,LineRanges) != 0) {
      // FIXME: Improve ClangTool to not abort if just one file fails.
      return 1;
    }

    if (GlobalOptions.EnableTiming)
      collectSourcePerfData(*T, PerfData);

    if (SummaryMode) {
      llvm::outs() << "Transform: " << T->getName()
                   << " - Accepted: " << T->getAcceptedChanges();
      if (T->getChangesNotMade()) {
        llvm::outs() << " - Rejected: " << T->getRejectedChanges()
                     << " - Deferred: " << T->getDeferredChanges();
      }
      llvm::outs() << "\n";
    }

    if (!ReplacementHandler.serializeReplacements(T->getAllReplacements()))
      return 1;

    if (!SerializeOnly)
      if (!ReplacementHandler.applyReplacements())
        return 1;
  }

  // Let the user know which temporary directory the replacements got written
  // to.
  if (SerializeOnly && !TempDestinationDir.empty())
    llvm::errs() << "Replacements serialized to: " << TempDestinationDir << "\n";

  if (FinalSyntaxCheck) {
    ClangTool SyntaxTool(*Compilations, SourcePaths);
    if (SyntaxTool.run(newFrontendActionFactory<SyntaxOnlyAction>().get()) != 0)
      return 1;
  }

  // Report execution times.
  if (GlobalOptions.EnableTiming && !PerfData.empty()) {
    std::string DirectoryName = TimingDirectoryName;
    // Use default directory name.
    if (DirectoryName.empty())
      DirectoryName = "./migrate_perf";
    writePerfDataJSON(DirectoryName, PerfData);
  }

  return 0;
}
示例#28
0
文件: main.cpp 项目: E-LLP/trick
/**

Most of the main program is pieced together from examples on the web. We are doing the following.

-# Creating lists of include directories, defines, and input files from the command line arguments.
-# Initializing the compiler to read C++ code, and setting the compiler to think we are creating
   code for the default target architecture.
-# Creating the necessary source and file managers as well as the preprocessor.
-# Adding search directories and creating #define statements for -D command line arguments.
-# Telling clang to use our ICGASTConsumer as an ASTConsumer.
-# Parse the input file.

*/
int main( int argc , char * argv[] ) {

#if (__clang_major__ >= 6) || ((__clang_major__ == 3) && (__clang_minor__ >= 5))
    clang::TargetOptions to;
#elif (__clang_major__ == 3) && (__clang_minor__ >= 3)
    clang::TargetOptions * to = new clang::TargetOptions() ;
#else
    clang::TargetOptions to;
#endif
    clang::CompilerInstance ci;

    /* Gather all of the command line arguments into lists of include directories, defines, and input files.
       All other arguments will be ignored. */
    llvm::cl::SetVersionPrinter(ICG_version) ;
    llvm::cl::ParseCommandLineOptions(argc , argv) ;

    if ( ! validAttributesVersion(attr_version) ) {
        return -1 ;
    }

/*
    if ( show_units ) {
        list_units() ;
        return 0 ;
    }
*/

    if ( input_file_names.empty() ) {
        std::cerr << "No header file specified" << std::endl ;
        return 1 ;
    }

    ci.createDiagnostics();
    clang::DiagnosticOptions & diago = ci.getDiagnosticOpts() ;
    diago.ShowColors = 1 ;
    ci.getDiagnostics().setIgnoreAllWarnings(true) ;
#if ( GCC_MAJOR == 4 ) && ( GCC_MINOR <= 2 )
    ci.getDiagnostics().setSuppressAllDiagnostics() ;
#endif

    // Set all of the defaults to c++
    clang::CompilerInvocation::setLangDefaults(ci.getLangOpts() , clang::IK_CXX) ;
    ci.getLangOpts().CXXExceptions = true ;

    // Activate C++11 parsing
    ci.getLangOpts().CPlusPlus11 = true ;

    // Set the default target architecture
#if (__clang_major__ >= 6) || (__clang_major__ == 3) && (__clang_minor__ >= 5)
    to.Triple = llvm::sys::getDefaultTargetTriple();
#elif (__clang_major__ == 3) && (__clang_minor__ >= 3)
    to->Triple = llvm::sys::getDefaultTargetTriple();
#else
    to.Triple = llvm::sys::getDefaultTargetTriple();
#endif

#if (__clang_major__ >= 6) || (__clang_major__ == 3) && (__clang_minor__ >= 5)
    std::shared_ptr<clang::TargetOptions> shared_to  = std::make_shared<clang::TargetOptions>(to) ;
    clang::TargetInfo *pti = clang::TargetInfo::CreateTargetInfo(ci.getDiagnostics(), shared_to);
#else
    clang::TargetInfo *pti = clang::TargetInfo::CreateTargetInfo(ci.getDiagnostics(), to);
#endif
    ci.setTarget(pti);

    // Create all of the necessary managers.
    ci.createFileManager();
    ci.createSourceManager(ci.getFileManager());
#if (__clang_major__ >= 6) || (__clang_major__ == 3) && (__clang_minor__ >= 5)
    ci.createPreprocessor(clang::TU_Complete);
#else
    ci.createPreprocessor();
#endif

    clang::HeaderSearch & hs = ci.getPreprocessor().getHeaderSearchInfo() ;
    clang::HeaderSearchOptions & hso = ci.getHeaderSearchOpts() ;
    clang::Preprocessor & pp = ci.getPreprocessor() ;

    // Add all of the include directories to the preprocessor
    HeaderSearchDirs hsd(hs , hso , pp, sim_services_flag) ;
    hsd.addSearchDirs ( include_dirs ) ;

    // Tell the preprocessor to use its default predefines
    clang::PreprocessorOptions & ppo = ci.getPreprocessorOpts() ;
    ppo.UsePredefines = true;
#if (__clang_major__ == 3) && (__clang_minor__ >= 8)
    pp.getBuiltinInfo().initializeBuiltins(pp.getIdentifierTable(), pp.getLangOpts());
#else
    pp.getBuiltinInfo().InitializeBuiltins(pp.getIdentifierTable(), pp.getLangOpts());
#endif
    // Add all of the #define from the command line to the default predefines.
    hsd.addDefines ( defines ) ;

    // Add our comment saver as a comment handler in the preprocessor
    CommentSaver cs(ci, hsd) ;
    pp.addCommentHandler(&cs) ;

    PrintAttributes pa( attr_version, hsd, cs, ci, force, sim_services_flag, output_dir) ;

    // create new class and enum map files
    if ( create_map ) {
        pa.createMapFiles() ;
    }

    // Tell the compiler to use our ICGASTconsumer
    ICGASTConsumer *astConsumer = new ICGASTConsumer(ci, hsd, cs, pa);
#if (__clang_major__ >= 6) || ((__clang_major__ == 3) && (__clang_minor__ >= 6))
    std::unique_ptr<clang::ASTConsumer> unique_ast(astConsumer) ;
    ci.setASTConsumer(std::move(unique_ast));
#else
    ci.setASTConsumer(astConsumer);
#endif
    ci.createASTContext();
    ci.createSema(clang::TU_Prefix, NULL);

    // Get the full path of the file to be read.
    char * input_file_cp = strdup(input_file_names[0].c_str()) ;
    char * input_file_file = basename(input_file_cp) ;
    char * input_file_dir = dirname(input_file_cp) ;
    char * input_file_full_path = NULL ;
    std::stringstream os ;
    os << input_file_dir << "/" << input_file_file ;
    input_file_full_path = almostRealPath( os.str().c_str() ) ;
    //std::cout << input_file_full_path << std::endl ;

    struct stat buffer ;
    if ( stat ( input_file_full_path , &buffer) != 0 ) {
        std::cerr << "Could not open file " << input_file_full_path << std::endl ;
        exit(-1) ;
    }
    // Open up the input file and parse it.
    const clang::FileEntry *pFile = ci.getFileManager().getFile(input_file_full_path);
#if (__clang_major__ >= 6) || ((__clang_major__ == 3) && (__clang_minor__ >= 5))
    ci.getSourceManager().setMainFileID(ci.getSourceManager().createFileID(pFile, clang::SourceLocation(), clang::SrcMgr::C_User));
#else
    ci.getSourceManager().createMainFileID(pFile);
#endif
    ci.getDiagnosticClient().BeginSourceFile(ci.getLangOpts(), &ci.getPreprocessor());
    clang::ParseAST(ci.getSema());
    ci.getDiagnosticClient().EndSourceFile();

    free(input_file_cp) ;
    free(input_file_full_path) ;

    if ( ! sim_services_flag ) {
        pa.printIOMakefile() ;
    }

    // Close the map files
    pa.closeMapFiles() ;

    // Print the list of headers that have the ICG:(No) comment
    pa.printICGNoFiles() ;

    return 0;
}
示例#29
0
文件: clang-wpa.cpp 项目: CPFL/guc
int main(int argc, char **argv) {
  llvm::cl::ParseCommandLineOptions(argc, argv, "clang-wpa");
  std::vector<ASTUnit*> ASTUnits;

  Program Prog;
  Indexer Idxer(Prog);

  if (InputFilenames.empty())
    return 0;

  DiagnosticOptions DiagOpts;
  llvm::IntrusiveRefCntPtr<Diagnostic> Diags
    = CompilerInstance::createDiagnostics(DiagOpts, argc, argv);
  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
    const std::string &InFile = InputFilenames[i];
    llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromASTFile(InFile, Diags));
    if (!AST)
      return 1;

    ASTUnits.push_back(AST.take());
  }

  if (ViewCallGraph) {
    llvm::OwningPtr<CallGraph> CG;
    CG.reset(new CallGraph(Prog));

    for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i)
      CG->addTU(ASTUnits[i]->getASTContext());

    CG->ViewCallGraph();
    return 0;
  }

  if (AnalyzeFunction.empty())
    return 0;

  // Feed all ASTUnits to the Indexer.
  for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i) {
    ASTUnitTU *TU = new ASTUnitTU(ASTUnits[i]);
    Idxer.IndexAST(TU);
  }

  Entity Ent = Entity::get(AnalyzeFunction, Prog);
  FunctionDecl *FD;
  TranslationUnit *TU;
  llvm::tie(FD, TU) = Idxer.getDefinitionFor(Ent);

  if (!FD)
    return 0;

  // Create an analysis engine.
  Preprocessor &PP = TU->getPreprocessor();

  // Hard code options for now.
  AnalysisManager AMgr(TU->getASTContext(), PP.getDiagnostics(),
                       PP.getLangOptions(), /* PathDiagnostic */ 0,
                       CreateRegionStoreManager,
                       CreateRangeConstraintManager, &Idxer,
                       /* MaxNodes */ 300000, /* MaxLoop */ 3,
                       /* VisualizeEG */ false, /* VisualizeEGUbi */ false,
                       /* PurgeDead */ true, /* EagerlyAssume */ false,
                       /* TrimGraph */ false, /* InlineCall */ true, 
                       /* UseUnoptimizedCFG */ false);

  GRTransferFuncs* TF = MakeCFRefCountTF(AMgr.getASTContext(), /*GC*/false,
                                         AMgr.getLangOptions());
  GRExprEngine Eng(AMgr, TF);

  Eng.ExecuteWorkList(AMgr.getStackFrame(FD, TU), AMgr.getMaxNodes());
  
  return 0;
}
示例#30
0
int
main(int argc, char* argv[])
{
    llvm::llvm_shutdown_obj llvm_manager(false);

    cl::SetVersionPrinter(&PrintVersion);
    cl::ParseCommandLineOptions(argc, argv);

    if (show_help)
        cl::PrintHelpMessage();

    if (show_license)
    {
        for (std::size_t i=0; i<sizeof(license_msg)/sizeof(license_msg[0]); i++)
            llvm::outs() << license_msg[i] << '\n';
        return EXIT_SUCCESS;
    }

    if (show_info)
    {
        llvm::outs() << full_version << '\n';
        list_module<yasm::ObjectFormatModule>();
        return EXIT_SUCCESS;
    }

    yasm::OffsetDiagnosticPrinter diag_printer(llvm::errs());
    yasm::Diagnostic diags(&diag_printer);
    yasm::SourceManager source_mgr(diags);
    diags.setSourceManager(&source_mgr);
    diag_printer.setPrefix("yobjdump");

    // Load standard modules
    if (!yasm::LoadStandardPlugins())
    {
        diags.Report(yasm::diag::fatal_standard_modules);
        return EXIT_FAILURE;
    }

    if (show_all_headers)
    {
        show_file_headers = true;
        show_section_headers = true;
        show_private_headers = true;
        show_relocs = true;
        show_symbols = true;
    }

    // Determine input filename and open input file.
    if (in_filenames.empty())
    {
        diags.Report(yasm::diag::fatal_no_input_files);
        return EXIT_FAILURE;
    }

    int retval = EXIT_SUCCESS;

    for (std::vector<std::string>::const_iterator i=in_filenames.begin(),
         end=in_filenames.end(); i != end; ++i)
    {
        try
        {
            if (DoDump(*i, source_mgr, diags) != EXIT_SUCCESS)
                retval = EXIT_FAILURE;
        }
        catch (std::out_of_range& err)
        {
            llvm::errs() << *i << ": "
                << "out of range error while reading (corrupt file?)\n";
            retval = EXIT_FAILURE;
        }
    }
    return retval;
}