Ejemplo n.º 1
0
InternalizePass::InternalizePass(bool AllButMain)
  : ModulePass(ID), AllButMain(AllButMain){
  initializeInternalizePassPass(*PassRegistry::getPassRegistry());
  if (!APIFile.empty())           // If a filename is specified, use it.
    LoadFile(APIFile.c_str());
  if (!APIList.empty())           // If a list is specified, use it as well.
    ExternalNames.insert(APIList.begin(), APIList.end());
}
Ejemplo n.º 2
0
Archivo: main.cpp Proyecto: mleise/ldc
// Helper function to handle -of, -od, etc.
static void initFromString(const char*& dest, const cl::opt<std::string>& src) {
    dest = 0;
    if (src.getNumOccurrences() != 0) {
        if (src.empty())
            error(Loc(), "Expected argument to '-%s'", src.ArgStr);
        dest = mem.xstrdup(src.c_str());
    }
}
Ejemplo n.º 3
0
InternalizePass::InternalizePass()
  : ModulePass(ID) {
  initializeInternalizePassPass(*PassRegistry::getPassRegistry());
  if (!APIFile.empty())           // If a filename is specified, use it.
    LoadFile(APIFile.c_str());
  ExternalNames.insert(APIList.begin(), APIList.end());
  DSONames.insert(DSOList.begin(), DSOList.end());
}
Ejemplo n.º 4
0
    virtual bool
    runOnModule(Module& M)
    {
      AliasAnalysis& aa = this->getAnalysis<AliasAnalysis>();
      bool checked = false;

      errs() <<  "GatherInterfacePass::runOnModule: " << M.getModuleIdentifier() << "\n";
      
      if (!GatherInterfaceMain.empty()) {
        checked = true;
        for (cl::list<std::string>::const_iterator i = GatherInterfaceMain.begin(), e = GatherInterfaceMain.end();
            i != e; ++i) {
          Function* f = M.getFunction(*i);
          if (f == NULL) {
            errs() << "Function '" << *i << "' not found, skipping\n";
            continue;
          }
          if (f->isDeclaration()) {
            errs() << "Function '" << *i << "' is declaration, skipping\n";
            continue;
          }
          errs() << "Gathering from: " << *f << "\n";
          GatherInterface(*f, this->interface, &aa);
        }
      }
      if (!GatherInterfaceEntry.empty()) {
        checked = true;
        ComponentInterface ci;
        for (cl::list<std::string>::const_iterator i = GatherInterfaceEntry.begin(), e = GatherInterfaceEntry.end();
              i != e; ++i) {
          errs() << "Reading interface from '" << *i << "'...";
          if (ci.readFromFile(*i)) {
            errs() << "success\n";
          } else {
            errs() << "failed\n";
            continue;
          }
        }
        for (ComponentInterface::FunctionIterator i = ci.begin(), e = ci.end(); i != e; ++i) {
          Function* f = M.getFunction(i->first());
          if (f == NULL) continue;
          if (!GatherInterface(*f, this->interface, &aa)) break;
        }
      }
      if (!checked) {
        GatherInterface(M, this->interface, &aa);
      }

      if (GatherInterfaceOutput != "") {
        proto::ComponentInterface ci;
        codeInto<ComponentInterface, proto::ComponentInterface> (
            this->interface, ci);
        std::ofstream output(GatherInterfaceOutput.c_str(), std::ios::binary);
        assert(ci.SerializeToOstream(&output));
        output.close();
      }
      return false;
    }
Ejemplo n.º 5
0
// search for a BlockString with a name of "hsa_dwarf_debug", this marks
// the beginning of a group of BlockNumerics which make up the elf container
//
// Input: any directive inside the debug section
//        the debug section
// Returns: the directive following the matching BlockString (the beginning of
//          the BlockNumerics), or the end directive of the section if no
//          matching BlockString is found
//
static void DumpDebugInfoToFile( BrigContainer & c )
{
    std::ofstream ofs( (const char*)(DebugInfoFilename.c_str()), std::ofstream::binary );
    if ( ! ofs.is_open() || ofs.bad() )
        std::cout << "Could not create output debug info file " << DebugInfoFilename << ", not dumping debug info\n";
    else {
      SRef data = c.debugInfo().payload();
      ofs.write(data.begin, data.length());
    }
}
Ejemplo n.º 6
0
bool EnforcingLandmarks::runOnModule(Module &M) {
	if (EnforcingLandmarksFile == "") {
		const static size_t len = sizeof(DEFAULT_ENFORCING_LANDMARK_FUNCS) /
			sizeof(const char *[2]);
		for (size_t i = 0; i < len; ++i) {
			string func_name = DEFAULT_ENFORCING_LANDMARK_FUNCS[i][0];
			string is_blocking = DEFAULT_ENFORCING_LANDMARK_FUNCS[i][1];
			insert_enforcing_landmark_func(func_name, is_blocking);
		}
	} else {
		ifstream fin(EnforcingLandmarksFile.c_str());
		string func_name, is_blocking;
		while (fin >> func_name >> is_blocking)
			insert_enforcing_landmark_func(func_name, is_blocking);
	}

	// Mark any function call to landmark functions as enforcing landmarks. 
	for (Module::iterator f = M.begin(); f != M.end(); ++f) {
		if (f->getName() == "MyMalloc")
			continue;
		if (f->getName() == "MyFree")
			continue;
		if (f->getName() == "MyFreeNow")
			continue;
		if (f->getName() == "maketree")
			continue;
		for (Function::iterator bb = f->begin(); bb != f->end(); ++bb) {
			for (BasicBlock::iterator ins = bb->begin(); ins != bb->end(); ++ins) {
				CallSite cs(ins);
				if (cs.getInstruction()) {
					if (Function *callee = cs.getCalledFunction()) {
						StringRef callee_name = callee->getName();
						if (enforcing_landmark_funcs.count(callee_name)) {
							if (OnlyMain && callee_name != "pthread_self" &&
									f->getName() != "main")
								continue;
							if (callee_name.startswith("pthread_mutex")
									|| callee_name.startswith("pthread_cond")
									|| callee_name.startswith("pthread_barrier")
									|| callee_name.startswith("pthread_rwlock")
									|| callee_name.startswith("pthread_spin")) {
								if (rand() % 100 < PruningRate)
									continue;
							}
							enforcing_landmarks.insert(ins);
						}
					}
				}
			}
		}
	}

	return false;
}
Ejemplo n.º 7
0
int main(int argc, char **argv) {

  cl::ParseCommandLineOptions(argc, argv,
			      " llvm .bc -> .bc modular optimizer\n");

  // Load the input module...
  std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));


    if (M.get() == 0) {
    cerr << "bytecode didn't read correctly.\n";
    return 1;
  }

  // Figure out what stream we are supposed to write to...

  std::ostream *Out = &std::cout;  // Default to printing to stdout...


  if (OutputFilename != "") {
    Out = new std::ofstream(OutputFilename.c_str());
    

    if (!Out->good()) {
      cerr << "Error opening " << OutputFilename << "!\n";
      return 1;
    }
    
  }
    
    
  //
  PassManager Passes;
  Passes.add(new DataLayout("embec", M.get()));
  
  //Add passes
  Passes.add(createCZeroUninitPtrPass());
  /*
  Passes.add(createABCPreProcessPass());
  Passes.add(createArrayBoundsCheckPass());
  Passes.add(createStackSafetyPass());
  */
  Passes.add(createEmbeCFreeRemovalPass());
 
  // Now that we have all of the passes ready, run them.
  if (Passes.run(*M.get()))
    cerr << "Program modified.\n";
  (*Out) << M.get();
  //  WriteToC(M.get(), *Out, false);

  return 0;
}
static void readNames(std::set<std::string>& names) {
  std::ifstream msf(epaFile.c_str(), std::ifstream::in);
  if (!msf.good())
    errs() << "Failed to open file: " << epaFile << " (continuing anyway)\n";
  while (msf.good()) {
    std::string n;
    msf >> n;
    if (n.size()) {
      names.insert(n);
//      errs() << "Read " << n << "\n";
    }
  }
}
Ejemplo n.º 9
0
int main(int argc, char **argv) {
    cl::ParseCommandLineOptions(argc, argv, "LLJVM Backend\n");
    std::string err;
    
    MemoryBuffer *buf = MemoryBuffer::getFileOrSTDIN(input, &err);
    if(!buf) {
        std::cerr << "Unable to open bitcode file: " << err << std::endl;
        return 1;
    }
    
    Module *mod = ParseBitcodeFile(buf, getGlobalContext(), &err);
    if(!mod) {
        std::cerr << "Unable to parse bitcode file: " << err << std::endl;
        return 1;
    }

    llvm::raw_fd_ostream *trace_stream(0);
    if (!tracefile.empty()) {
        if (debugLevel < 3) {
            std::cerr << "May only specify a trace file if generating -g3 debugging information" << std::endl;
            return 1;
        }
        err = "";
        trace_stream = new llvm::raw_fd_ostream(tracefile.c_str(), err);
        if (!err.empty()) {
            std::cerr << "Unable to open tracefile " << tracefile << " : " << err << std::endl;
            return 1;
        }
    }

    
    PassManager pm;
    TargetData td("e-p:32:32:32"
                  "-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64"
                  "-f32:32:32-f64:64:64");
    pm.add(new TargetData(td));
    pm.add(createVerifierPass());
    pm.add(createGCLoweringPass());
    // TODO: fix switch generation so the following pass is not needed
    pm.add(createLowerSwitchPass());
    pm.add(createIndVarSimplifyPass());
    pm.add(createPromoteMemoryToRegisterPass());  //good
    pm.add(createDeadStoreEliminationPass());
    pm.add(createAggressiveDCEPass());
    pm.add(createCFGSimplificationPass());
    pm.add(new JVMWriter(&td, fouts(), classname
            , sourcename, debugLevel, trace_stream));
    pm.add(createGCInfoDeleter());
    pm.run(*mod);
    return 0;
}
Ejemplo n.º 10
0
int main(int argc, char * argv[]) {
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
  LLVMContext &Context = getGlobalContext();
  
  cl::ParseCommandLineOptions(argc, argv, "Anteater compiler\n");

  SMDiagnostic Err;

  // Load the input module...
  std::auto_ptr<Module> M;
  M.reset(ParseIRFile(InputFilename, Err, Context));

  if (M.get() == 0) {
    Err.Print(argv[0], errs());
    return 1;
  }

  // Figure out what stream we are supposed to write to...
  // FIXME: outs() is not binary!
  raw_ostream *Out = &outs();  // Default to printing to stdout...
  if (OutputFilename != "-") {
    std::string ErrorInfo;
    Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
                               raw_fd_ostream::F_Binary);
    if (!ErrorInfo.empty()) {
      errs() << ErrorInfo << '\n';
      delete Out;
      return 1;
    }
  }

  PassManager Passes;
  if (Backend == "yices") {
    Passes.add(anteater::createXorEliminationPass(&Context));
    Passes.add(anteater::createAnteaterInstructionNamerPass());
    Passes.add(anteater::createYicesWriter(Out));
    
  } else {
    Passes.add(anteater::createAnteaterInstructionNamerPass());
    Passes.add(anteater::createSMT12Writer(Out));    
  }
  Passes.run(*M.get());


  // Delete the raw_fd_ostream.
  if (Out != &outs())
    delete Out;
  
  return 0;
}
Ejemplo n.º 11
0
//===----------------------------------------------------------------------===//
int main(int argc, char **argv) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  cl::ParseCommandLineOptions(argc, argv, "llvm coverage tool\n");

  std::string ErrorInfo;
  raw_fd_ostream OS(OutputFile.c_str(), ErrorInfo);
  if (!ErrorInfo.empty())
    errs() << ErrorInfo << "\n";

  GCOVFile GF;
  if (InputGCNO.empty())
    errs() << " " << argv[0] << ": No gcov input file!\n";

  OwningPtr<MemoryBuffer> GCNO_Buff;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCNO, GCNO_Buff)) {
    errs() << InputGCNO << ": " << ec.message() << "\n";
    return 1;
  }
  GCOVBuffer GCNO_GB(GCNO_Buff.get());
  if (!GF.read(GCNO_GB)) {
    errs() << "Invalid .gcno File!\n";
    return 1;
  }

  if (!InputGCDA.empty()) {
    OwningPtr<MemoryBuffer> GCDA_Buff;
    if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCDA, GCDA_Buff)) {
      errs() << InputGCDA << ": " << ec.message() << "\n";
      return 1;
    }
    GCOVBuffer GCDA_GB(GCDA_Buff.get());
    if (!GF.read(GCDA_GB)) {
      errs() << "Invalid .gcda File!\n";
      return 1;
    }
  }


  if (DumpGCOV)
    GF.dump();

  FileInfo FI;
  GF.collectLineCounts(FI);
  FI.print(OS, InputGCNO, InputGCDA);
  return 0;
}
int main(int argc, char ** argv)
{
	unsigned char * bytes;
	unsigned byte_count;

	std::auto_ptr<Module> M;
	LLVMContext &Context = getGlobalContext();
	SMDiagnostic Err;
	cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
	M.reset(ParseIRFile(InputFilename, Err, Context));

	Module * mod = M.get();
  
	radeon_llvm_compile(wrap(mod), &bytes, &byte_count, TargetGPUName.c_str(), 1);
}
Ejemplo n.º 13
0
bool PointToDrawer::runOnModule(Module &M) {
  PointerAnalysis &PA = getAnalysis<PointerAnalysis>();

  if (DotFileName != "") {
    string ErrorInfo;
    raw_fd_ostream DotFile(DotFileName.c_str(), ErrorInfo);
    printToDot(DotFile);
  }

  if (ShouldPrintStat) {
    PA.printStats(errs());
  }

  return false;
}
Ejemplo n.º 14
0
void DisassembleOneInput(const uint8_t *Data, size_t Size) {
  char AssemblyText[AssemblyTextBufSize];

  std::vector<uint8_t> DataCopy(Data, Data + Size);

  LLVMDisasmContextRef Ctx = LLVMCreateDisasmCPUFeatures(
      TripleName.c_str(), MCPU.c_str(), FeaturesStr.c_str(), nullptr, 0,
      nullptr, nullptr);
  assert(Ctx);
  uint8_t *p = DataCopy.data();
  unsigned Consumed;
  unsigned InstructionsProcessed = 0;
  do {
    Consumed = LLVMDisasmInstruction(Ctx, p, Size, 0, AssemblyText,
                                     AssemblyTextBufSize);
    Size -= Consumed;
    p += Consumed;

    InstructionsProcessed ++;
    if (InsnLimit != 0 && InstructionsProcessed < InsnLimit)
      break;
  } while (Consumed != 0);
  LLVMDisasmDispose(Ctx);
}
Ejemplo n.º 15
0
GCOVOptions GCOVOptions::getDefault() {
  GCOVOptions Options;
  Options.EmitNotes = true;
  Options.EmitData = true;
  Options.UseCfgChecksum = false;
  Options.NoRedZone = false;
  Options.FunctionNamesInData = true;

  if (DefaultGCOVVersion.size() != 4) {
    llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
                             DefaultGCOVVersion);
  }
  memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
  return Options;
}
Ejemplo n.º 16
0
static tool_output_file *GetOutputStream() {
  if (OutputFilename == "")
    OutputFilename = "-";

  std::string Err;
  tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
                                               raw_fd_ostream::F_Binary);
  if (!Err.empty()) {
    errs() << Err << '\n';
    delete Out;
    return 0;
  }

  return Out;
}
Ejemplo n.º 17
0
static tool_output_file *GetOutputStream() {
  if (OutputFilename == "")
    OutputFilename = "-";

  std::string Err;
  tool_output_file *Out =
      new tool_output_file(OutputFilename.c_str(), Err, sys::fs::F_None);
  if (!Err.empty()) {
    errs() << Err << '\n';
    delete Out;
    return nullptr;
  }

  return Out;
}
Ejemplo n.º 18
0
static void WriteOutputFile(const Module *M) {

  std::string ErrorInfo;
  OwningPtr<tool_output_file> Out
    (new tool_output_file(OutputFilename.c_str(), ErrorInfo,
			  raw_fd_ostream::F_Binary));
  if (!ErrorInfo.empty()) {
    errs() << ErrorInfo << '\n';
    exit(1);
  }

  NaClWriteBitcodeToFile(M, Out->os(), /* AcceptSupportedOnly = */ false);

  // Declare success.
  Out->keep();
}
Ejemplo n.º 19
0
void DynamicGiri::printBackwardsSlice(const Instruction *Criterion,
                                      std::set<Value *> &Slice,
                                      std::unordered_set<DynValue> &DynSlice,
                                      std::set<DynValue *> &DataFlowGraph) {
  // Print out the dynamic backwards slice.
  std::string errinfo;
  raw_fd_ostream SliceFile(SliceFilename.c_str(),
                           errinfo,
                           sys::fs::F_Append);
  if (!errinfo.empty()) {
    errs() << "Error opening the slice output file: " << SliceFilename
           << " : " << errinfo << "\n";
    return;
  }
  SliceFile << "----------------------------------------------------------\n";
  SliceFile << "Static Slice from instruction: \n";
  Criterion->print(SliceFile);
  SliceFile << "\n----------------------------------------------------------\n";
  for (std::set<Value *>::iterator i = Slice.begin(); i != Slice.end(); ++i) {
    Value *V = *i;
    V->print(SliceFile);
    SliceFile << "\n";
    if (Instruction *I = dyn_cast<Instruction>(V))
      SliceFile << "Source Line Info: "
                << SourceLineMappingPass::locateSrcInfo(I)
                << "\n";
  }

  // Print out the instructions in the dynamic backwards slice that
  // failed their invariants.
  SliceFile << "----------------------------------------------------------\n";
  SliceFile << "Dynamic Slice from instruction: \n";
  Criterion->print(SliceFile);
  SliceFile << "\n----------------------------------------------------------\n";
  for (std::unordered_set<DynValue>::iterator i = DynSlice.begin();
       i != DynSlice.end();
       ++i) {
    DynValue DV = *i;
    DV.print(SliceFile, lsNumPass);
    if (Instruction *I = dyn_cast<Instruction>(i->getValue()))
      SliceFile << "Source Line Info: "
                << SourceLineMappingPass::locateSrcInfo(I)
                << "\n";
  }
  SliceFile << "\n";
  SliceFile.close();
}
static void WriteOutputFile(const Module *M) {
  // Infer the output filename if needed.
  if (OutputFilename.empty()) {
    if (InputFilename == "-") {
      OutputFilename = "-";
    } else {
      std::string IFN = InputFilename;
      int Len = IFN.length();
      if (IFN[Len-3] == '.' && IFN[Len-2] == 'l' && IFN[Len-1] == 'l') {
        // Source ends in .ll
        OutputFilename = std::string(IFN.begin(), IFN.end()-3);
      } else {
        OutputFilename = IFN;   // Append a .bc to it
      }
      OutputFilename += ".bc";
    }
  }

  std::string ErrorInfo;
  OwningPtr<tool_output_file> Out
  (new tool_output_file(OutputFilename.c_str(), ErrorInfo,
                        llvm::sys::fs::F_Binary));
  if (!ErrorInfo.empty()) {
    errs() << ErrorInfo << '\n';
    exit(1);
  }

  if (Force || !CheckBitcodeOutputToConsole(Out->os(), true)) {
    switch(BitcodeVersion) {
      case BC29:
        llvm_2_9::WriteBitcodeToFile(M, Out->os());
        break;
      case BC29Func:
        llvm_2_9_func::WriteBitcodeToFile(M, Out->os());
        break;
      case BC32:
        llvm_3_2::WriteBitcodeToFile(M, Out->os());
        break;
      case BCHEAD:
        llvm::WriteBitcodeToFile(M, Out->os());
        break;
    }
  }

  // Declare success.
  Out->keep();
}
/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
/// bytecode file for the program.
static void EmitShellScript(char **argv) {
  if (Verbose)
    cout << "Emitting Shell Script\n";
#if defined(_WIN32) || defined(__CYGWIN__)
  // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
  // support windows systems, we copy the llvm-stub.exe executable from the
  // build tree to the destination file.
  std::string ErrMsg;  
  sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
  if (llvmstub.isEmpty())
    PrintAndExit("Could not find llvm-stub.exe executable!");

  if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
    PrintAndExit(ErrMsg);

  return;
#endif

  // Output the script to start the program...
  std::ofstream Out2(OutputFilename.c_str());
  if (!Out2.good())
    PrintAndExit("error opening '" + OutputFilename + "' for writing!");

  Out2 << "#!/bin/sh\n";
  // Allow user to setenv LLVMINTERP if lli is not in their PATH.
  Out2 << "lli=${LLVMINTERP-lli}\n";
  Out2 << "exec $lli \\\n";
  // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
  LibPaths.push_back("/lib");
  LibPaths.push_back("/usr/lib");
  LibPaths.push_back("/usr/X11R6/lib");
  // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
  // shared object at all! See RH 8: plain text.
  std::vector<std::string>::iterator libc =
    std::find(Libraries.begin(), Libraries.end(), "c");
  if (libc != Libraries.end()) Libraries.erase(libc);
  // List all the shared object (native) libraries this executable will need
  // on the command line, so that we don't have to do this manually!
  for (std::vector<std::string>::iterator i = Libraries.begin(),
         e = Libraries.end(); i != e; ++i) {
    sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
    if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
      Out2 << "    -load=" << FullLibraryPath.toString() << " \\\n";
  }
  Out2 << "    $0.bc ${1+\"$@\"}\n";
  Out2.close();
}
int main(int argc, char **argv) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
  cl::ParseCommandLineOptions(argc, argv, "strip function attribute pass\n");

  std::string ErrorMessage;

  std::unique_ptr<Module> M(LoadFile(argv[0], InputFilenames[0], Context));
  if (M.get() == 0) {
    errs() << argv[0] << ": error loading file '"
           << InputFilenames[0] << "'\n";
    return 1;
  }

  // Perform the actual function attribute stripping.
  legacy::PassManager PM;
  PM.add(createStripAttributePass());
  PM.run(*M.get());

  std::error_code EC;
  tool_output_file Out(OutputFilename.c_str(), EC,
                       sys::fs::F_None);
  if (EC) {
    errs() << EC.message() << '\n';
    return 1;
  }

  if (verifyModule(*M)) {
    errs() << argv[0] << ": stripped module is broken!\n";
    return 1;
  }

  if (OutputAssembly) {
    Out.os() << *M;
  } else if (!CheckBitcodeOutputToConsole(Out.os(), true)) {
    WriteBitcodeToFile(M.get(), Out.os());
  }

  Out.keep();

  return 0;
}
Ejemplo n.º 23
0
void AliasAnalysisChecker::collectDynamicAliases(
    DenseSet<ValuePair> &DynamicAliases) {
  DynamicAliases.clear();
  if (InputDynamicAliases == "") {
    DynamicAliasAnalysis &DAA = getAnalysis<DynamicAliasAnalysis>();
    DynamicAliases.insert(DAA.getAllAliases().begin(),
                          DAA.getAllAliases().end());
  } else {
    IDAssigner &IDA = getAnalysis<IDAssigner>();
    ifstream InputFile(InputDynamicAliases.c_str());
    unsigned VID1, VID2;
    while (InputFile >> VID1 >> VID2) {
      Value *V1 = IDA.getValue(VID1), *V2 = IDA.getValue(VID2);
      DynamicAliases.insert(make_pair(V1, V2));
    }
  }
}
std::map<std::string, int>* FeatureExtractor::getTripCountMap() {
  std::map<std::string, int> *trip_count_map = new std::map<std::string, int>;
  std::string line;
  std::ifstream infile(tripcount_filename.c_str());
  while (getline(infile,line)) {
    std::string token;
    std::istringstream ss(line);
    std::vector<std::string> v;
    while(std::getline(ss, token, ',')) {
      v.push_back(token);
    }
    if (v.size() == 2) {
      std::istringstream buffer(v[1]);
      int reuses;
      buffer >> reuses;
      (*trip_count_map)[v[0]] = reuses;
    }   
  }
Ejemplo n.º 25
0
static formatted_raw_ostream *GetOutputStream() {
  if (OutputFilename == "")
    OutputFilename = "-";

  // Make sure that the Out file gets unlinked from the disk if we get a
  // SIGINT.
  if (OutputFilename != "-")
    sys::RemoveFileOnSignal(sys::Path(OutputFilename));

  std::string Err;
  raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
                                           raw_fd_ostream::F_Binary);
  if (!Err.empty()) {
    errs() << Err << '\n';
    delete Out;
    return 0;
  }
  
  return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
}
Ejemplo n.º 26
0
static formatted_raw_ostream *GetOutputStream() {
  if (OutputFilename == "" || OutputFilename == "-")
    return &fouts();

  // Make sure that the Out file gets unlinked from the disk if we get a
  // SIGINT
  sys::RemoveFileOnSignal(sys::Path(OutputFilename));

  std::string Err;
  raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(),
                                           /*Binary=*/false, Force, Err);
  if (!Err.empty()) {
    errs() << Err << '\n';
    if (!Force)
      errs() << "Use -f command line argument to force output\n";
    delete Out;
    return 0;
  }
  
  return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
}
Ejemplo n.º 27
0
static std::string getProgram(const char *name, const cl::opt<std::string> &opt, const char *envVar = 0)
{
    std::string path;
    const char *prog = NULL;

    if (opt.getNumOccurrences() > 0 && opt.length() > 0 && (prog = opt.c_str()))
        path = findProgramByName(prog);

    if (path.empty() && envVar && (prog = getenv(envVar)))
        path = findProgramByName(prog);

    if (path.empty())
        path = findProgramByName(name);

    if (path.empty()) {
        error(Loc(), "failed to locate %s", name);
        fatal();
    }

    return path;
}
Ejemplo n.º 28
0
std::unique_ptr<FDRPCChannel> connect() {
  int sockfd = socket(PF_INET, SOCK_STREAM, 0);
  hostent *server = gethostbyname(HostName.c_str());

  if (!server) {
    errs() << "Could not find host " << HostName << "\n";
    exit(1);
  }

  sockaddr_in servAddr;
  bzero(&servAddr, sizeof(servAddr));
  servAddr.sin_family = PF_INET;
  bcopy(server->h_addr, &servAddr.sin_addr.s_addr, server->h_length);
  servAddr.sin_port = htons(Port);
  if (connect(sockfd, reinterpret_cast<sockaddr*>(&servAddr),
              sizeof(servAddr)) < 0) {
    errs() << "Failure to connect.\n";
    exit(1);
  }

  return llvm::make_unique<FDRPCChannel>(sockfd, sockfd);
}
Ejemplo n.º 29
0
int main(int argc, const char * argv[]) {
    cl::ParseCommandLineOptions(argc, argv);
    
    std::ifstream file(filename, std::iostream::binary | std::iostream::ate);
    if (!file) {
        std::cerr << "Could not open file \"" + filename + "\"" << std::endl;
        return EXIT_FAILURE;
    }
    std::streamsize size = file.tellg();
    file.seekg(0, std::ios::beg);
    
    char *code = (char *)malloc(size * sizeof(char));
    file.read(code, size);
    
    Options options = (Options) { filename.c_str(), code, optimizationLevel, emitAST, emitIR };
    
    Driver::run(options);
    
    free(code);
    
    return 0;
}
Ejemplo n.º 30
0
int main(int argc, char **argv) {
  // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
  llvm::PrettyStackTraceProgram X(argc, argv);
  cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
  llvm_shutdown_obj Y;

  OwningPtr<Module> M(new Module("/tmp/autogen.bc", getGlobalContext()));
  Function *F = GenEmptyFunction(M.get());

  // Pick an initial seed value
  Random R(SeedCL);
  // Generate lots of random instructions inside a single basic block.
  FillFunction(F, R);
  // Break the basic block into many loops.
  IntroduceControlFlow(F, R);

  // Figure out what stream we are supposed to write to...
  OwningPtr<tool_output_file> Out;
  // Default to standard output.
  if (OutputFilename.empty())
    OutputFilename = "-";

  std::string ErrorInfo;
  Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
                                 sys::fs::F_Binary));
  if (!ErrorInfo.empty()) {
    errs() << ErrorInfo << '\n';
    return 1;
  }

  PassManager Passes;
  Passes.add(createVerifierPass());
  Passes.add(createPrintModulePass(Out->os()));
  Passes.run(*M.get());
  Out->keep();

  return 0;
}