Example #1
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 #2
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 #3
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 #4
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 #5
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);
}
Example #6
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;
}
Example #7
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 #8
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;
}
Example #9
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;
    }
  }
}
Example #10
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);
    }
  }
}
Example #11
0
int main(int argc, char **argv) {
  INITIALIZE_LLVM(argc, argv);

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

  if (PrintStats)
    llvm::EnableStatistics();

  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);
  std::vector<SearchPathOptions::FrameworkSearchPath> FramePaths;
  for (const auto &path : FrameworkPaths) {
    FramePaths.push_back({path, /*isSystem=*/false});
  }
  Invocation.setFrameworkSearchPaths(FramePaths);
  // 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 (!Target.empty())
    Invocation.setTargetTriple(Target);
  if (!ResourceDir.empty())
    Invocation.setRuntimeResourcePath(ResourceDir);
  Invocation.getFrontendOptions().EnableResilience = EnableResilience;
  // Set the module cache path. If not passed in we use the default swift module
  // cache.
  Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;
  Invocation.setParseStdlib();
  Invocation.getLangOptions().DisableAvailabilityChecking = true;
  Invocation.getLangOptions().EnableAccessControl = false;
  Invocation.getLangOptions().EnableObjCAttrRequiresFoundation = false;
  Invocation.getLangOptions().EnableObjCInterop =
    llvm::Triple(Target).isOSDarwin();

  Invocation.getLangOptions().ASTVerifierProcessCount =
      ASTVerifierProcessCount;
  Invocation.getLangOptions().ASTVerifierProcessId =
      ASTVerifierProcessId;
  Invocation.getLangOptions().EnableSILOpaqueValues = EnableSILOpaqueValues;

  // Setup the SIL Options.
  SILOptions &SILOpts = Invocation.getSILOptions();
  SILOpts.InlineThreshold = SILInlineThreshold;
  SILOpts.VerifyAll = EnableSILVerifyAll;
  SILOpts.RemoveRuntimeAsserts = RemoveRuntimeAsserts;
  SILOpts.AssertConfig = AssertConfId;
  if (OptimizationGroup != OptGroup::Diagnostics)
    SILOpts.Optimization = SILOptions::SILOptMode::Optimize;
  SILOpts.EnableSILOwnership = EnableSILOwnershipOpt;
  SILOpts.AssumeUnqualifiedOwnershipWhenParsing =
    AssumeUnqualifiedOwnershipWhenParsing;

  switch (EnforceExclusivity) {
  case EnforceExclusivityMode::Unchecked:
    // This option is analogous to the -Ounchecked optimization setting.
    // It will disable dynamic checking but still diagnose statically.
    SILOpts.EnforceExclusivityStatic = true;
    SILOpts.EnforceExclusivityDynamic = false;
    break;
  case EnforceExclusivityMode::Checked:
    SILOpts.EnforceExclusivityStatic = true;
    SILOpts.EnforceExclusivityDynamic = true;
    break;
  case EnforceExclusivityMode::DynamicOnly:
    // This option is intended for staging purposes. The intent is that
    // it will eventually be removed.
    SILOpts.EnforceExclusivityStatic = false;
    SILOpts.EnforceExclusivityDynamic = true;
    break;
  case EnforceExclusivityMode::None:
    // This option is for staging purposes.
    SILOpts.EnforceExclusivityStatic = false;
    SILOpts.EnforceExclusivityDynamic = false;
    break;
  }

  // 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 {
    const StringRef Name = ModuleName.size() ? StringRef(ModuleName) : "main";
    Invocation.setModuleName(Name);
    Invocation.setInputKind(InputFileKind::IFK_SIL);
  }

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

  if (!PerformWMO) {
    auto &FrontendOpts = Invocation.getFrontendOptions();
    if (!InputFilename.empty() && InputFilename != "-") {
      FrontendOpts.PrimaryInput = SelectedInput(
          FrontendOpts.InputFilenames.size());
    } else {
      FrontendOpts.PrimaryInput = SelectedInput(
          FrontendOpts.InputBuffers.size(), SelectedInput::InputKind::Buffer);
    }
  }

  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(), PerformWMO));
    std::unique_ptr<SerializedSILLoader> SL = SerializedSILLoader::create(
        CI.getASTContext(), CI.getSILModule(), nullptr);

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

  // If we're in verify mode, install a custom diagnostic handling for
  // SourceMgr.
  if (VerifyMode)
    enableDiagnosticVerifier(CI.getSourceMgr());

  if (OptimizationGroup == OptGroup::Diagnostics) {
    runSILDiagnosticPasses(*CI.getSILModule());
  } else if (OptimizationGroup == OptGroup::Performance) {
    runSILOptimizationPasses(*CI.getSILModule());
  } else if (OptimizationGroup == OptGroup::Lowering) {
    runSILLoweringPasses(*CI.getSILModule());
  } else {
    auto *SILMod = CI.getSILModule();
    {
      auto T = irgen::createIRGenModule(SILMod, getGlobalLLVMContext());
      runCommandLineSelectedPasses(SILMod, T.second);
      irgen::deleteIRGenModule(T);
    }
  }

  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);
    }
  }

  bool HadError = CI.getASTContext().hadError();

  // If we're in -verify mode, we've buffered up all of the generated
  // diagnostics.  Check now to ensure that they meet our expectations.
  if (VerifyMode) {
    HadError = verifyDiagnostics(CI.getSourceMgr(), CI.getInputBufferIDs(),
                                 /*autoApplyFixes*/false,
                                 /*ignoreUnknown*/false);
    DiagnosticEngine &diags = CI.getDiags();
    if (diags.hasFatalErrorOccurred() &&
        !Invocation.getDiagnosticOptions().ShowDiagnosticsAfterFatalError) {
      diags.resetHadAnyError();
      diags.diagnose(SourceLoc(), diag::verify_encountered_fatal);
      HadError = true;
    }
  }

  return HadError;
}
Example #12
0
int main(int argc, char **argv) {
  INITIALIZE_LLVM(argc, argv);

  llvm::cl::ParseCommandLineOptions(argc, argv, "Swift LLVM IR Generator\n");

  if (PrintStats)
    llvm::EnableStatistics();

  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);
  Invocation.setFrameworkSearchPaths(FrameworkPaths);
  // 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 (!Target.empty())
    Invocation.setTargetTriple(Target);
  if (!ResourceDir.empty())
    Invocation.setRuntimeResourcePath(ResourceDir);
  // Set the module cache path. If not passed in we use the default swift module
  // cache.
  Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;
  Invocation.setParseStdlib();

  // Setup the language options
  auto &LangOpts = Invocation.getLangOptions();
  LangOpts.DisableAvailabilityChecking = true;
  LangOpts.EnableAccessControl = false;
  LangOpts.EnableObjCAttrRequiresFoundation = false;
  LangOpts.EnableObjCInterop = LangOpts.Target.isOSDarwin();

  // Setup the SIL Options.
  SILOptions &SILOpts = Invocation.getSILOptions();
  SILOpts.AssumeUnqualifiedOwnershipWhenParsing =
      AssumeUnqualifiedOwnershipWhenParsing;

  // Setup the IRGen Options.
  IRGenOptions &Opts = Invocation.getIRGenOptions();
  Opts.MainInputFilename = InputFilename;
  Opts.OutputFilenames.push_back(OutputFilename);
  Opts.OutputKind = OutputKind;

  // 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 {
    const StringRef Name = ModuleName.size() ? StringRef(ModuleName) : "main";
    Invocation.setModuleName(Name);
    Invocation.setInputKind(InputFileKind::IFK_SIL);
  }

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

  if (!PerformWMO) {
    auto &FrontendOpts = Invocation.getFrontendOptions();
    if (!InputFilename.empty() && InputFilename != "-") {
      FrontendOpts.PrimaryInput =
          SelectedInput(FrontendOpts.InputFilenames.size());
    } else {
      FrontendOpts.PrimaryInput = SelectedInput(
          FrontendOpts.InputBuffers.size(), SelectedInput::InputKind::Buffer);
    }
  }

  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(), PerformWMO));
    std::unique_ptr<SerializedSILLoader> SL = SerializedSILLoader::create(
        CI.getASTContext(), CI.getSILModule(), nullptr);

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

  std::unique_ptr<llvm::Module> Mod = performIRGeneration(
      Opts, CI.getMainModule(), CI.takeSILModule(),
      CI.getMainModule()->getName().str(), getGlobalLLVMContext());
  return CI.getASTContext().hadError();
}
Example #13
0
int main(int argc, char** argv) {
  
  llvm::cl::ParseCommandLineOptions(argc, argv, "");
  
  clock_t start,end;
  start = clock();
  
  
  // generate cross reference info
  clang::idx::Program Prog;
  clang::idx::Indexer Idxer(Prog);
  
  
  std::ifstream inf(InputFilename.c_str(), std::ios::in);
  std::cout << InputFilename << " read." <<std::endl;
  std::vector<std::string> lines;
  std::string line;
  
  while(getline(inf, line)) lines.push_back(line);
  
  inf.close();
  std::vector<clang::ASTUnit*> astList;
  
  std::vector<std::string>::iterator itr;
  for(itr=lines.begin();itr!=lines.end();++itr) {
    std::cout << itr->c_str() << std::endl;
    const char* inputs[] = {argv[0],itr->c_str()};
    llvm::OwningPtr<clang::ASTUnit>  ast(generateASTUnitFromSource(inputs));
    astList.push_back(ast.take());
  }

  std::cout <<  "loaded TU size: " << astList.size() << std::endl;
  for (unsigned i = 0, e = astList.size(); i != e; ++i) {
    std::cout <<  "load astList[" << i << "]" ;
    std::cout.flush();
    
    ASTUnitTU *TU = new ASTUnitTU(astList[i]);
    Idxer.IndexAST(TU);
    std::cout <<  "... OK!" << std::endl;
  }
  
  clang::idx::Analyzer* analyzer = new clang::idx::Analyzer(Idxer.getProgram(),Idxer);

  // get Entity  
  clang::idx::Entity Ent =
  	clang::idx::Entity::get("a", Idxer.getProgram());
  std::cout << Ent.getPrintableName() << std::endl;
  
  //clang::FunctionDecl *FD;
  for (unsigned i = 0, e = astList.size(); i != e; ++i) {
    auto decl = Ent.getDecl(astList[i]->getASTContext());
    if (decl) {
      std::cout << "found!" << std::endl;
      Handler* handler = new Handler();
      analyzer->FindReferences(decl,*handler);
      return 0;
    }
  }
  
  //clang::idx::TranslationUnit *TU;
  //llvm::tie(FD, TU) = Idxer.getDefinitionFor(Ent);
  
  
  
  
  end = clock();
  printf("%.2f second spend.\n",(double)(end-start)/CLOCKS_PER_SEC);
  
  return 0;
}
Example #14
0
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;
}
Example #15
0
int main(int argc, char **argv) {
    llvm::llvm_shutdown_obj shutdown;  // calls llvm_shutdown() on exit
    llvm::cl::ParseCommandLineOptions(argc, argv, "llvm2bpl - LLVM bitcode to Boogie transformation\n");

    llvm::sys::PrintStackTraceOnErrorSignal();
    llvm::PrettyStackTraceProgram PSTP(argc, argv);
    llvm::EnableDebugBuffering = true;

    llvm::SMDiagnostic err;
    std::unique_ptr<llvm::Module> module = llvm::parseIRFile(InputFilename, err, llvm::getGlobalContext());
    if (!err.getMessage().empty())
        check("Problem reading input bitcode/IR: " + err.getMessage().str());

    auto &L = module.get()->getDataLayoutStr();
    if (L.empty())
        module.get()->setDataLayout(DefaultDataLayout);

    ///////////////////////////////
    // initialise and run passes //
    ///////////////////////////////

    llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
    llvm::initializeAnalysis(Registry);

    llvm::legacy::PassManager pass_manager;

    pass_manager.add(llvm::createLowerSwitchPass());
    //pass_manager.add(llvm::createCFGSimplificationPass());
    pass_manager.add(llvm::createInternalizePass());
    pass_manager.add(llvm::createPromoteMemoryToRegisterPass());

    if (StaticUnroll) {
        pass_manager.add(llvm::createLoopSimplifyPass());
        pass_manager.add(llvm::createLoopRotatePass());
        //pass_manager.add(llvm::createIndVarSimplifyPass());
        pass_manager.add(llvm::createLoopUnrollPass(32767));
    }

    pass_manager.add(new llvm::StructRet());
    pass_manager.add(new llvm::SimplifyEV());
    pass_manager.add(new llvm::SimplifyIV());
    pass_manager.add(new smack::ExtractContracts());
    pass_manager.add(llvm::createDeadCodeEliminationPass());
    pass_manager.add(new smack::CodifyStaticInits());
    pass_manager.add(new smack::RemoveDeadDefs());
    pass_manager.add(new llvm::MergeArrayGEP());
    // pass_manager.add(new smack::SimplifyLibCalls());
    pass_manager.add(new llvm::Devirtualize());

    if (smack::SmackOptions::MemorySafety) {
        pass_manager.add(new smack::MemorySafetyChecker());
    }

    if (SignedIntegerOverflow)
        pass_manager.add(new smack::SignedIntegerOverflowChecker());

    std::vector<tool_output_file*> files;

    if (!FinalIrFilename.empty()) {
        std::error_code EC;
        auto F = new tool_output_file(FinalIrFilename.c_str(), EC, sys::fs::F_None);
        if (EC) check(EC.message());
        F->keep();
        files.push_back(F);
        pass_manager.add(llvm::createPrintModulePass(F->os()));
    }

    if (!OutputFilename.empty()) {
        std::error_code EC;
        auto F = new tool_output_file(OutputFilename.c_str(), EC, sys::fs::F_None);
        if (EC) check(EC.message());
        F->keep();
        files.push_back(F);
        pass_manager.add(new smack::SmackModuleGenerator());
        pass_manager.add(new smack::BplFilePrinter(F->os()));
    }

    pass_manager.run(*module.get());

    for (auto F : files)
        delete F;

    return 0;
}
int main(int argc, char** argv) {
  Galois::StatManager statManager;
  LonestarStart(argc, argv, name, desc, url);

  graph = new Graph();
  {
    Mesh m;
    m.read(graph, filename.c_str(), detAlgo == nondet);
    Verifier v;
    if (!skipVerify && !v.verify(graph)) {
      std::cerr << "bad input mesh\n";
      assert(0 && "Refinement failed");
      abort();
    }
  }

  std::cout << "configuration: " << std::distance(graph->begin(), graph->end())
	    << " total triangles, " << std::count_if(graph->begin(), graph->end(), is_bad(graph)) << " bad triangles\n";

  Galois::Statistic("MeminfoPre1", GaloisRuntime::MM::pageAllocInfo());
  Galois::preAlloc(15 * numThreads + GaloisRuntime::MM::pageAllocInfo() * 10);
  Galois::Statistic("MeminfoPre2", GaloisRuntime::MM::pageAllocInfo());

  Galois::StatTimer T;
  T.start();

  if (detAlgo == nondet)
    Galois::do_all_local(*graph, Preprocess());
  else
    std::for_each(graph->begin(), graph->end(), Preprocess());

  Galois::Statistic("MeminfoMid", GaloisRuntime::MM::pageAllocInfo());
  
  Galois::StatTimer Trefine("refine");
  Trefine.start();
  using namespace GaloisRuntime::WorkList;
  
  typedef LocalQueues<dChunkedLIFO<256>, ChunkedLIFO<256> > BQ;
  typedef ChunkedAdaptor<false,32> CA;
  
  switch (detAlgo) {
    case nondet: 
      Galois::for_each_local<CA>(wl, Process<>()); break;
    case detBase:
      Galois::for_each_det(wl.begin(), wl.end(), Process<>()); break;
    case detPrefix:
      Galois::for_each_det(wl.begin(), wl.end(), Process<detPrefix>(), Process<>());
      break;
    case detDisjoint:
      Galois::for_each_det(wl.begin(), wl.end(), Process<detDisjoint>()); break;
    default: std::cerr << "Unknown algorithm" << detAlgo << "\n"; abort();
  }
  Trefine.stop();
  T.stop();
  
  Galois::Statistic("MeminfoPost", GaloisRuntime::MM::pageAllocInfo());
  
  if (!skipVerify) {
    int size = Galois::ParallelSTL::count_if(graph->begin(), graph->end(), is_bad(graph));
    if (size != 0) {
      std::cerr << size << " bad triangles remaining.\n";
      assert(0 && "Refinement failed");
      abort();
    }
    Verifier v;
    if (!v.verify(graph)) {
      std::cerr << "Refinement failed.\n";
      assert(0 && "Refinement failed");
      abort();
    }
    std::cout << "Refinement OK\n";
  }

  return 0;
}
Example #17
0
// generate ASTUnit from source file.
clang::ASTUnit* generateASTUnitFromSource(const char** argv) {
	clang::CompilerInstance compiler;

	// Setup Diagnostic Options
	clang::DiagnosticOptions diagOpts;
	diagOpts.ErrorLimit = 60000;
	diagOpts.IgnoreWarnings = 1;
	diagOpts.TabStop = clang::DiagnosticOptions::DefaultTabStop;
	diagOpts.MessageLength = 0;
	diagOpts.NoRewriteMacros = 0;
	diagOpts.Pedantic = 0;
	diagOpts.PedanticErrors = 0;
	diagOpts.ShowCarets = 1;
	diagOpts.ShowColors = 0;
	diagOpts.ShowOverloads = clang::DiagnosticsEngine::Ovl_All;
	diagOpts.ShowColumn = 1;
	diagOpts.ShowFixits = 1;
	diagOpts.ShowLocation = 1;
	diagOpts.ShowOptionNames = 0;
	diagOpts.ShowCategories = 0;
	diagOpts.ShowSourceRanges = 0;
	diagOpts.ShowParseableFixits = 0;
	diagOpts.VerifyDiagnostics = 0;
	diagOpts.TemplateBacktraceLimit = clang::DiagnosticOptions::DefaultTemplateBacktraceLimit;
	diagOpts.MacroBacktraceLimit = clang::DiagnosticOptions::DefaultMacroBacktraceLimit;

	auto ignoreConsumer = new clang::IgnoringDiagConsumer();
	auto diagnosticEngine = compiler.createDiagnostics(diagOpts,2,argv,ignoreConsumer);

	compiler.setDiagnostics(diagnosticEngine.getPtr());
	//compiler.setDiagnostics(compiler.createDiagnostics(diagOpts,argc, argv));

	auto& diag = compiler.getDiagnostics();
	auto& invocation = compiler.getInvocation();

	// setup language options
	clang::LangOptions langOpts;
	langOpts.NoInline = 0;
	//langOpts.BCPLComment = true;
	langOpts.Bool   = true;
	//langOpts.MicrosoftExt = true;
	//langOpts.MicrosoftMode = true;
	langOpts.CPlusPlus  = true;
	langOpts.CPlusPlus0x = true;
	langOpts.Exceptions  = true;
	langOpts.CXXExceptions = true;
	langOpts.MSBitfields = true;
	langOpts.NeXTRuntime = false;
	langOpts.NoBuiltin  = true;
	langOpts.CatchUndefined = true;
	langOpts.EmitAllDecls = true;
	//langOpts.MSCVersion  = _MSC_VER;
	invocation.setLangDefaults(langOpts,clang::IK_C);
        
	auto depOpts = invocation.getDependencyOutputOpts();
	depOpts.UsePhonyTargets = 1;
        
	clang::CompilerInvocation::CreateFromArgs(invocation, 
                                                  argv + 1,
                                                  argv + 2,
                                                  diag);

	compiler.setTarget(clang::TargetInfo::CreateTargetInfo(diag,
                                                               compiler.getTargetOpts()));
	compiler.createFileManager();
	compiler.createSourceManager(compiler.getFileManager());
        
        std::ifstream inf(IncludeFilename.c_str(), std::ios::in);
	std::vector<std::string> lines;
	std::string line;
	while(getline(inf, line)) lines.push_back(line);
	inf.close();
        
	std::vector<std::string>::iterator itr;
	for(itr=lines.begin();itr!=lines.end();++itr) {

          compiler.getHeaderSearchOpts().AddPath(itr->c_str(),
          clang::frontend::Quoted, true, false, false);
          compiler.getHeaderSearchOpts().AddPath(itr->c_str(),
                                                 clang::frontend::Angled, true, false, false);
          std::cout <<  "Include:"  << itr->c_str() << std::endl;
        }
	compiler.createPreprocessor();
        compiler.createASTContext();
	compiler.setASTConsumer(new MyASTConsumer());

	compiler.createSema(clang::TU_Complete, nullptr);
        std::cout << "parse start" << std::endl;
        // To Parse C Source file from ARG
	auto& inputs = compiler.getFrontendOpts().Inputs;
	if (inputs.size() > 0) {
          compiler.InitializeSourceManager(inputs[0].second);
          clang::ParseAST(
              compiler.getPreprocessor(),
              &compiler.getASTConsumer(),
              compiler.getASTContext()
                          );
	}
        std::cout << "parse end" << std::endl;
        std::cout << "generate ASTUnit" << std::endl;
        auto astUnit = clang::ASTUnit::LoadFromCompilerInvocation(&invocation,
                                                   llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine>(&diag));
        std::cout << "generate ASTUnit end" << std::endl;
	return astUnit;
}
Example #18
0
int main(int argc, char **argv) {
  llvm::llvm_shutdown_obj shutdown;  // calls llvm_shutdown() on exit
  llvm::cl::ParseCommandLineOptions(argc, argv, "SMACK - LLVM bitcode to Boogie transformation\n");

  llvm::sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram PSTP(argc, argv);
  llvm::EnableDebugBuffering = true;

  if (OutputFilename.empty()) {
//    OutputFilename = getFileName(InputFilename) + ".bpl";
    OutputFilename = "a.bpl";
  }
 
  std::string error_msg;
  llvm::SMDiagnostic err;
  llvm::LLVMContext &context = llvm::getGlobalContext();  
  std::unique_ptr<llvm::Module> module;
  std::unique_ptr<llvm::tool_output_file> output;
 
  module.reset(llvm::ParseIRFile(InputFilename, err, context));
  if (module.get() == 0) {
    if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED);
    llvm::errs() << "error: " << "Bitcode was not properly read; " << err.getMessage() << "\n";
    if (llvm::errs().has_colors()) llvm::errs().resetColor();
    return 1;
  }
 
  output.reset(new llvm::tool_output_file(OutputFilename.c_str(), error_msg, llvm::sys::fs::F_None));
  if (!error_msg.empty()) {
    if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED);
    llvm::errs() << "error: " << error_msg << "\n";
    if (llvm::errs().has_colors()) llvm::errs().resetColor();
    return 1;
  }
 
  ///////////////////////////////
  // initialise and run passes //
  ///////////////////////////////

  llvm::PassManager pass_manager;
  llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
  llvm::initializeAnalysis(Registry);
 
  // add an appropriate DataLayout instance for the module
  const llvm::DataLayout *dl = 0;
  const std::string &moduleDataLayout = module.get()->getDataLayoutStr();
  if (!moduleDataLayout.empty())
    dl = new llvm::DataLayout(moduleDataLayout);
  else if (!DefaultDataLayout.empty())
    dl = new llvm::DataLayout(moduleDataLayout);
  if (dl) pass_manager.add(new llvm::DataLayoutPass(*dl));

  pass_manager.add(llvm::createLowerSwitchPass());
  pass_manager.add(llvm::createCFGSimplificationPass());
  pass_manager.add(llvm::createInternalizePass());
  pass_manager.add(llvm::createPromoteMemoryToRegisterPass());
  pass_manager.add(new llvm::StructRet());
  pass_manager.add(new llvm::SimplifyEV());
  pass_manager.add(new llvm::SimplifyIV());
  pass_manager.add(new smack::SmackModuleGenerator());
  pass_manager.add(new smack::BplFilePrinter(output->os()));
  pass_manager.run(*module.get());

  output->keep();

  return 0;
}
Example #19
0
int main(int argc, char **argv) {
  llvm::llvm_shutdown_obj shutdown;  // calls llvm_shutdown() on exit
  llvm::cl::ParseCommandLineOptions(argc, argv, "llvm2bpl - LLVM bitcode to Boogie transformation\n");

  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
  llvm::PrettyStackTraceProgram PSTP(argc, argv);
  llvm::EnableDebugBuffering = true;

  llvm::SMDiagnostic err;
  llvm::LLVMContext Context;

  InitializeAllTargets();
  InitializeAllTargetMCs();
  InitializeAllAsmPrinters();
  InitializeAllAsmParsers();

  std::unique_ptr<llvm::Module> module = llvm::parseIRFile(InputFilename, err, Context);
  if (!err.getMessage().empty())
    check("Problem reading input bitcode/IR: " + err.getMessage().str());

  auto &L = module.get()->getDataLayoutStr();
  if (L.empty())
    module.get()->setDataLayout(DefaultDataLayout);

  ///////////////////////////////
  // initialise and run passes //
  ///////////////////////////////

  llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
  llvm::initializeAnalysis(Registry);

  llvm::legacy::PassManager pass_manager;

  pass_manager.add(llvm::createLowerSwitchPass());
  //pass_manager.add(llvm::createCFGSimplificationPass());
  pass_manager.add(llvm::createInternalizePass());
  pass_manager.add(llvm::createPromoteMemoryToRegisterPass());

  if (StaticUnroll) {
    pass_manager.add(llvm::createLoopSimplifyPass());
    pass_manager.add(llvm::createLoopRotatePass());
    //pass_manager.add(llvm::createIndVarSimplifyPass());
    pass_manager.add(llvm::createLoopUnrollPass(32767));
  }

  pass_manager.add(new llvm::StructRet());
  pass_manager.add(new llvm::SimplifyEV());
  pass_manager.add(new llvm::SimplifyIV());
  pass_manager.add(new smack::ExtractContracts());
  pass_manager.add(new smack::VerifierCodeMetadata());
  pass_manager.add(llvm::createDeadCodeEliminationPass());
  pass_manager.add(new smack::CodifyStaticInits());
  if (!Modular) {
    pass_manager.add(new smack::RemoveDeadDefs());
  }
  pass_manager.add(new llvm::MergeArrayGEP());
  // pass_manager.add(new smack::SimplifyLibCalls());
  pass_manager.add(new llvm::Devirtualize());

  if (SplitStructs)
    pass_manager.add(new smack::SplitAggregateLoadStore());

  if (smack::SmackOptions::MemorySafety) {
    pass_manager.add(new smack::MemorySafetyChecker());
  }

  if (SignedIntegerOverflow)
    pass_manager.add(new smack::SignedIntegerOverflowChecker());


  if(smack::SmackOptions::AddTiming){
    Triple ModuleTriple(module->getTargetTriple());
    assert (ModuleTriple.getArch() && "Module has no defined architecture: unable to add timing annotations");

    const TargetOptions Options; /* = InitTargetOptionsFromCodeGenFlags();*/
    std::string CPUStr = ""; /*getCPUStr();*/
    std::string FeaturesStr = ""; /*getFeaturesStr();*/
    TargetMachine *Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);

    assert(Machine && "Module did not have a Target Machine: Cannot set up timing pass");
    // Add an appropriate TargetLibraryInfo pass for the module's triple.
    TargetLibraryInfoImpl TLII(ModuleTriple);
    pass_manager.add(new TargetLibraryInfoWrapperPass(TLII));

    // Add internal analysis passes from the target machine.
    pass_manager.add(createTargetTransformInfoWrapperPass(Machine->getTargetIRAnalysis()));
    pass_manager.add(new smack::AddTiming());
  }

  std::vector<tool_output_file*> files;

  if (!FinalIrFilename.empty()) {
    std::error_code EC;
    auto F = new tool_output_file(FinalIrFilename.c_str(), EC, sys::fs::F_None);
    if (EC) check(EC.message());
    F->keep();
    files.push_back(F);
    pass_manager.add(llvm::createPrintModulePass(F->os()));
  }

  if (!OutputFilename.empty()) {
    std::error_code EC;
    auto F = new tool_output_file(OutputFilename.c_str(), EC, sys::fs::F_None);
    if (EC) check(EC.message());
    F->keep();
    files.push_back(F);
    pass_manager.add(new smack::SmackModuleGenerator());
    pass_manager.add(new smack::BplFilePrinter(F->os()));
  }

  pass_manager.run(*module.get());

  for (auto F : files)
    delete F;

  return 0;
}
int main(int argc, char** argv) {
    Galois::StatManager M;
    LonestarStart(argc, argv, name, desc, url);

    Graph g;
    G = &g;

    G->structureFromFile(filename.c_str());

    NumNodes = G->size();

#if SHARE_SINGLE_BC
    std::vector<cache_line_storage<BCrecord> > cb(NumNodes);
    CB = &cb;
#else
    Galois::GVectorElementAccumulator<std::vector<double> > cb;
    CB = &cb;
#endif

    initGraphData();

    int iterations = NumNodes;
    if (iterLimit)
        iterations = iterLimit;

    boost::filter_iterator<HasOut,Graph::iterator>
    begin = boost::make_filter_iterator(HasOut(G), g.begin(), g.end()),
    end = boost::make_filter_iterator(HasOut(G), g.end(), g.end());

    iterations = std::min((int) std::distance(begin, end), iterations);

    std::cout
            << "NumNodes: " << NumNodes
            << " Iterations: " << iterations << "\n";

    end = begin;
    std::advance(end, iterations);
    std::vector<GNode> tmp;
    std::copy(begin, end, std::back_inserter(tmp));

    typedef GaloisRuntime::WorkList::dChunkedLIFO<1> WL;
    Galois::StatTimer T;
    T.start();
    Galois::for_each<WL>(tmp.begin(), tmp.end(), process());
    T.stop();

    if (forceVerify || !skipVerify) {
        verify();
    } else { // print bc value for first 10 nodes
#if SHARE_SINGLE_BC
#else
        const std::vector<double>& bcv = CB->reduce();
#endif
        for (int i=0; i<10; ++i)
#if SHARE_SINGLE_BC
            std::cout << i << ": " << setiosflags(std::ios::fixed) << std::setprecision(6) << (*CB)[i].data.bc << "\n";
#else
            std::cout << i << ": " << setiosflags(std::ios::fixed) << std::setprecision(6) << bcv[i] << "\n";
#endif
#if SHOULD_PRODUCE_CERTIFICATE
        printBCcertificate();
#endif
    }
    std::cerr << "Application done...\n";

    Galois::StatTimer tt("cleanup");
    tt.start();
    cleanupData();
    tt.stop();

    return 0;
}
Example #21
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 #22
0
int main(int argc, char** argv) {
  Galois::StatManager statManager;
  LonestarStart(argc, argv, name, desc, url);

  Galois::StatTimer Tinitial("InitializeTime");
  Tinitial.start();

  // Load filled graph with edge data
  Galois::Graph::readGraph(graph, inputFilename.c_str());
  std::cout << "Num nodes: " << graph.size() << "\n";

  // Assign IDs to each node
  {
    unsigned int n = graph.size(), i = 0;
    for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) {
      Node& data = graph.getData(*ii);
      data.id = i++;
      assert(!data.seen);
    }
    assert(i == n);

    // Load dependence ordering
    depgraph = new DepItem[n];
    assert(depgraph);
    std::ifstream depfile(depFilename.c_str());
    i = 0;
    while (depfile) {
      unsigned int node;
      depfile >> node;
      if ( !depfile ) break;
      assert(node < n);
      if ( i < 0 || i >= n ) {
        std::cout << "Error loading dependencies.\n";
        abort();
      }
      depgraph[i] = node;
      i++;
    }
    assert(i == n);
    depfile.close();
  }

  Tinitial.stop();

  //Galois::preAlloc(numThreads);
  Galois::reportPageAlloc("MeminfoPre");

  switch (algo) {
    case demo: run<DemoAlgo>(); break;
    //case asynchronous: run<AsynchronousAlgo>(); break;
    default: std::cerr << "Unknown algo: " << algo << "\n";
  }
  Galois::reportPageAlloc("MeminfoPost");

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

  return 0;
}