/// addPassesToEmitMC - Add passes to the specified pass manager to get /// machine code emitted with the MCJIT. This method returns true if machine /// code is not supported. It fills the MCContext Ctx pointer which can be /// used to build custom MCStreamer. /// bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, raw_ostream &Out, bool DisableVerify) { // Add common CodeGen passes. Ctx = addPassesToGenerateCode(this, PM, DisableVerify); if (!Ctx) return true; if (hasMCSaveTempLabels()) Ctx->setAllowTemporaryLabels(false); // Create the code emitter for the target if it exists. If not, .o file // emission fails. const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>(); MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx); MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple()); if (MCE == 0 || MAB == 0) return true; OwningPtr<MCStreamer> AsmStreamer; AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx, *MAB, Out, MCE, hasMCRelaxAll(), hasMCNoExecStack())); AsmStreamer.get()->InitSections(); // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); if (Printer == 0) return true; // If successful, createAsmPrinter took ownership of AsmStreamer. AsmStreamer.take(); PM.add(Printer); return false; // success! }
void MCJIT::generateCodeForModule(Module *M) { // Get a thread lock to make sure we aren't trying to load multiple times MutexGuard locked(lock); // This must be a module which has already been added to this MCJIT instance. assert(OwnedModules.ownsModule(M) && "MCJIT::generateCodeForModule: Unknown module."); // Re-compilation is not supported if (OwnedModules.hasModuleBeenLoaded(M)) return; OwningPtr<ObjectBuffer> ObjectToLoad; // Try to load the pre-compiled object from cache if possible if (0 != ObjCache) { OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M)); if (0 != PreCompiledObject.get()) ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take())); } // If the cache did not contain a suitable object, compile the object if (!ObjectToLoad) { ObjectToLoad.reset(emitObject(M)); assert(ObjectToLoad.get() && "Compilation did not produce an object."); } // Load the object into the dynamic linker. // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list). ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.take()); LoadedObjects.push_back(LoadedObject); if (!LoadedObject) report_fatal_error(Dyld.getErrorString()); // FIXME: Make this optional, maybe even move it to a JIT event listener LoadedObject->registerWithDebugger(); NotifyObjectEmitted(*LoadedObject); OwnedModules.markModuleAsLoaded(M); }
int main (int argc, char ** argv) { if (argc < 3) { fprintf(stderr,"Not enough positional arguments to %s.\n",argv[0]); return 1; } llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. LLVMContext &Context = getGlobalContext(); std::string InputFilename(argv[1]); std::string OutputFilename(argv[2]); OwningPtr<tool_output_file> Out; std::string ErrorInfo; Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo, sys::fs::F_Binary)); SMDiagnostic Err; std::auto_ptr<Module> M; M.reset(ParseIRFile(InputFilename, Err, Context)); if (M.get() == 0) { Err.print(argv[0], errs()); return 1; } Summarize(M.get()); WriteBitcodeToFile(M.get(),Out->os()); Out->keep(); 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 profile dump decoder\n"); // Read in the bitcode file... std::string ErrorMessage; OwningPtr<MemoryBuffer> Buffer; error_code ec; Module *M = 0; if (!(ec = MemoryBuffer::getFileOrSTDIN(BitcodeFile, Buffer))) { M = ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage); } else ErrorMessage = ec.message(); if (M == 0) { errs() << argv[0] << ": " << BitcodeFile << ": " << ErrorMessage << "\n"; return 1; } // Read the profiling information. This is redundant since we load it again // using the standard profile info provider pass, but for now this gives us // access to additional information not exposed via the ProfileInfo // interface. ProfileInfoLoader PIL(argv[0], ProfileDataFile); // Run the printer pass. PassManager PassMgr; PassMgr.add(createProfileLoaderPass(ProfileDataFile)); PassMgr.add(new ProfileInfoPrinterPass(PIL)); PassMgr.run(*M); return 0; }
bool SimplePrinterConsumer::HandleTopLevelDecl(DeclGroupRef D) { if(D.begin() == D.end()) { return true; } Decl *firstD = *(D.begin()); if(compInst->getSourceManager().isInSystemHeader(firstD->getLocation())) { return true; } PrintingPolicy policy = compInst->getASTContext().getPrintingPolicy(); NullStmt *nullSt = new (compInst->getASTContext()) NullStmt(SourceLocation()); for(DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { Decl *dd = *I; DPRINT("PrintingPolicy: %d %d %d %d %d", policy.SuppressSpecifiers, policy.SuppressScope, policy.SuppressTag, policy.SuppressUnwrittenScope, policy.SuppressSpecifiers); dd->print(out, policy); nullSt->printPretty(out, NULL, policy); if(dd->hasBody()) { Stmt *ss = dd->getBody(); // Print Stmts //dd->dump(); //StmtPrinter(compInst, dd->getBody()).TraverseDecl(dd); // CFG OwningPtr<CFG> cfg; cfg.reset(CFG::buildCFG((const Decl*)dd, (Stmt*)(dd->getBody()), &compInst->getASTContext(), CFG::BuildOptions())); assert(cfg.get() != NULL && "build CFG failed."); cfg->dump(compInst->getLangOpts(), true); cfg->viewCFG(compInst->getLangOpts()); } } return true; };
error_code Archive::Child::getMemoryBuffer(OwningPtr<MemoryBuffer> &Result, bool FullPath) const { StringRef Name; if (error_code ec = getName(Name)) return ec; SmallString<128> Path; Result.reset(MemoryBuffer::getMemBuffer( getBuffer(), FullPath ? (Twine(Parent->getFileName()) + "(" + Name + ")") .toStringRef(Path) : Name, false)); return error_code::success(); }
// Get just the externally visible defined symbols from the bitcode bool llvm::GetBitcodeSymbols(const sys::Path& fName, LLVMContext& Context, std::vector<std::string>& symbols, std::string* ErrMsg) { OwningPtr<MemoryBuffer> Buffer; if (error_code ec = MemoryBuffer::getFileOrSTDIN(fName.c_str(), Buffer)) { if (ErrMsg) *ErrMsg = "Could not open file '" + fName.str() + "'" + ": " + ec.message(); return true; } Module *M = ParseBitcodeFile(Buffer.get(), Context, ErrMsg); if (!M) return true; // Get the symbols getSymbols(M, symbols); // Done with the module. delete M; return true; }
/// addPassesToEmitMC - Add passes to the specified pass manager to get /// machine code emitted with the MCJIT. This method returns true if machine /// code is not supported. It fills the MCContext Ctx pointer which can be /// used to build custom MCStreamer. /// bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, raw_ostream &Out, CodeGenOpt::Level OptLevel, bool DisableVerify) { // Add common CodeGen passes. if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx)) return true; // Create the code emitter for the target if it exists. If not, .o file // emission fails. MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Ctx); TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple); if (MCE == 0 || TAB == 0) return true; OwningPtr<MCStreamer> AsmStreamer; AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Ctx, *TAB, Out, MCE, hasMCRelaxAll(), hasMCNoExecStack())); AsmStreamer.get()->InitSections(); // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); if (Printer == 0) return true; // If successful, createAsmPrinter took ownership of AsmStreamer. AsmStreamer.take(); PM.add(Printer); // Make sure the code model is set. setCodeModelForJIT(); return false; // success! }
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; }
bool TeslaVisitor::VisitFunctionDecl(FunctionDecl *F) { // Only analyse non-deleted definitions (i.e. definitions with bodies). if (!F->doesThisDeclarationHaveABody()) return true; // We only parse functions that return __tesla_automaton_description*. const Type *RetTy = F->getResultType().getTypePtr(); if (!RetTy->isPointerType()) return true; QualType Pointee = RetTy->getPointeeType(); auto TypeID = Pointee.getBaseTypeIdentifier(); if (!TypeID) return true; OwningPtr<Parser> P; StringRef FnName = F->getName(); // Build a Parser appropriate to what we're parsing. string RetTypeName = TypeID->getName(); if (RetTypeName == AUTOMATON_DESC) P.reset(Parser::AutomatonParser(F, *Context)); else if ((RetTypeName == AUTOMATON_USAGE) && (FnName != AUTOMATON_USES)) P.reset(Parser::MappingParser(F, *Context)); else return true; // Actually parse the function. if (!P) return false; OwningPtr<AutomatonDescription> Description; OwningPtr<Usage> Use; if (!P->Parse(Description, Use)) return false; if (Description) Automata.push_back(Description.take()); if (Use) Roots.push_back(Use.take()); return true; }
llvm::MemoryBuffer *FileManager:: getBufferForFile(const FileEntry *Entry, std::string *ErrorStr, bool isVolatile) { OwningPtr<llvm::MemoryBuffer> Result; llvm::error_code ec; uint64_t FileSize = Entry->getSize(); // If there's a high enough chance that the file have changed since we // got its size, force a stat before opening it. if (isVolatile) FileSize = -1; const char *Filename = Entry->getName(); // If the file is already open, use the open file descriptor. if (Entry->File) { ec = Entry->File->getBuffer(Filename, Result, FileSize); if (ErrorStr) *ErrorStr = ec.message(); Entry->closeFile(); return Result.take(); } // Otherwise, open the file. if (FileSystemOpts.WorkingDir.empty()) { ec = FS->getBufferForFile(Filename, Result, FileSize); if (ec && ErrorStr) *ErrorStr = ec.message(); return Result.take(); } SmallString<128> FilePath(Entry->getName()); FixupRelativePath(FilePath); ec = FS->getBufferForFile(FilePath.str(), Result, FileSize); if (ec && ErrorStr) *ErrorStr = ec.message(); return Result.take(); }
bool FixItRewriter::WriteFixedFiles( std::vector<std::pair<std::string, std::string> > *RewrittenFiles) { if (NumFailures > 0 && !FixItOpts->FixWhatYouCan) { Diag(FullSourceLoc(), diag::warn_fixit_no_changes); return true; } RewritesReceiver Rec(Rewrite); Editor.applyRewrites(Rec); for (iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) { const FileEntry *Entry = Rewrite.getSourceMgr().getFileEntryForID(I->first); int fd; std::string Filename = FixItOpts->RewriteFilename(Entry->getName(), fd); std::string Err; OwningPtr<llvm::raw_fd_ostream> OS; if (fd != -1) { OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true)); } else { OS.reset(new llvm::raw_fd_ostream(Filename.c_str(), Err, llvm::raw_fd_ostream::F_Binary)); } if (!Err.empty()) { Diags.Report(clang::diag::err_fe_unable_to_open_output) << Filename << Err; continue; } RewriteBuffer &RewriteBuf = I->second; RewriteBuf.write(*OS); OS->flush(); if (RewrittenFiles) RewrittenFiles->push_back(std::make_pair(Entry->getName(), Filename)); } return false; }
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, raw_fd_ostream::F_Binary)); if (!ErrorInfo.empty()) { errs() << ErrorInfo << '\n'; exit(1); } // @LOCALMOD-BEGIN if (Force || !CheckBitcodeOutputToConsole(Out->os(), true)) { WriteBitcodeToFile(M, Out->os()); } // @LOCALMOD-END // Declare success. Out->keep(); }
static int performOperation(ArchiveOperation Operation) { // Create or open the archive object. OwningPtr<MemoryBuffer> Buf; error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false); if (EC && EC != llvm::errc::no_such_file_or_directory) { errs() << ToolName << ": error opening '" << ArchiveName << "': " << EC.message() << "!\n"; return 1; } if (!EC) { object::Archive Archive(Buf.take(), EC); if (EC) { errs() << ToolName << ": error loading '" << ArchiveName << "': " << EC.message() << "!\n"; return 1; } performOperation(Operation, &Archive); return 0; } assert(EC == llvm::errc::no_such_file_or_directory); if (!shouldCreateArchive(Operation)) { failIfError(EC, Twine("error loading '") + ArchiveName + "'"); } else { if (!Create) { // Produce a warning if we should and we're creating the archive errs() << ToolName << ": creating " << ArchiveName << "\n"; } } performOperation(Operation, NULL); return 0; }
virtual bool HandleTopLevelDecl(DeclGroupRef D) { PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), Context->getSourceManager(), "LLVM IR generation of declaration"); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.startTimer(); Gen->HandleTopLevelDecl(D); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.stopTimer(); return true; }
// MCJIT will call this function before compiling any module // MCJIT takes ownership of both the MemoryBuffer object and the memory // to which it refers. virtual MemoryBuffer* getObject(const Module* M) { // Get the ModuleID const std::string ModuleID = M->getModuleIdentifier(); // If we've flagged this as an IR file, cache it if (0 == ModuleID.compare(0, 3, "IR:")) { std::string IRFileName = ModuleID.substr(3); SmallString<128> IRCacheFile = CacheDir; sys::path::append(IRCacheFile, IRFileName); if (!sys::fs::exists(IRCacheFile.str())) { // This file isn't in our cache return NULL; } OwningPtr<MemoryBuffer> IRObjectBuffer; MemoryBuffer::getFile(IRCacheFile.c_str(), IRObjectBuffer, -1, false); // MCJIT will want to write into this buffer, and we don't want that // because the file has probably just been mmapped. Instead we make // a copy. The filed-based buffer will be released when it goes // out of scope. return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer()); } return NULL; }
/// \brief Attempt to read the lock file with the given name, if it exists. /// /// \param LockFileName The name of the lock file to read. /// /// \returns The process ID of the process that owns this lock file Optional<std::pair<std::string, int> > LockFileManager::readLockFile(StringRef LockFileName) { // Check whether the lock file exists. If not, clearly there's nothing // to read, so we just return. bool Exists = false; if (sys::fs::exists(LockFileName, Exists) || !Exists) return None; // Read the owning host and PID out of the lock file. If it appears that the // owning process is dead, the lock file is invalid. OwningPtr<MemoryBuffer> MB; if (MemoryBuffer::getFile(LockFileName, MB)) { StringRef Hostname; StringRef PIDStr; tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " "); int PID; if (PIDStr.getAsInteger(10, PID)) return std::make_pair(std::string(Hostname), PID); } // Delete the lock file. It's invalid anyway. sys::fs::remove(LockFileName); return None; }
explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr, DiagnosticsEngine &Diags, ModuleMap &Map, const DirectoryEntry *Directory, const DirectoryEntry *BuiltinIncludeDir) : L(L), SourceMgr(SourceMgr), Diags(Diags), Map(Map), Directory(Directory), BuiltinIncludeDir(BuiltinIncludeDir), HadError(false), ActiveModule(0) { TargetOptions TargetOpts; TargetOpts.Triple = llvm::sys::getDefaultTargetTriple(); Target.reset(TargetInfo::CreateTargetInfo(Diags, TargetOpts)); Tok.clear(); consumeToken(); }
bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input, DiagnosticsEngine &Diags, FileManager &FileMgr, SourceManager &SourceMgr, const FrontendOptions &Opts) { SrcMgr::CharacteristicKind Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; if (Input.isBuffer()) { SourceMgr.createMainFileIDForMemBuffer(Input.getBuffer(), Kind); assert(!SourceMgr.getMainFileID().isInvalid() && "Couldn't establish MainFileID!"); return true; } StringRef InputFile = Input.getFile(); // Figure out where to get and map in the main file. if (InputFile != "-") { const FileEntry *File = FileMgr.getFile(InputFile); if (!File) { Diags.Report(diag::err_fe_error_reading) << InputFile; return false; } SourceMgr.createMainFileID(File, Kind); // The natural SourceManager infrastructure can't currently handle named // pipes, but we would at least like to accept them for the main // file. Detect them here, read them with the more generic MemoryBuffer // function, and simply override their contents as we do for STDIN. if (File->isNamedPipe()) { OwningPtr<llvm::MemoryBuffer> MB; if (llvm::error_code ec = llvm::MemoryBuffer::getFile(InputFile, MB)) { Diags.Report(diag::err_cannot_open_file) << InputFile << ec.message(); return false; } SourceMgr.overrideFileContents(File, MB.take()); } } else { OwningPtr<llvm::MemoryBuffer> SB; if (llvm::MemoryBuffer::getSTDIN(SB)) { // FIXME: Give ec.message() in this diag. Diags.Report(diag::err_fe_error_reading_stdin); return false; } const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(), SB->getBufferSize(), 0); SourceMgr.createMainFileID(File, Kind); SourceMgr.overrideFileContents(File, SB.take()); } assert(!SourceMgr.getMainFileID().isInvalid() && "Couldn't establish MainFileID!"); return true; }
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(); }
error_code MachOUniversalBinary::ObjectForArch::getAsObjectFile( OwningPtr<ObjectFile> &Result) const { if (Parent) { StringRef ParentData = Parent->getData(); StringRef ObjectData = ParentData.substr(Header.offset, Header.size); std::string ObjectName = Parent->getFileName().str() + ":" + Triple::getArchTypeName(MachOObjectFile::getArch(Header.cputype)); MemoryBuffer *ObjBuffer = MemoryBuffer::getMemBuffer( ObjectData, ObjectName, false); ErrorOr<ObjectFile *> Obj = ObjectFile::createMachOObjectFile(ObjBuffer); if (error_code EC = Obj.getError()) return EC; Result.reset(Obj.get()); return object_error::success; } return object_error::parse_failed; }
OwningPtr<LuaStackChecker> LuaStateAccess::replaceLuaStackChecker(lua_State* L, OwningPtr<LuaStackChecker> newStackChecker) { ExtraLuaStateData* extra = (ExtraLuaStateData*)((char*)(L) - sizeof(ExtraLuaStateData)); OwningPtr<LuaStackChecker> oldStackChecker; if (extra->stackChecker != NULL) { { LuaStackChecker* p = (LuaStackChecker*) extra->stackChecker; LuaStateAccess_HeapObjectRefManipulator::resetInitialOwnership(p); oldStackChecker = OwningPtr<LuaStackChecker>(p); // no decRefCounter, because OwningPtr takes given Ownerchip } LuaStateAccess_HeapObjectRefManipulator::incRefCounter(newStackChecker); extra->stackChecker = newStackChecker.getRawPtr(); } return oldStackChecker; }
static error_code getMemoryBufferForStream(int FD, StringRef BufferName, OwningPtr<MemoryBuffer> &result) { const ssize_t ChunkSize = 4096*4; SmallString<ChunkSize> Buffer; ssize_t ReadBytes; // Read into Buffer until we hit EOF. do { Buffer.reserve(Buffer.size() + ChunkSize); ReadBytes = read(FD, Buffer.end(), ChunkSize); if (ReadBytes == -1) { if (errno == EINTR) continue; return error_code(errno, posix_category()); } Buffer.set_size(Buffer.size() + ReadBytes); } while (ReadBytes != 0); result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName)); return error_code::success(); }
error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) { // Read in all of the data from stdin, we cannot mmap stdin. // // FIXME: That isn't necessarily true, we should try to mmap stdin and // fallback if it fails. sys::Program::ChangeStdinToBinary(); const ssize_t ChunkSize = 4096*4; SmallString<ChunkSize> Buffer; ssize_t ReadBytes; // Read into Buffer until we hit EOF. do { Buffer.reserve(Buffer.size() + ChunkSize); ReadBytes = read(0, Buffer.end(), ChunkSize); if (ReadBytes == -1) { if (errno == EINTR) continue; return error_code(errno, posix_category()); } Buffer.set_size(Buffer.size() + ReadBytes); } while (ReadBytes != 0); result.reset(getMemBufferCopy(Buffer, "<stdin>")); return error_code::success(); }
ExternalASTSource * CompilerInstance::createPCHExternalASTSource(StringRef Path, const std::string &Sysroot, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context, void *DeserializationListener, bool Preamble) { OwningPtr<ASTReader> Reader; Reader.reset(new ASTReader(PP, Context, Sysroot.empty() ? "" : Sysroot.c_str(), DisablePCHValidation, AllowPCHWithCompilerErrors)); Reader->setDeserializationListener( static_cast<ASTDeserializationListener *>(DeserializationListener)); switch (Reader->ReadAST(Path, Preamble ? serialization::MK_Preamble : serialization::MK_PCH, SourceLocation(), ASTReader::ARR_None)) { case ASTReader::Success: // Set the predefines buffer as suggested by the PCH reader. Typically, the // predefines buffer will be empty. PP.setPredefines(Reader->getSuggestedPredefines()); return Reader.take(); case ASTReader::Failure: // Unrecoverable failure: don't even try to process the input file. break; case ASTReader::OutOfDate: case ASTReader::VersionMismatch: case ASTReader::ConfigurationMismatch: case ASTReader::HadErrors: // No suitable PCH file could be found. Return an error. break; } return 0; }
static void DumpSymbolNamesFromFile(std::string &Filename) { if (Filename != "-" && !sys::fs::exists(Filename)) { errs() << ToolName << ": '" << Filename << "': " << "No such file\n"; return; } OwningPtr<MemoryBuffer> Buffer; if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename)) return; sys::fs::file_magic magic = sys::fs::identify_magic(Buffer->getBuffer()); LLVMContext &Context = getGlobalContext(); std::string ErrorMessage; if (magic == sys::fs::file_magic::bitcode) { Module *Result = 0; Result = ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage); if (Result) { DumpSymbolNamesFromModule(Result); delete Result; } else { error(ErrorMessage, Filename); return; } } else if (magic == sys::fs::file_magic::archive) { OwningPtr<Binary> arch; if (error(object::createBinary(Buffer.take(), arch), Filename)) return; if (object::Archive *a = dyn_cast<object::Archive>(arch.get())) { if (ArchiveMap) { outs() << "Archive map" << "\n"; for (object::Archive::symbol_iterator i = a->begin_symbols(), e = a->end_symbols(); i != e; ++i) { object::Archive::child_iterator c; StringRef symname; StringRef filename; if (error(i->getMember(c))) return; if (error(i->getName(symname))) return; if (error(c->getName(filename))) return; outs() << symname << " in " << filename << "\n"; } outs() << "\n"; } for (object::Archive::child_iterator i = a->begin_children(), e = a->end_children(); i != e; ++i) { OwningPtr<Binary> child; if (i->getAsBinary(child)) { // Try opening it as a bitcode file. OwningPtr<MemoryBuffer> buff(i->getBuffer()); Module *Result = 0; if (buff) Result = ParseBitcodeFile(buff.get(), Context, &ErrorMessage); if (Result) { DumpSymbolNamesFromModule(Result); delete Result; } continue; } if (object::ObjectFile *o = dyn_cast<ObjectFile>(child.get())) { outs() << o->getFileName() << ":\n"; DumpSymbolNamesFromObject(o); } } } } else if (magic.is_object()) { OwningPtr<Binary> obj; if (error(object::createBinary(Buffer.take(), obj), Filename)) return; if (object::ObjectFile *o = dyn_cast<ObjectFile>(obj.get())) DumpSymbolNamesFromObject(o); } else { errs() << ToolName << ": " << Filename << ": " << "unrecognizable file type\n"; return; } }
//===----------------------------------------------------------------------===// // main for opt // int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X(argc, argv); // Enable debug stream buffering. EnableDebugBuffering = true; llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. LLVMContext &Context = getGlobalContext(); InitializeAllTargets(); InitializeAllTargetMCs(); // Initialize passes PassRegistry &Registry = *PassRegistry::getPassRegistry(); initializeCore(Registry); initializeScalarOpts(Registry); initializeObjCARCOpts(Registry); initializeVectorization(Registry); initializeIPO(Registry); initializeAnalysis(Registry); initializeIPA(Registry); initializeTransformUtils(Registry); initializeInstCombine(Registry); initializeInstrumentation(Registry); initializeTarget(Registry); // @LOCALMOD-BEGIN initializeAddPNaClExternalDeclsPass(Registry); initializeCanonicalizeMemIntrinsicsPass(Registry); initializeExpandArithWithOverflowPass(Registry); initializeExpandByValPass(Registry); initializeExpandConstantExprPass(Registry); initializeExpandCtorsPass(Registry); initializeExpandGetElementPtrPass(Registry); initializeExpandSmallArgumentsPass(Registry); initializeExpandStructRegsPass(Registry); initializeExpandTlsConstantExprPass(Registry); initializeExpandTlsPass(Registry); initializeExpandVarArgsPass(Registry); initializeFlattenGlobalsPass(Registry); initializeGlobalCleanupPass(Registry); initializeInsertDivideCheckPass(Registry); initializePNaClABIVerifyFunctionsPass(Registry); initializePNaClABIVerifyModulePass(Registry); initializePNaClSjLjEHPass(Registry); initializePromoteI1OpsPass(Registry); initializePromoteIntegersPass(Registry); initializeRemoveAsmMemoryPass(Registry); initializeReplacePtrsWithIntsPass(Registry); initializeResolveAliasesPass(Registry); initializeResolvePNaClIntrinsicsPass(Registry); initializeRewriteAtomicsPass(Registry); initializeRewriteLLVMIntrinsicsPass(Registry); initializeRewritePNaClLibraryCallsPass(Registry); initializeStripAttributesPass(Registry); initializeStripMetadataPass(Registry); initializeExpandI64Pass(Registry); // @LOCALMOD-END cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .bc modular optimizer and analysis printer\n"); if (AnalyzeOnly && NoOutput) { errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; return 1; } SMDiagnostic Err; // Load the input module... OwningPtr<Module> M; M.reset(ParseIRFile(InputFilename, Err, Context)); if (M.get() == 0) { Err.print(argv[0], errs()); return 1; } // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) M->setTargetTriple(Triple::normalize(TargetTriple)); // Figure out what stream we are supposed to write to... OwningPtr<tool_output_file> Out; if (NoOutput) { if (!OutputFilename.empty()) errs() << "WARNING: The -o (output filename) option is ignored when\n" "the --disable-output option is used.\n"; } else { // Default to standard output. if (OutputFilename.empty()) OutputFilename = "-"; std::string ErrorInfo; Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo, raw_fd_ostream::F_Binary)); if (!ErrorInfo.empty()) { errs() << ErrorInfo << '\n'; return 1; } } // If the output is set to be emitted to standard out, and standard out is a // console, print out a warning message and refuse to do it. We don't // impress anyone by spewing tons of binary goo to a terminal. if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) if (CheckBitcodeOutputToConsole(Out->os(), !Quiet)) NoOutput = true; // Create a PassManager to hold and optimize the collection of passes we are // about to build. // PassManager Passes; // Add an appropriate TargetLibraryInfo pass for the module's triple. TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple())); // The -disable-simplify-libcalls flag actually disables all builtin optzns. if (DisableSimplifyLibCalls) TLI->disableAllFunctions(); Passes.add(TLI); // Add an appropriate DataLayout instance for this module. DataLayout *TD = 0; const std::string &ModuleDataLayout = M.get()->getDataLayout(); if (!ModuleDataLayout.empty()) TD = new DataLayout(ModuleDataLayout); else if (!DefaultDataLayout.empty()) TD = new DataLayout(DefaultDataLayout); if (TD) Passes.add(TD); Triple ModuleTriple(M->getTargetTriple()); TargetMachine *Machine = 0; if (ModuleTriple.getArch()) Machine = GetTargetMachine(Triple(ModuleTriple)); OwningPtr<TargetMachine> TM(Machine); // Add internal analysis passes from the target machine. if (TM.get()) TM->addAnalysisPasses(Passes); OwningPtr<FunctionPassManager> FPasses; if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) { FPasses.reset(new FunctionPassManager(M.get())); if (TD) FPasses->add(new DataLayout(*TD)); } if (PrintBreakpoints) { // Default to standard output. if (!Out) { if (OutputFilename.empty()) OutputFilename = "-"; std::string ErrorInfo; Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo, raw_fd_ostream::F_Binary)); if (!ErrorInfo.empty()) { errs() << ErrorInfo << '\n'; return 1; } } Passes.add(new BreakpointPrinter(Out->os())); NoOutput = true; } // If the -strip-debug command line option was specified, add it. If // -std-compile-opts was also specified, it will handle StripDebug. if (StripDebug && !StandardCompileOpts) addPass(Passes, createStripSymbolsPass(true)); // Create a new optimization pass for each one specified on the command line for (unsigned i = 0; i < PassList.size(); ++i) { // Check to see if -std-compile-opts was specified before this option. If // so, handle it. if (StandardCompileOpts && StandardCompileOpts.getPosition() < PassList.getPosition(i)) { AddStandardCompilePasses(Passes); StandardCompileOpts = false; } if (StandardLinkOpts && StandardLinkOpts.getPosition() < PassList.getPosition(i)) { AddStandardLinkPasses(Passes); StandardLinkOpts = false; } if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { AddOptimizationPasses(Passes, *FPasses, 1, 0); OptLevelO1 = false; } if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { AddOptimizationPasses(Passes, *FPasses, 2, 0); OptLevelO2 = false; } if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { AddOptimizationPasses(Passes, *FPasses, 2, 1); OptLevelOs = false; } if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { AddOptimizationPasses(Passes, *FPasses, 2, 2); OptLevelOz = false; } if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { AddOptimizationPasses(Passes, *FPasses, 3, 0); OptLevelO3 = false; } // @LOCALMOD-BEGIN if (PNaClABISimplifyPreOpt && PNaClABISimplifyPreOpt.getPosition() < PassList.getPosition(i)) { PNaClABISimplifyAddPreOptPasses(Passes); PNaClABISimplifyPreOpt = false; } if (PNaClABISimplifyPostOpt && PNaClABISimplifyPostOpt.getPosition() < PassList.getPosition(i)) { PNaClABISimplifyAddPostOptPasses(Passes); PNaClABISimplifyPostOpt = false; } // @LOCALMOD-END const PassInfo *PassInf = PassList[i]; Pass *P = 0; if (PassInf->getNormalCtor()) P = PassInf->getNormalCtor()(); else errs() << argv[0] << ": cannot create pass: "******"\n"; if (P) { PassKind Kind = P->getPassKind(); addPass(Passes, P); if (AnalyzeOnly) { switch (Kind) { case PT_BasicBlock: Passes.add(new BasicBlockPassPrinter(PassInf, Out->os())); break; case PT_Region: Passes.add(new RegionPassPrinter(PassInf, Out->os())); break; case PT_Loop: Passes.add(new LoopPassPrinter(PassInf, Out->os())); break; case PT_Function: Passes.add(new FunctionPassPrinter(PassInf, Out->os())); break; case PT_CallGraphSCC: Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os())); break; default: Passes.add(new ModulePassPrinter(PassInf, Out->os())); break; } } } if (PrintEachXForm) Passes.add(createPrintModulePass(&errs())); } // If -std-compile-opts was specified at the end of the pass list, add them. if (StandardCompileOpts) { AddStandardCompilePasses(Passes); StandardCompileOpts = false; } if (StandardLinkOpts) { AddStandardLinkPasses(Passes); StandardLinkOpts = false; } if (OptLevelO1) AddOptimizationPasses(Passes, *FPasses, 1, 0); if (OptLevelO2) AddOptimizationPasses(Passes, *FPasses, 2, 0); if (OptLevelOs) AddOptimizationPasses(Passes, *FPasses, 2, 1); if (OptLevelOz) AddOptimizationPasses(Passes, *FPasses, 2, 2); if (OptLevelO3) AddOptimizationPasses(Passes, *FPasses, 3, 0); if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) { FPasses->doInitialization(); for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F) FPasses->run(*F); FPasses->doFinalization(); } // @LOCALMOD-BEGIN if (PNaClABISimplifyPreOpt) PNaClABISimplifyAddPreOptPasses(Passes); if (PNaClABISimplifyPostOpt) PNaClABISimplifyAddPostOptPasses(Passes); // @LOCALMOD-END // Check that the module is well formed on completion of optimization if (!NoVerify && !VerifyEach) Passes.add(createVerifierPass()); // Write bitcode or assembly to the output as the last step... if (!NoOutput && !AnalyzeOnly) { if (OutputAssembly) Passes.add(createPrintModulePass(&Out->os())); // @LOCALMOD } // Before executing passes, print the final values of the LLVM options. cl::PrintOptionValues(); // Now that we have all of the passes ready, run them. Passes.run(*M.get()); // @LOCALMOD-BEGIN // Write bitcode to the output. if (!NoOutput && !AnalyzeOnly && !OutputAssembly) { switch (OutputFileFormat) { case LLVMFormat: WriteBitcodeToFile(M.get(), Out->os()); break; case PNaClFormat: NaClWriteBitcodeToFile(M.get(), Out->os()); break; default: errs() << "Don't understand bitcode format for generated bitcode.\n"; return 1; } } // @LOCALMOD-END // Declare success. if (!NoOutput || PrintBreakpoints) Out->keep(); return 0; }
int main(int argc, char *argv[]) { cl::ParseCommandLineOptions(argc, argv); auto& err = llvm::errs(); ManifestFile Result; std::map<Identifier,const AutomatonDescription*> Automata; std::map<Identifier,const Usage*> Usages; for (auto& Filename : InputFiles) { OwningPtr<Manifest> Manifest(Manifest::load(llvm::errs(), Automaton::Unlinked, Filename)); if (!Manifest) { err << "Unable to read manifest '" << Filename << "'\n"; return 1; } for (auto i : Manifest->AllAutomata()) { auto Existing = Automata.find(i.first); if (Existing == Automata.end()) Automata[i.first] = &(*Result.add_automaton() = *i.second); // If we already have this automaton, verify that both are // exactly the same. else if (*Existing->second != *i.second) panic("Attempting to cat two files containing automaton '" + ShortName(Existing->first) + "', but these automata are not exactly the same."); } for (auto i : Manifest->RootAutomata()) { auto Existing = Usages.find(i->identifier()); if (Existing == Usages.end()) Usages[i->identifier()] = &(*Result.add_root() = *i); else if (*Existing->second != *i) panic("Attempting to cat two files containing root '" + ShortName(i->identifier()) + "', but these roots are not exactly the same."); } } string ProtobufText; google::protobuf::TextFormat::PrintToString(Result, &ProtobufText); bool UseFile = (OutputFile != "-"); OwningPtr<raw_fd_ostream> outfile; if (UseFile) { string OutErrorInfo; outfile.reset(new raw_fd_ostream(OutputFile.c_str(), OutErrorInfo)); } raw_ostream& out = UseFile ? *outfile : llvm::outs(); out << ProtobufText; google::protobuf::ShutdownProtobufLibrary(); return 0; }
int main(int argc, char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; cl::ParseCommandLineOptions(argc, argv, "linker script randomizer\n"); sys::Path ldPath = sys::Program::FindProgramByName("ld"); if (ldPath.isEmpty()) { errs() << "Couldn't find system linker"; llvm_shutdown(); return 1; } sys::Path scriptPath = sys::Path::GetTemporaryDirectory(); if (scriptPath.isEmpty()) { errs() << "Error accessing temporary directory"; llvm_shutdown(); return 1; } scriptPath.appendComponent("ld_script"); scriptPath.makeUnique(false, NULL); sys::Path devNull; std::string errMsg; const char *ldArgs[] = { ldPath.c_str(), "--verbose", NULL }; const sys::Path *redirects[] = { &devNull, &scriptPath, &scriptPath, NULL }; if (sys::Program::ExecuteAndWait(ldPath, ldArgs, 0, redirects, 0, 0, &errMsg)) { errs() << "Error executing linker"; llvm_shutdown(); return 1; } OwningPtr< MemoryBuffer > scriptFile; error_code ec = MemoryBuffer::getFile(scriptPath.c_str(), scriptFile); if (ec) { errs() << "Error reading script file: " << ec.message(); llvm_shutdown(); return 1; } uint32_t minPage = (MinBaseAddress + PAGE_SIZE - 1) / PAGE_SIZE, maxPage = MaxBaseAddress / PAGE_SIZE; if (minPage > maxPage) { errs() << "Base address interval is empty"; llvm_shutdown(); return 1; } uint32_t newAddr = PAGE_SIZE * (minPage + RandomNumberGenerator::Generator().Random(maxPage - minPage + 1)); char oldAddrStr[12]; sprintf(oldAddrStr, "0x%08x", OldBaseAddress.getValue()); llvm::Regex oldAddrRegex(oldAddrStr); StringRef scriptText = scriptFile->getBuffer(); StringRef oldScriptText = scriptText; char newAddrStr[12]; sprintf(newAddrStr, "0x%08x", newAddr); do { // Replace one occurrence of old address with new one oldScriptText = scriptText; scriptText = oldAddrRegex.sub(newAddrStr, scriptText); } while (!scriptText.equals(oldScriptText)); std::cout << scriptText.str(); return 0; }
bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM, formatted_raw_ostream &Out, CodeGenFileType FileType, CodeGenOpt::Level OptLevel, bool DisableVerify) { // Add common CodeGen passes. MCContext *Context = 0; if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context)) return true; assert(Context != 0 && "Failed to get MCContext"); if (hasMCSaveTempLabels()) Context->setAllowTemporaryLabels(false); const MCAsmInfo &MAI = *getMCAsmInfo(); const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>(); OwningPtr<MCStreamer> AsmStreamer; switch (FileType) { default: return true; case CGFT_AssemblyFile: { MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI); // Create a code emitter if asked to show the encoding. MCCodeEmitter *MCE = 0; MCAsmBackend *MAB = 0; if (ShowMCEncoding) { const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>(); MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context); MAB = getTarget().createMCAsmBackend(getTargetTriple()); } MCStreamer *S = getTarget().createAsmStreamer(*Context, Out, getVerboseAsm(), hasMCUseLoc(), hasMCUseCFI(), hasMCUseDwarfDirectory(), InstPrinter, MCE, MAB, ShowMCInst); AsmStreamer.reset(S); break; } case CGFT_ObjectFile: { // Create the code emitter for the target if it exists. If not, .o file // emission fails. MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context); MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple()); if (MCE == 0 || MAB == 0) return true; AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Context, *MAB, Out, MCE, hasMCRelaxAll(), hasMCNoExecStack())); AsmStreamer.get()->InitSections(); break; } case CGFT_Null: // The Null output is intended for use for performance analysis and testing, // not real users. AsmStreamer.reset(createNullStreamer(*Context)); break; } if (EnableMCLogging) AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs())); // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); if (Printer == 0) return true; // If successful, createAsmPrinter took ownership of AsmStreamer. AsmStreamer.take(); PM.add(Printer); PM.add(createGCInfoDeleter()); return false; }