int main(int argc, char **argv) { LLVMContext &context = getGlobalContext(); SMDiagnostic err; std::unique_ptr<Module> m = parseIRFile("-", err, context); if (!m) { err.print(argv[0], errs()); return 1; } for (auto &v : m->getGlobalList()) { if (v.hasLocalLinkage() && v.hasUnnamedAddr()) v.setName(""); } for (auto &f : m->getFunctionList()) { for (auto &a : f.getArgumentList()) a.setName(""); for (auto &b : f.getBasicBlockList()) { b.setName(""); for (auto &i : b.getInstList()) i.setName(""); } } outs() << *m; return 0; }
int main(int argc, char **argv) { if (argc < 2) { errs() << "Usage: " << argv[0] << " <IR file>\n"; return 1; } // Parse the input LLVM IR file into a module. SMDiagnostic Err; std::unique_ptr<Module> Mod(parseIRFile(argv[1], Err, getGlobalContext())); if (!Mod) { Err.print(argv[0], errs()); return 1; } // Create a function declarations for _tidx, _tidy, _tidz FunctionType *TidFuncTy = FunctionType::get(Type::getInt32Ty(Mod->getContext()), false); Function *Tidx = Function::Create(TidFuncTy, GlobalValue::InternalLinkage, "_tidx", Mod.get()); Function *Tidy = Function::Create(TidFuncTy, GlobalValue::InternalLinkage, "_tidy", Mod.get()); Function *Tidz = Function::Create(TidFuncTy, GlobalValue::InternalLinkage, "_tidz", Mod.get()); // Create a pass manager and fill it with the passes we want to run. PassManager PM; PM.add(new ReplaceThreadIdxRefs(Tidx, Tidy, Tidz)); PM.run(*Mod); outs() << "Dumping the module after the pass has run:\n"; Mod->dump(); return 0; }
int main (int argc, char **argv) { // This boilerplate provides convenient stack traces and clean LLVM exit // handling. It also initializes the built in support for convenient // command line option handling. sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj shutdown; cl::ParseCommandLineOptions(argc, argv); // Construct an IR file from the filename passed on the command line. SMDiagnostic err; LLVMContext &context = getGlobalContext(); unique_ptr<Module> module = parseIRFile(inPath.getValue(), err, context); if (!module.get()) { errs() << "Error reading bitcode file: " << inPath << "\n"; err.print(argv[0], errs()); return -1; } if (AnalysisType::DYNAMIC == analysisType) { prepareLinkingPaths(StringRef(argv[0])); instrumentForDynamicCount(*module); } else { countStaticCalls(*module); } return 0; }
int main (int argc, char **argv, const char **env) { // This boilerplate provides convenient stack traces and clean LLVM exit // handling. It also initializes the built in support for convenient // command line option handling. sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X{argc, argv}; llvm_shutdown_obj shutdown; cl::ParseCommandLineOptions(argc, argv); // Construct an IR file from the filename passed on the command line. LLVMContext &context = getGlobalContext(); SMDiagnostic err; unique_ptr<Module> module = parseIRFile(inPath.getValue(), err, context); if (!module.get()) { errs() << "Error reading bitcode file.\n"; err.print(argv[0], errs()); return -1; } // Build up all of the passes that we want to run on the module. PassManager pm; pm.add(new callgraphs::CallGraphPass); pm.add(new callgraphs::WeightedCallGraphPass); pm.add(new CallGraphPrinter<callgraphs::WeightedCallGraphPass>(outs())); pm.run(*module); return 0; }
int main(int argc, char **argv, char * const *envp) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); LLVMContext &Context = getGlobalContext(); atexit(llvm_shutdown); // If we have a native target, initialize it to ensure it is linked in and // usable by the JIT. InitializeNativeTarget(); InitializeNativeTargetAsmPrinter(); InitializeNativeTargetAsmParser(); cl::ParseCommandLineOptions(argc, argv, "llvm interpreter & dynamic compiler\n"); // Load the bitcode... SMDiagnostic Err; std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context); Module *Mod = Owner.get(); if (!Mod) { Err.print(argv[0], errs()); return 1; } //Mod->dump(); return runOrcLazyJIT(std::move(Owner), argc, argv); //return 0; }
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, "llvm .ll -> .bc assembler\n"); // Parse the file now... SMDiagnostic Err; std::auto_ptr<Module> M(ParseAssemblyFile(InputFilename, Err, Context)); if (M.get() == 0) { Err.print(argv[0], errs()); return 1; } if (!DisableVerify) { std::string Err; if (verifyModule(*M.get(), ReturnStatusAction, &Err)) { errs() << argv[0] << ": assembly parsed, but does not verify as correct!\n"; errs() << Err; return 1; } } if (DumpAsm) errs() << "Here's the assembly:\n" << *M.get(); if (!DisableOutput) WriteOutputFile(M.get()); return 0; }
int main(int argc, char **argv) { LLVMContext &Context = getGlobalContext(); SMDiagnostic Err; cl::ParseCommandLineOptions(argc, argv, "LLVM module splitter\n"); std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context); if (!M) { Err.print(argv[0], errs()); return 1; } unsigned I = 0; SplitModule(std::move(M), NumOutputs, [&](std::unique_ptr<Module> MPart) { std::error_code EC; std::unique_ptr<tool_output_file> Out(new tool_output_file( OutputFilename + utostr(I++), EC, sys::fs::F_None)); if (EC) { errs() << EC.message() << '\n'; exit(1); } verifyModule(*MPart); WriteBitcodeToFile(MPart.get(), Out->os()); // Declare success. Out->keep(); }, PreserveLocals); return 0; }
int main(int argc, char **argv) { InitLLVM X(argc, argv); LLVMContext Context; cl::ParseCommandLineOptions(argc, argv, "llvm .ll -> .bc assembler\n"); // Parse the file now... SMDiagnostic Err; std::unique_ptr<Module> M = parseAssemblyFile( InputFilename, Err, Context, nullptr, !DisableVerify, ClDataLayout); if (!M.get()) { Err.print(argv[0], errs()); return 1; } if (!DisableVerify) { std::string ErrorStr; raw_string_ostream OS(ErrorStr); if (verifyModule(*M.get(), &OS)) { errs() << argv[0] << ": assembly parsed, but does not verify as correct!\n"; errs() << OS.str(); return 1; } } if (DumpAsm) errs() << "Here's the assembly:\n" << *M.get(); if (!DisableOutput) WriteOutputFile(M.get()); return 0; }
IR JIT(IR code) { SMDiagnostic errors; string parser_errors; ParseAssemblyString(code.assembly.c_str(),master.Program,errors,Context); if(master.debug) { cerr << "Code:\n" << code.assembly << endl; } llvm::Function* entryfn = master.Engine->FindFunctionNamed("entry"); if(entryfn == NULL) nerror("ERROR: Couldn't find program entry point."); if(!errors.getMessage().empty()) { entryfn->eraseFromParent(); nerror("IR Parsed with errors: ",errors.getMessage(),"\nCode: \n",code.assembly); } if(verifyModule(*master.Program,ReturnStatusAction,&parser_errors)) { entryfn->eraseFromParent(); nerror("IR Parser Error: ",parser_errors); } master.Passes.run(*master.Program); if(master.debug) { cerr << "\nIR:" << endl; master.Program->dump(); } return code; }
/// ParseInputFile - Given a bitcode or assembly input filename, parse and /// return it, or return null if not possible. /// Module *llvm::ParseInputFile(const std::string &Filename, LLVMContext& Ctxt) { std::auto_ptr<MemoryBuffer> Buffer(MemoryBuffer::getFileOrSTDIN(Filename)); Module *Result = 0; if (Buffer.get()) Result = ParseBitcodeFile(Buffer.get(), Ctxt); SMDiagnostic Err; if (!Result && !(Result = ParseAssemblyFile(Filename, Err, Ctxt))) { Err.Print("bugpoint", errs()); Result = 0; } // If we don't have an override triple, use the first one to configure // bugpoint, or use the host triple if none provided. if (Result) { if (TargetTriple.getTriple().empty()) { Triple TheTriple(Result->getTargetTriple()); if (TheTriple.getTriple().empty()) TheTriple.setTriple(sys::getHostTriple()); TargetTriple.setTriple(TheTriple.getTriple()); } Result->setTargetTriple(TargetTriple.getTriple()); // override the triple } return Result; }
std::unique_ptr<Module> llvm::parseInputFile(StringRef Filename, LLVMContext &Ctxt) { SMDiagnostic Err; std::unique_ptr<Module> Result = parseIRFile(Filename, Err, Ctxt); if (!Result) { Err.print("bugpoint", errs()); return Result; } if (verifyModule(*Result, &errs())) { errs() << "bugpoint: " << Filename << ": error: input module is broken!\n"; return std::unique_ptr<Module>(); } // If we don't have an override triple, use the first one to configure // bugpoint, or use the host triple if none provided. if (TargetTriple.getTriple().empty()) { Triple TheTriple(Result->getTargetTriple()); if (TheTriple.getTriple().empty()) TheTriple.setTriple(sys::getDefaultTargetTriple()); TargetTriple.setTriple(TheTriple.getTriple()); } Result->setTargetTriple(TargetTriple.getTriple()); // override the triple return Result; }
CodeGenContext::CodeGenContext(): mainFunction(0), builder(getGlobalContext()) { module = new Module("main", getGlobalContext()); linker=new llvm::Linker("phc", module); char * externLibDir=getenv(PHC_ROOT_ENV); if(externLibDir==0){ std::cout<<"Need Enviroment Variable "<<PHC_ROOT_ENV<<"\n"; return; } std::cout << "Parse print function\n"; SMDiagnostic Err; std::string dir(externLibDir, strlen(externLibDir)); std::string filename("/extern/print.s"); filename = dir + filename; libs = llvm::ParseIRFile(filename.c_str(), Err, getGlobalContext()); std::cout << "Status: " << Err.getMessage() << "\n"; if (libs == 0) { std::cout << "Error: cannot parse module " << filename << "\n"; return; } std::cout << "Link print function\n"; std::string errorMsg; linker->LinkModules(module, libs, llvm::Linker::DestroySource, &errorMsg); std::cout << "Status: " << errorMsg << "\n"; }
int main(int argc, char **argv) { using namespace llvm; std::cout << "hello_world_ir: " << std::endl; std::cout << std::endl; std::cout << hello_world_ir << std::endl; std::cout << std::endl; InitializeNativeTarget(); LLVMContext context; SMDiagnostic error; Module *m = ParseIR(MemoryBuffer::getMemBuffer(StringRef(hello_world_ir)), error, context); if(!m) { error.print(argv[0], errs()); } ExecutionEngine *ee = ExecutionEngine::create(m); Function *func = ee->FindFunctionNamed("hello_world"); typedef void (*fcn_ptr)(); fcn_ptr hello_world = reinterpret_cast<fcn_ptr>(ee->getPointerToFunction(func)); hello_world(); delete ee; return 0; }
int main(int argc, char **argv) { LLVMContext &Context = getGlobalContext(); SMDiagnostic Err; cl::ParseCommandLineOptions(argc, argv, "PNaCl Bitcode ABI checker\n"); OwningPtr<Module> Mod( NaClParseIRFile(InputFilename, InputFileFormat, Err, Context)); if (Mod.get() == 0) { Err.print(argv[0], errs()); return 1; } PNaClABIErrorReporter ABIErrorReporter; ABIErrorReporter.setNonFatal(); bool ErrorsFound = false; OwningPtr<ModulePass> ModuleChecker( createPNaClABIVerifyModulePass(&ABIErrorReporter)); ModuleChecker->doInitialization(*Mod); ModuleChecker->runOnModule(*Mod); ErrorsFound |= CheckABIVerifyErrors(ABIErrorReporter, "Module"); OwningPtr<FunctionPassManager> PM(new FunctionPassManager(&*Mod)); PM->add(new DataLayout(&*Mod)); PM->add(createPNaClABIVerifyFunctionsPass(&ABIErrorReporter)); PM->doInitialization(); for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) { PM->run(*I); ErrorsFound |= CheckABIVerifyErrors(ABIErrorReporter, "Function " + I->getName()); } PM->doFinalization(); return ErrorsFound ? 1 : 0; }
int main(int argc, char *argv[]) { // Parse command line arguments cl::ParseCommandLineOptions(argc, argv, "SPIR Encoder"); // Load bitcode module from file SMDiagnostic ErrInfo; LLVMContext& Context = getGlobalContext(); Module *Input = ParseIRFile(InputFilename, ErrInfo, Context); if (!Input) { raw_os_ostream StdErr(cerr); ErrInfo.print(argv[0], StdErr); return 1; } // Open output file string ErrStr; raw_fd_ostream Output(OutputFilename.c_str(), ErrStr, sys::fs::F_None); if (!ErrStr.empty()) { cerr << ErrStr << endl; return 1; } // Output re-encoded module SPIR::WriteBitcodeToFile_SPIR(Input, Output); return 0; }
/// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo /// struct above. static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) { AsmPrinter::SrcMgrDiagInfo *DiagInfo = static_cast<AsmPrinter::SrcMgrDiagInfo *>(diagInfo); assert(DiagInfo && "Diagnostic context not passed down?"); // Look up a LocInfo for the buffer this diagnostic is coming from. unsigned BufNum = DiagInfo->SrcMgr.FindBufferContainingLoc(Diag.getLoc()); const MDNode *LocInfo = nullptr; if (BufNum > 0 && BufNum <= DiagInfo->LocInfos.size()) LocInfo = DiagInfo->LocInfos[BufNum-1]; // If the inline asm had metadata associated with it, pull out a location // cookie corresponding to which line the error occurred on. unsigned LocCookie = 0; if (LocInfo) { unsigned ErrorLine = Diag.getLineNo()-1; if (ErrorLine >= LocInfo->getNumOperands()) ErrorLine = 0; if (LocInfo->getNumOperands() != 0) if (const ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine))) LocCookie = CI->getZExtValue(); } DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie); }
/// Reads a module from a file. On error, messages are written to stderr /// and null is returned. static Module *ReadModule(LLVMContext &Context, StringRef Name) { SMDiagnostic Diag; Module *M = ParseIRFile(Name, Diag, Context); if (!M) Diag.Print("llvmdiff", errs()); return M; }
std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const { DEBUG(dbgs() << " - read assembly\n"); SMDiagnostic Err; std::unique_ptr<Module> M = parseAssemblyFile(Filename, Err, Context); if (!M.get()) Err.print("verify-uselistorder", errs()); return M; }
/// Reads a module from a file. On error, messages are written to stderr /// and null is returned. static std::unique_ptr<Module> readModule(LLVMContext &Context, StringRef Name) { SMDiagnostic Diag; std::unique_ptr<Module> M = parseIRFile(Name, Diag, Context); if (!M) Diag.print("llvm-diff", errs()); return M; }
Module *LoadModule(StringRef Filename, LLVMContext& Context) { SMDiagnostic Err; Module *M = ParseIRFile(Filename, Err, Context); if (M == nullptr) { Err.print(Argv0, errs()); } return M; }
int main(int argc, char **argv){ // Load the bitcode cl::ParseCommandLineOptions(argc, argv, "helper_call_modifier\n"); SMDiagnostic Err; LLVMContext &Context = getGlobalContext(); Module *Mod = ParseIRFile(InputFile, Err, Context); if (!Mod) { Err.print(argv[0], errs()); exit(1); } /* * This iterates through the list of functions, copies/renames, and deletes * the original function. This is how we have to do it with the while loop * because of how the LLVM function list is implemented. */ Module::iterator i = Mod->begin(); while (i != Mod->end()){ Function *f = i; i++; Module *m = f->getParent(); assert(m); if (!f->isDeclaration()){ // internal functions only ValueToValueMapTy VMap; Function *newFunc = CloneFunction(f, VMap, false); std::string origName = f->getName(); std::string newName = origName.append("_llvm"); newFunc->setName(newName); /* * XXX: We need to remove stack smash protection from helper * functions that are to be compiled with the JIT. There is a bug * in LLVM 3.0 that causes the JIT to generate stack protection code * that causes the program to segfault. More information available * here: http://llvm.org/bugs/show_bug.cgi?id=11089 */ const AttributeSet AS = newFunc->getAttributes(); newFunc->setAttributes(AS.removeAttribute(newFunc->getContext(), AttributeSet::FunctionIndex, Attribute::StackProtectReq)); // push to the front so the iterator doesn't see them again m->getFunctionList().push_front(newFunc); f->replaceAllUsesWith(newFunc); f->eraseFromParent(); } } // Verify the new bitcode and write it out, printing errors if necessary std::string errstring; verifyModule(*Mod, PrintMessageAction, &errstring); raw_fd_ostream *fstream = new raw_fd_ostream(OutputFile.c_str(), errstring); WriteBitcodeToFile(Mod, *fstream); printf("%s", errstring.c_str()); fstream->close(); return 0; }
extern "C" LLVMModuleRef LLVMRustParseAssemblyFile(const char *Filename) { SMDiagnostic d; Module *m = ParseAssemblyFile(Filename, d, getGlobalContext()); if (m) { return wrap(m); } else { LLVMRustError = d.getMessage().str().c_str(); return NULL; } }
static std::unique_ptr<Module> loadModule(StringRef Filename, LLVMContext &Ctx) { SMDiagnostic Err; std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx)); if (!M) { Err.print("llvm-lto", errs()); report_fatal_error("Can't load module for file " + Filename); } return M; }
SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error, SMRange SourceRange) { assert(SourceRange.isValid()); // Translate the location of the error from the location in the llvm IR string // to the corresponding location in the MIR file. auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start); unsigned Line = LineAndColumn.first + Error.getLineNo() - 1; unsigned Column = Error.getColumnNo(); StringRef LineStr = Error.getLineContents(); SMLoc Loc = Error.getLoc(); // Get the full line and adjust the column number by taking the indentation of // LLVM IR into account. for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E; L != E; ++L) { if (L.line_number() == Line) { LineStr = *L; Loc = SMLoc::getFromPointer(LineStr.data()); auto Indent = LineStr.find(Error.getLineContents()); if (Indent != StringRef::npos) Column += Indent; break; } } return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(), Error.getMessage(), LineStr, Error.getRanges(), Error.getFixIts()); }
std::unique_ptr<Module> MCJITHelper::createModuleFromFile(const std::string &FileName) { // TODO check for file existence SMDiagnostic Err; std::unique_ptr<Module> M = parseIRFile(FileName, Err, Context); // TODO if (!M) { Err.print("IR parsing failed: ", errs()); return nullptr; } return M; }
void LLVMGenerator::linkLibrary(const std::string& path) { SMDiagnostic diag; Module* mod = ParseIRFile(path, diag, getGlobalContext()); if(!mod) throw std::runtime_error("could not load library '" + path + "': " + diag.getMessage()); linkLibrary(*mod); }
static std::unique_ptr<Module> getModule( StringRef ProgramName, LLVMContext &Context, StreamingMemoryObject *StreamingObject) { std::unique_ptr<Module> M; SMDiagnostic Err; std::string VerboseBuffer; raw_string_ostream VerboseStrm(VerboseBuffer); if (LazyBitcode) { std::string StrError; switch (InputFileFormat) { case PNaClFormat: { std::unique_ptr<StreamingMemoryObject> Cache( new ThreadedStreamingCache(StreamingObject)); M.reset(getNaClStreamedBitcodeModule( InputFilename, Cache.release(), Context, &VerboseStrm, &StrError)); break; } case LLVMFormat: { std::unique_ptr<StreamingMemoryObject> Cache( new ThreadedStreamingCache(StreamingObject)); ErrorOr<std::unique_ptr<Module>> MOrErr = getStreamedBitcodeModule( InputFilename, Cache.release(), Context); M = std::move(*MOrErr); break; } case AutodetectFileFormat: report_fatal_error("Command can't autodetect file format!"); } if (!StrError.empty()) Err = SMDiagnostic(InputFilename, SourceMgr::DK_Error, StrError); } else { #if defined(PNACL_BROWSER_TRANSLATOR) llvm_unreachable("native client SRPC only supports streaming"); #else // Parses binary bitcode as well as textual assembly // (so pulls in more code into pnacl-llc). M = NaClParseIRFile(InputFilename, InputFileFormat, Err, &VerboseStrm, Context); #endif } if (!M) { #if defined(PNACL_BROWSER_TRANSLATOR) report_fatal_error(VerboseStrm.str() + Err.getMessage()); #else // Err.print is prettier, so use it for the non-sandboxed translator. Err.print(ProgramName.data(), errs()); errs() << VerboseStrm.str(); return nullptr; #endif } return std::move(M); }
static inline std::unique_ptr<Module> LoadFile(const char *argv0, const std::string &FN, LLVMContext& Context) { SMDiagnostic Err; std::unique_ptr<Module> Result = parseIRFile(FN, Err, Context); if (Result) { return Result; // Load successful! } Err.print(argv0, errs()); return std::unique_ptr<Module>(); }
static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context, unsigned LocCookie) { bool *HasError = static_cast<bool *>(Context); if (SMD.getKind() == SourceMgr::DK_Error) *HasError = true; SMD.print(nullptr, errs()); // For testing purposes, we print the LocCookie here. if (LocCookie) errs() << "note: !srcloc = " << LocCookie << "\n"; }
// LoadFile - Read the specified bitcode file in and return it. This routine // searches the link path for the specified file to try to find it... // static inline Module *LoadFile(const char *argv0, const std::string &FN, LLVMContext& Context) { SMDiagnostic Err; if (Verbose) errs() << "Loading '" << FN << "'\n"; Module* Result = nullptr; Result = ParseIRFile(FN, Err, Context); if (Result) return Result; // Load successful! Err.print(argv0, errs()); return nullptr; }