Example #1
0
void SILPassManager::run() {
  const SILOptions &Options = getOptions();
  (void) Options;

  if (SILPrintAll) {
    if (SILPrintOnlyFun.empty() && SILPrintOnlyFuns.empty()) {
      llvm::dbgs() << "*** SIL module before transformation ("
                   << NumOptimizationIterations << ") ***\n";
      Mod->dump(Options.EmitVerboseSIL);
    } else {
      for (auto &F : *Mod) {
        if (!SILPrintOnlyFun.empty() && F.getName().str() == SILPrintOnlyFun) {
          llvm::dbgs() << "*** SIL function before transformation ("
                       << NumOptimizationIterations << ") ***\n";
          F.dump(Options.EmitVerboseSIL);
        }
        if (!SILPrintOnlyFuns.empty() &&
            F.getName().find(SILPrintOnlyFuns, 0) != StringRef::npos) {
          llvm::dbgs() << "*** SIL function before transformation ("
                       << NumOptimizationIterations << ") ***\n";
          F.dump(Options.EmitVerboseSIL);
        }
      }
    }
  }
  runOneIteration();
}
Example #2
0
void updateArgIfSet(llvm::cl::opt<T> &argValue, const llvm::Optional<T> &configValue)
{
    if (configValue.hasValue() && argValue.getNumOccurrences() == 0)
    {
        argValue.setValue(configValue.getValue());
    }
}
Example #3
0
int main(int argc, char **argv) {
   Galois::StatManager M;
   LonestarStart(argc, argv, name, desc, url);
   if(use_weighted_rmat)
      readWeightedRMAT(inputfile.c_str());
   else
      makeGraph(inputfile.c_str());
#if BORUVKA_DEBUG
   EdgeDataType kruskal_wt;
   if(verify_via_kruskal){
      kruskal_wt= verify(graph);
      cout<<"Kruskal MST Result is " << kruskal_wt <<"\n";
   }
#endif
   cout << "Starting loop body\n";
   EdgeDataType mst_wt = runBodyParallel();
   cout<<"Boruvka MST Result is " << mst_wt <<"\n";
#if BORUVKA_DEBUG
   if(verify_via_kruskal){
      assert(kruskal_wt==mst_wt);
   }
#endif

#if COMPILE_STATISICS
   cout<< " \n==================================================\n";
   stat_collector.dump(cout);
   cout<< " \n==================================================\n";
#endif
   return 0;
}
Example #4
0
int main(int argc, char** argv)
{
    // Should ParseCommandLineOptions be able to accept a const argv?
    llvm::cl::ParseCommandLineOptions(argc, argv, "ploy compiler\n");

    const char* file_location = InputFile.c_str();

    symbol_table* tbl = sym_tbl = init_symbol_table();
    init_symbols(tbl);

    pointer ret = parse_file_to_tree(file_location, tbl);
    if(!ret)
        return 1;

    materialize_includes(&ret, tbl);

    ploy_do_compile(ret, tbl);
    type_map type_define_map;
    transform_tree_gen_typedef(ret, tbl, &type_define_map);
    transform_tree_gen_typeinfo(ret, tbl, &type_define_map);

    compiler* compile = init_compiler(tbl);

    compiler_compile_expression(compile, ret, EntryFunc.c_str());
    compiler_print_module(compile);
    compiler_write_asm_file(compile, OutputFile.c_str());

    destroy_compiler(compile);

    destroy_symbol_table(tbl);
    return 0;
}
Example #5
0
  NumDebugFrontendAction() {
#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR == 8
      std::error_code EC; 
      out = new llvm::raw_fd_ostream(output_file.c_str(), EC, 
              llvm::sys::fs::OpenFlags::F_None);
#else
      std::string code;
      out = new llvm::raw_fd_ostream(output_file.c_str(), code,
              llvm::sys::fs::OpenFlags::F_None);
#endif
  }
Example #6
0
// Test the function and pass names we're given against the debug
// options that force us to break prior to a given pass and/or on a
// given function.
static bool breakBeforeRunning(StringRef fnName, StringRef passName) {
  if (SILBreakOnFun.empty() && SILBreakOnPass.empty())
    return false;

  if (SILBreakOnFun.empty() && passName == SILBreakOnPass)
    return true;

  if (SILBreakOnPass.empty() && fnName == SILBreakOnFun)
    return true;

  return fnName == SILBreakOnFun && passName == SILBreakOnPass;
}
Example #7
0
static void printModule(SILModule *Mod, bool EmitVerboseSIL) {
  if (SILPrintOnlyFun.empty() && SILPrintOnlyFuns.empty()) {
    Mod->dump();
    return;
  }
  for (auto &F : *Mod) {
    if (!SILPrintOnlyFun.empty() && F.getName().str() == SILPrintOnlyFun)
      F.dump(EmitVerboseSIL);

    if (!SILPrintOnlyFuns.empty() &&
        F.getName().find(SILPrintOnlyFuns, 0) != StringRef::npos)
      F.dump(EmitVerboseSIL);
  }
}
Example #8
0
// Test the function and pass names we're given against the debug
// options that force us to break prior to a given pass and/or on a
// given function.
static bool breakBeforeRunning(StringRef fnName, SILFunctionTransform *SFT) {
  if (SILBreakOnFun.empty() && SILBreakOnPass.empty())
    return false;

  if (SILBreakOnFun.empty()
      && (SFT->getName() == SILBreakOnPass || SFT->getTag() == SILBreakOnPass))
    return true;

  if (SILBreakOnPass.empty() && fnName == SILBreakOnFun)
    return true;

  return fnName == SILBreakOnFun
    && (SFT->getName() == SILBreakOnPass || SFT->getTag() == SILBreakOnPass);
}
Example #9
0
int main(int argc, char** argv) {
  LonestarStart(argc, argv, name, desc, url);

	srand(-1);
	MetisGraph metisGraph;
	GGraph graph;
	metisGraph.setGraph(&graph);
	bool directed = true;
	if(mtxInput){
	  readMetisGraph(&metisGraph, filename.c_str());
	}else{
	  readGraph(&metisGraph, filename.c_str(), weighted, directed);
	}
	partition(&metisGraph, numPartitions);
	verify(&metisGraph);
}
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;
}
Example #11
0
int main(int argc, char** argv) {
  Galois::StatManager statManager;
  LonestarStart(argc, argv, name, desc, url);

  Galois::StatTimer Tinitial("InitializeTime");
  Tinitial.start();
  graph.structureFromFile(inputFilename.c_str());
  std::cout << "Num nodes: " << graph.size() << "\n";
  Tinitial.stop();

  //Galois::preAlloc(numThreads);
  Galois::Statistic("MeminfoPre", GaloisRuntime::MM::pageAllocInfo());
  switch (algo) {
    case demo: run<DemoAlgo>(); break;
    case asynchronous: run<AsynchronousAlgo>(); break;
    default: std::cerr << "Unknown algo: " << algo << "\n";
  }
  Galois::Statistic("MeminfoPost", GaloisRuntime::MM::pageAllocInfo());

  if (!skipVerify && !verify()) {
    std::cerr << "verification failed\n";
    assert(0 && "verification failed");
    abort();
  }

  return 0;
}
/// HSAILTargetMachine ctor -
///
HSAILTargetMachine::HSAILTargetMachine(const Target &T, StringRef TT,
    StringRef CPU, StringRef FS,const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM,CodeGenOpt::Level OL, bool is64bitTarget )
:
  LLVMTargetMachine(T, TT, CPU, FS,Options, RM, CM,OL),
  Subtarget(TT, CPU, FS, is64bitTarget),
  //  DLInfo(Subtarget.getDataLayout()),
  FrameLowering(TargetFrameLowering::StackGrowsUp,
      Subtarget.getStackAlignment(), 0),
  //  InstrInfo(*this),
  //  TLInfo(*this), 
  IntrinsicInfo(this)
 {
     if (FileType == CGFT_AssemblyFile) {
       if (FileType.getNumOccurrences() == 0) {
         // LLVM's default is CGFT_AssemblyFile. HSAIL default is binary BRIG,
         // thus we need to change output to CGFT_AssemblyFile, unless text
         // assembly was explicitly requested by the command line switch.
         HSAILFileType = FileType = CGFT_ObjectFile;
       }
     }

     setAsmVerbosityDefault(true);

     // disable use of the .loc directive, because only by 
     // setting this to false does DwarfDebug generate the .debug_line
     // section
     //
     setMCUseLoc(false);

}
Example #13
0
int KoonDriver::output() const {
    Kompiler kompiler(OutputFilename);
    int res = kompiler.kompile(*this->_k.module());

    if (res) return res;
    std::string object = "/tmp/" + OutputFilename + ".o";

    Process("/usr/bin/ld",
            "--build-id",
            "--eh-frame-hdr",
            "--hash-style=gnu",
            "-m",
            "elf_x86_64",
            "-dynamic-linker",
            "/lib64/ld-linux-x86-64.so.2",
            "../krt/krt0.o",
//            "-L/usr/lib/gcc/x86_64-pc-linux-gnu/6.2.1",
            "-L/usr/lib",
            object.c_str(),
//            "-lgcc",
//            "--as-needed",
//            "-lgcc_s",
//            "--no-as-needed",
            "-lc",
            "-o",
            OutputFilename.c_str());

    Process("/usr/bin/rm", "-f", object.c_str());
    return res;
}
Example #14
0
// 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);
}
Example #15
0
void SILFunction::viewCFG() const {
/// When asserts are disabled, this should be a NoOp.
#ifndef NDEBUG
    // If we have a target function, only print that function out.
    if (!TargetFunction.empty() && !(getName().str() == TargetFunction))
      return;

  ViewGraph(const_cast<SILFunction *>(this), "cfg" + getName().str());
#endif
}
Example #16
0
static llvm::tool_output_file *
GetOutputStream() {
 
    if (OutputFilename.empty()) {
        OutputFilename = GetFileNameRoot(InputFilename) + ".o";
    }
    
    string error;
    unsigned openFlags = llvm::raw_fd_ostream::F_Binary;
    llvm::tool_output_file * FDOut = new llvm::tool_output_file(OutputFilename.c_str(), error, openFlags);
    
    if (!error.empty()) {
        llvm::errs() << error << '\n';
        delete FDOut;
        return NULL;
    }
    
    return FDOut;
}
void readInOutGraph(Graph& graph) {
  using namespace Galois::Graph;
  if (symmetricGraph) {
    Galois::Graph::readGraph(graph, filename);
  } else if (transposeGraphName.size()) {
    Galois::Graph::readGraph(graph, filename, transposeGraphName);
  } else {
    GALOIS_DIE("Graph type not supported");
  }
}
Example #18
0
static void viewCFGHelper(const SILFunction* f, bool skipBBContents) {
/// When asserts are disabled, this should be a NoOp.
#ifndef NDEBUG
    // If we have a target function, only print that function out.
    if (!TargetFunction.empty() && !(f->getName().str() == TargetFunction))
      return;

    ViewGraph(const_cast<SILFunction *>(f), "cfg" + f->getName().str(),
              /*shortNames=*/skipBBContents);
#endif
}
Example #19
0
int main(int argc, const char **argv) {
  int success = 0;
  if (argc > 1) {
    clang::tooling::CommonOptionsParser OptionsParser(argc, argv, OpOvLintCategory);
    OpOvApp app(Conf.getValue());
    app.init();
    success = app.execute(OptionsParser.getCompilations(), OptionsParser.getSourcePathList());
    app.cleanUp();
  }
  return success;
}
Example #20
0
int main(int argc, const char *argv[]) {
  llvm::cl::ParseCommandLineOptions(argc, argv);
  if (LogLevel < 0 || LogLevel > 3) {
    std::cerr << "Log level must be 0-3";
    return 1;
  }

  if (!DbFile.length())
    DbFile = "clscope.db";

  CrossReference CrossRef(DbFile);

  if (Query.length() > 0) {
    CrossRef.ListReferences(Query, QueryType, IdType);
  } else {
    // Index
    Index = new Indexer(Path, CrossRef);
    Index->Run();
  }
  return 0;
}
Example #21
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;
}
int main(int argc, char **argv) {
  // Parse the command line arguments
  llvm::cl::ParseCommandLineOptions(argc, argv);

// Read the module file
#if LLVM_VERSION_MAJOR > 3 ||                                                  \
    (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 6)
  std::unique_ptr<llvm::Module> module;
#else
  llvm::Module *module;
#endif

  module = getModuleFromIRFile(BitcodeFilename);
  if (!module) {
    llvm::errs() << "Something is wrong with your bitcode file" << '\n';
    return -1;
  }

  // Get the entry function
  llvm::Function *entry = module->getFunction(EntryFunction);
  if (!entry) {
    llvm::errs() << "Entry function " << EntryFunction << " not found" << '\n';
    return -1;
  }

  if (TargetFunction.empty()) {
    CountInstructions stratDistance;
    FinalReturn stratTarget;
    Dijkstra s(&stratDistance, &stratTarget, &(entry->front().front()));

    llvm::outs() << "Minimal Instruction from " << EntryFunction
                 << " to final return: " << s.searchForMinimalDistance()
                 << '\n';
  } else {
    llvm::Function *target = module->getFunction(TargetFunction);

    if (!target) {
      llvm::errs() << "Target function " << TargetFunction << " not found"
                   << '\n';
      return -1;
    }

    CountDecisions stratDistance;
    CallToSpecificFunction stratTarget(TargetFunction);
    Dijkstra s(&stratDistance, &stratTarget, &(entry->front().front()));

    llvm::outs() << "Minimal Decisions from " << EntryFunction << " to call of "
                 << TargetFunction << ": " << s.searchForMinimalDistance()
                 << '\n';
  }
}
Example #23
0
int main(int argc, char *argv[]) {
  // Setup pretty stack trace printers.
  llvm::PrettyStackTraceProgram X(argc, argv);
  llvm::sys::PrintStackTraceOnErrorSignal();

  // Automatically call llvm_shutdown on exit -- release resources used by
  // ManagedStatic instances.
  llvm::llvm_shutdown_obj Y;

  llvm::cl::ParseCommandLineOptions(argc, argv, "ACSE standalone parser");

  llvm::OwningPtr<llvm::MemoryBuffer> Input;
  llvm::OwningPtr<llvm::tool_output_file> Output;

  llvm::error_code ErrorCode;
  std::string ErrorInfo;

  ErrorCode = llvm::MemoryBuffer::getFileOrSTDIN(InputFileName, Input);
  if(ErrorCode) {
    llvm::errs() << "Error opening input file '" << InputFileName << "'\n";
    return EXIT_FAILURE;
  }

  Output.reset(new llvm::tool_output_file(OutputFileName.c_str(), ErrorInfo));
  if(!ErrorInfo.empty()) {
    llvm::errs() << ErrorInfo << "\n";
    return EXIT_FAILURE;
  }

  llvm::SourceMgr Srcs;
  Srcs.AddNewSourceBuffer(Input.take(), llvm::SMLoc());

  Lexer Lex(Srcs);
  Parser Parse(Lex);

  Parse.Run();

  if(!Parse.Success())
    return EXIT_FAILURE;

  AbstractSyntaxTree *AST = Parse.GetAST();

  if(ViewAST)
    AST->View();
  else
    AST->Dump(Output->os());

  Output->keep();

  return EXIT_SUCCESS;
}
Example #24
0
void CallGraphNode::print(llvm::raw_ostream &OS) const {
  OS << CallGraphFileCheckPrefix << "Function #" << Ordinal << ": " <<
    getFunction()->getName() << "\n";
  OS << CallGraphFileCheckPrefix << "Demangled: " <<
    demangle_wrappers::demangleSymbolAsString(getFunction()->getName()) << "\n";
  printFlag(OS, "Trivially dead", isTriviallyDead());
  printFlag(OS, "All callers known", isCallerEdgesComplete());

  auto &CalleeEdges = getCalleeEdges();
  if (!CalleeEdges.empty()) {
    OS << CallGraphFileCheckPrefix << "Call sites:\n";

    llvm::SmallVector<CallGraphEdge *, 8> OrderedCalleeEdges;
    orderEdges(CalleeEdges, OrderedCalleeEdges);

    for (auto *Edge : OrderedCalleeEdges) {
      OS << "\n";
      Edge->print(OS, /* Indent= */ 2);
    }
    OS << "\n";
  }

  auto &CallerEdges = getCallerEdges();
  if (!CallerEdges.empty()) {
    OS << CallGraphFileCheckPrefix <<
      (!isCallerEdgesComplete() ? "Known " : "");
    OS << "Callers:\n";

    llvm::SmallVector<CallGraphEdge *, 8> OrderedCallerEdges;
    orderEdges(CallerEdges, OrderedCallerEdges);

    llvm::SetVector<SILFunction *> Callers;

    for (auto *Edge : OrderedCallerEdges)
      Callers.insert(Edge->getInstruction()->getFunction());

    for (auto *Caller : Callers) {
      OS << "\n";
      indent(OS, 2);
      OS << CallGraphFileCheckPrefix << "Name: " << Caller->getName() << "\n";
      indent(OS, 2);
      OS << CallGraphFileCheckPrefix << "Demangled: " <<
        demangle_wrappers::demangleSymbolAsString(Caller->getName()) << "\n";
    }
    OS << "\n";
  }

  if (!CallGraphFileCheckPrefix.empty())
    getFunction()->print(OS);
}
Example #25
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;
    }
  }
}
/// \brief Extract the minimum compiler versions as requested on the command
/// line by the switch \c -for-compilers.
///
/// \param ProgName The name of the program, \c argv[0], used to print errors.
/// \param Error If an error occur while parsing the versions this parameter is
/// set to \c true, otherwise it will be left untouched.
static CompilerVersions handleSupportedCompilers(const char *ProgName,
                                                 bool &Error) {
  if (SupportedCompilers.getNumOccurrences() == 0)
    return CompilerVersions();
  CompilerVersions RequiredVersions;
  llvm::SmallVector<llvm::StringRef, 4> Compilers;

  llvm::StringRef(SupportedCompilers).split(Compilers, ",");

  for (llvm::SmallVectorImpl<llvm::StringRef>::iterator I = Compilers.begin(),
                                                        E = Compilers.end();
       I != E; ++I) {
    llvm::StringRef Compiler, VersionStr;
    std::tie(Compiler, VersionStr) = I->split('-');
    Version *V = llvm::StringSwitch<Version *>(Compiler)
        .Case("clang", &RequiredVersions.Clang)
        .Case("gcc", &RequiredVersions.Gcc).Case("icc", &RequiredVersions.Icc)
        .Case("msvc", &RequiredVersions.Msvc).Default(NULL);

    if (V == NULL) {
      llvm::errs() << ProgName << ": " << Compiler
                   << ": unsupported platform\n";
      Error = true;
      continue;
    }
    if (VersionStr.empty()) {
      llvm::errs() << ProgName << ": " << *I
                   << ": missing version number in platform\n";
      Error = true;
      continue;
    }

    Version Version = Version::getFromString(VersionStr);
    if (Version.isNull()) {
      llvm::errs()
          << ProgName << ": " << *I
          << ": invalid version, please use \"<major>[.<minor>]\" instead of \""
          << VersionStr << "\"\n";
      Error = true;
      continue;
    }
    // support the lowest version given
    if (V->isNull() || Version < *V)
      *V = Version;
  }
  return RequiredVersions;
}
Example #27
0
static void addMscrtLibs(std::vector<std::string> &args) {
  llvm::StringRef mscrtlibName = mscrtlib;
  if (mscrtlibName.empty()) {
    // default to static release variant
    mscrtlibName =
        staticFlag || staticFlag.getNumOccurrences() == 0 ? "libcmt" : "msvcrt";
  }

  args.push_back(("/DEFAULTLIB:" + mscrtlibName).str());

  const bool isStatic = mscrtlibName.startswith_lower("libcmt");
  const bool isDebug =
      mscrtlibName.endswith_lower("d") || mscrtlibName.endswith_lower("d.lib");

  const llvm::StringRef prefix = isStatic ? "lib" : "";
  const llvm::StringRef suffix = isDebug ? "d" : "";

  args.push_back(("/DEFAULTLIB:" + prefix + "vcruntime" + suffix).str());
}
Example #28
0
static bool verifyTransformedFiles(ArrayRef<std::string> resultFiles) {
  using namespace llvm;

  assert(!resultFiles.empty());

  std::map<StringRef, StringRef> resultMap;

  for (ArrayRef<std::string>::iterator
         I = resultFiles.begin(), E = resultFiles.end(); I != E; ++I) {
    StringRef fname(*I);
    if (!fname.endswith(".result")) {
      errs() << "error: filename '" << fname
                   << "' does not have '.result' extension\n";
      return true;
    }
    resultMap[sys::path::stem(fname)] = fname;
  }

  ErrorOr<std::unique_ptr<MemoryBuffer>> inputBuf = std::error_code();
  if (RemappingsFile.empty())
    inputBuf = MemoryBuffer::getSTDIN();
  else
    inputBuf = MemoryBuffer::getFile(RemappingsFile);
  if (!inputBuf) {
    errs() << "error: could not read remappings input\n";
    return true;
  }

  SmallVector<StringRef, 8> strs;
  inputBuf.get()->getBuffer().split(strs, "\n", /*MaxSplit=*/-1,
                                    /*KeepEmpty=*/false);

  if (strs.empty()) {
    errs() << "error: no files to verify from stdin\n";
    return true;
  }
  if (strs.size() % 2 != 0) {
    errs() << "error: files to verify are not original/result pairs\n";
    return true;
  }

  for (unsigned i = 0, e = strs.size(); i != e; i += 2) {
    StringRef inputOrigFname = strs[i];
    StringRef inputResultFname = strs[i+1];

    std::map<StringRef, StringRef>::iterator It;
    It = resultMap.find(sys::path::filename(inputOrigFname));
    if (It == resultMap.end()) {
      errs() << "error: '" << inputOrigFname << "' is not in the list of "
             << "transformed files to verify\n";
      return true;
    }

    if (!sys::fs::exists(It->second)) {
      errs() << "error: '" << It->second << "' does not exist\n";
      return true;
    }
    if (!sys::fs::exists(inputResultFname)) {
      errs() << "error: '" << inputResultFname << "' does not exist\n";
      return true;
    }

    if (!filesCompareEqual(It->second, inputResultFname)) {
      errs() << "error: '" << It->second << "' is different than "
             << "'" << inputResultFname << "'\n";
      return true;
    }

    resultMap.erase(It);
  }

  if (!resultMap.empty()) {
    for (std::map<StringRef, StringRef>::iterator
           I = resultMap.begin(), E = resultMap.end(); I != E; ++I)
      errs() << "error: '" << I->second << "' was not verified!\n";
    return true;
  }

  return false; 
}
Example #29
0
int main(int argc, char *argv[]) {
  llvm::cl::SetVersionPrinter(PrintVersion);
  llvm::cl::ParseCommandLineOptions(argc, argv, "CFG to LLVM");


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

  auto context = new llvm::LLVMContext;

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

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

  auto triple = M->getTargetTriple();

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

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

    if (!LiftCodeIntoModule(mod, 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, entry_point_name);
      if (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);
      } else {
        std::cerr << "Could not find entry point: " << entry_point_name
                  << "; aborting" << std::endl;
        return EXIT_FAILURE;
      }
    }

    RenameLiftedFunctions(mod, 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;
}
Example #30
0
static void indent(llvm::raw_ostream &OS, int Indent) {
  if (!CallGraphFileCheckPrefix.empty()) return;

  std::string Blanks(Indent, ' ');
  OS << Blanks;
}