本文整理汇总了C++中Expected类的典型用法代码示例。如果您正苦于以下问题:C++ Expected类的具体用法?C++ Expected怎么用?C++ Expected使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Expected类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: printDynamicSection
void printDynamicSection(const ELFFile<ELFT> *Elf, StringRef Filename) {
ArrayRef<typename ELFT::Dyn> DynamicEntries =
unwrapOrError(Elf->dynamicEntries(), Filename);
outs() << "Dynamic Section:\n";
for (const typename ELFT::Dyn &Dyn : DynamicEntries) {
if (Dyn.d_tag == ELF::DT_NULL)
continue;
std::string Str = Elf->getDynamicTagAsString(Dyn.d_tag);
outs() << format(" %-21s", Str.c_str());
const char *Fmt =
ELFT::Is64Bits ? "0x%016" PRIx64 "\n" : "0x%08" PRIx64 "\n";
if (Dyn.d_tag == ELF::DT_NEEDED || Dyn.d_tag == ELF::DT_RPATH ||
Dyn.d_tag == ELF::DT_RUNPATH || Dyn.d_tag == ELF::DT_SONAME ||
Dyn.d_tag == ELF::DT_AUXILIARY || Dyn.d_tag == ELF::DT_FILTER) {
Expected<StringRef> StrTabOrErr = getDynamicStrTab(Elf);
if (StrTabOrErr) {
const char *Data = StrTabOrErr.get().data();
outs() << (Data + Dyn.d_un.d_val) << "\n";
continue;
}
warn(toString(StrTabOrErr.takeError()));
consumeError(StrTabOrErr.takeError());
}
outs() << format(Fmt, (uint64_t)Dyn.d_un.d_val);
}
}
示例2: formatSymbol
static std::string formatSymbol(const Dumper::Context &Ctx,
const coff_section *Section, uint64_t Offset,
uint32_t Displacement) {
std::string Buffer;
raw_string_ostream OS(Buffer);
SymbolRef Symbol;
if (!Ctx.ResolveSymbol(Section, Offset, Symbol, Ctx.UserData)) {
Expected<StringRef> Name = Symbol.getName();
if (Name) {
OS << *Name;
if (Displacement > 0)
OS << format(" +0x%X (0x%" PRIX64 ")", Displacement, Offset);
else
OS << format(" (0x%" PRIX64 ")", Offset);
return OS.str();
} else {
// TODO: Actually report errors helpfully.
consumeError(Name.takeError());
}
}
OS << format(" (0x%" PRIX64 ")", Offset);
return OS.str();
}
示例3: switch
void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
switch (C.getKind()) {
case Counter::Zero:
OS << '0';
return;
case Counter::CounterValueReference:
OS << '#' << C.getCounterID();
break;
case Counter::Expression: {
if (C.getExpressionID() >= Expressions.size())
return;
const auto &E = Expressions[C.getExpressionID()];
OS << '(';
dump(E.LHS, OS);
OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
dump(E.RHS, OS);
OS << ')';
break;
}
}
if (CounterValues.empty())
return;
Expected<int64_t> Value = evaluate(C);
if (auto E = Value.takeError()) {
consumeError(std::move(E));
return;
}
OS << '[' << *Value << ']';
}
示例4: errorToErrorCode
std::error_code
ELFDumper<ELFT>::dumpSymbol(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
StringRef StrTable, ELFYAML::Symbol &S) {
S.Type = Sym->getType();
S.Value = Sym->st_value;
S.Size = Sym->st_size;
S.Other = Sym->st_other;
Expected<StringRef> SymbolNameOrErr = Sym->getName(StrTable);
if (!SymbolNameOrErr)
return errorToErrorCode(SymbolNameOrErr.takeError());
S.Name = SymbolNameOrErr.get();
ErrorOr<const Elf_Shdr *> ShdrOrErr = Obj.getSection(Sym, SymTab, ShndxTable);
if (std::error_code EC = ShdrOrErr.getError())
return EC;
const Elf_Shdr *Shdr = *ShdrOrErr;
if (!Shdr)
return obj2yaml_error::success;
ErrorOr<StringRef> NameOrErr = Obj.getSectionName(Shdr);
if (std::error_code EC = NameOrErr.getError())
return EC;
S.Section = NameOrErr.get();
return obj2yaml_error::success;
}
示例5: verify
static bool verify(llvm::StringRef OutputFile, llvm::StringRef Arch) {
if (OutputFile == "-") {
llvm::errs() << "warning: verification skipped for " << Arch
<< "because writing to stdout.\n";
return true;
}
Expected<OwningBinary<Binary>> BinOrErr = createBinary(OutputFile);
if (!BinOrErr) {
errs() << OutputFile << ": " << toString(BinOrErr.takeError());
return false;
}
Binary &Binary = *BinOrErr.get().getBinary();
if (auto *Obj = dyn_cast<MachOObjectFile>(&Binary)) {
raw_ostream &os = Verbose ? errs() : nulls();
os << "Verifying DWARF for architecture: " << Arch << "\n";
std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(*Obj);
DIDumpOptions DumpOpts;
bool success = DICtx->verify(os, DumpOpts.noImplicitRecursion());
if (!success)
errs() << "error: verification failed for " << Arch << '\n';
return success;
}
return false;
}
示例6: loadCurrentObjectFileSymbols
/// Load the current object file symbols into CurrentObjectAddresses.
void MachODebugMapParser::loadCurrentObjectFileSymbols(
const object::MachOObjectFile &Obj) {
CurrentObjectAddresses.clear();
for (auto Sym : Obj.symbols()) {
uint64_t Addr = Sym.getValue();
Expected<StringRef> Name = Sym.getName();
if (!Name) {
// TODO: Actually report errors helpfully.
consumeError(Name.takeError());
continue;
}
// The value of some categories of symbols isn't meaningful. For
// example common symbols store their size in the value field, not
// their address. Absolute symbols have a fixed address that can
// conflict with standard symbols. These symbols (especially the
// common ones), might still be referenced by relocations. These
// relocations will use the symbol itself, and won't need an
// object file address. The object file address field is optional
// in the DebugMap, leave it unassigned for these symbols.
if (Sym.getFlags() & (SymbolRef::SF_Absolute | SymbolRef::SF_Common))
CurrentObjectAddresses[*Name] = None;
else
CurrentObjectAddresses[*Name] = Addr;
}
}
示例7: move
/// diffProgram - This method executes the specified module and diffs the
/// output against the file specified by ReferenceOutputFile. If the output
/// is different, 1 is returned. If there is a problem with the code
/// generator (e.g., llc crashes), this will set ErrMsg.
///
Expected<bool> BugDriver::diffProgram(const Module *Program,
const std::string &BitcodeFile,
const std::string &SharedObject,
bool RemoveBitcode) const {
// Execute the program, generating an output file...
Expected<std::string> Output =
executeProgram(Program, "", BitcodeFile, SharedObject, nullptr);
if (Error E = Output.takeError())
return std::move(E);
std::string Error;
bool FilesDifferent = false;
if (int Diff = DiffFilesWithTolerance(ReferenceOutputFile, *Output,
AbsTolerance, RelTolerance, &Error)) {
if (Diff == 2) {
errs() << "While diffing output: " << Error << '\n';
exit(1);
}
FilesDifferent = true;
} else {
// Remove the generated output if there are no differences.
sys::fs::remove(*Output);
}
// Remove the bitcode file if we are supposed to.
if (RemoveBitcode)
sys::fs::remove(BitcodeFile);
return FilesDifferent;
}
示例8: HandleOneRename
void HandleOneRename(ASTContext &Context, const std::string &NewName,
const std::string &PrevName,
const std::vector<std::string> &USRs) {
const SourceManager &SourceMgr = Context.getSourceManager();
SymbolOccurrences Occurrences = tooling::getOccurrencesOfUSRs(
USRs, PrevName, Context.getTranslationUnitDecl());
if (PrintLocations) {
for (const auto &Occurrence : Occurrences) {
FullSourceLoc FullLoc(Occurrence.getNameRanges()[0].getBegin(),
SourceMgr);
errs() << "clang-rename: renamed at: " << SourceMgr.getFilename(FullLoc)
<< ":" << FullLoc.getSpellingLineNumber() << ":"
<< FullLoc.getSpellingColumnNumber() << "\n";
}
}
// FIXME: Support multi-piece names.
// FIXME: better error handling (propagate error out).
StringRef NewNameRef = NewName;
Expected<std::vector<AtomicChange>> Change =
createRenameReplacements(Occurrences, SourceMgr, NewNameRef);
if (!Change) {
llvm::errs() << "Failed to create renaming replacements for '" << PrevName
<< "'! " << llvm::toString(Change.takeError()) << "\n";
return;
}
convertChangesToFileReplacements(*Change, &FileToReplaces);
}
示例9: GetOutputStream
std::unique_ptr<ASTConsumer>
CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
BackendAction BA = static_cast<BackendAction>(Act);
std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
if (BA != Backend_EmitNothing && !OS)
return nullptr;
// Load bitcode modules to link with, if we need to.
if (LinkModules.empty())
for (const CodeGenOptions::BitcodeFileToLink &F :
CI.getCodeGenOpts().LinkBitcodeFiles) {
auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
if (!BCBuf) {
CI.getDiagnostics().Report(diag::err_cannot_open_file)
<< F.Filename << BCBuf.getError().message();
LinkModules.clear();
return nullptr;
}
Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
if (!ModuleOrErr) {
handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
CI.getDiagnostics().Report(diag::err_cannot_open_file)
<< F.Filename << EIB.message();
});
LinkModules.clear();
return nullptr;
}
LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
F.Internalize, F.LinkFlags});
}
CoverageSourceInfo *CoverageInfo = nullptr;
// Add the preprocessor callback only when the coverage mapping is generated.
if (CI.getCodeGenOpts().CoverageMapping) {
CoverageInfo = new CoverageSourceInfo;
CI.getPreprocessor().addPPCallbacks(
std::unique_ptr<PPCallbacks>(CoverageInfo));
}
std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
BEConsumer = Result.get();
// Enable generating macro debug info only when debug info is not disabled and
// also macro debug info is enabled.
if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
CI.getCodeGenOpts().MacroDebugInfo) {
std::unique_ptr<PPCallbacks> Callbacks =
llvm::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
CI.getPreprocessor());
CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
}
return std::move(Result);
}
示例10: success
Error RawInstrProfReader<IntPtrT>::readValueProfilingData(
InstrProfRecord &Record) {
Record.clearValueData();
CurValueDataSize = 0;
// Need to match the logic in value profile dumper code in compiler-rt:
uint32_t NumValueKinds = 0;
for (uint32_t I = 0; I < IPVK_Last + 1; I++)
NumValueKinds += (Data->NumValueSites[I] != 0);
if (!NumValueKinds)
return success();
Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
ValueProfData::getValueProfData(
ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(),
getDataEndianness());
if (Error E = VDataPtrOrErr.takeError())
return E;
// Note that besides deserialization, this also performs the conversion for
// indirect call targets. The function pointers from the raw profile are
// remapped into function name hashes.
VDataPtrOrErr.get()->deserializeTo(Record, &Symtab->getAddrHashMap());
CurValueDataSize = VDataPtrOrErr.get()->getSize();
return success();
}
示例11: GTEST_TEST
GTEST_TEST(ExpectedTest, success_contructor_initialization) {
Expected<std::string, TestError> value = std::string("Test");
EXPECT_TRUE(value);
EXPECT_TRUE(value.isValue());
EXPECT_FALSE(value.isError());
EXPECT_EQ(value.get(), "Test");
}
示例12: upgrade
// Upgrade a vector of bitcode modules created by an old version of LLVM by
// creating an irsymtab for them in the current format.
static Expected<FileContents> upgrade(ArrayRef<BitcodeModule> BMs) {
FileContents FC;
LLVMContext Ctx;
std::vector<Module *> Mods;
std::vector<std::unique_ptr<Module>> OwnedMods;
for (auto BM : BMs) {
Expected<std::unique_ptr<Module>> MOrErr =
BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
/*IsImporting*/ false);
if (!MOrErr)
return MOrErr.takeError();
Mods.push_back(MOrErr->get());
OwnedMods.push_back(std::move(*MOrErr));
}
StringTableBuilder StrtabBuilder(StringTableBuilder::RAW);
BumpPtrAllocator Alloc;
if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
return std::move(E);
StrtabBuilder.finalizeInOrder();
FC.Strtab.resize(StrtabBuilder.getSize());
StrtabBuilder.write((uint8_t *)FC.Strtab.data());
FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
{FC.Strtab.data(), FC.Strtab.size()}};
return std::move(FC);
}
示例13: errorToErrorCode
std::error_code ELFDumper<ELFT>::dumpRelocation(const RelT *Rel,
const Elf_Shdr *SymTab,
ELFYAML::Relocation &R) {
R.Type = Rel->getType(Obj.isMips64EL());
R.Offset = Rel->r_offset;
R.Addend = 0;
auto SymOrErr = Obj.getRelocationSymbol(Rel, SymTab);
if (!SymOrErr)
return errorToErrorCode(SymOrErr.takeError());
const Elf_Sym *Sym = *SymOrErr;
auto StrTabSec = Obj.getSection(SymTab->sh_link);
if (!StrTabSec)
return errorToErrorCode(StrTabSec.takeError());
auto StrTabOrErr = Obj.getStringTable(*StrTabSec);
if (!StrTabOrErr)
return errorToErrorCode(StrTabOrErr.takeError());
StringRef StrTab = *StrTabOrErr;
if (Sym) {
Expected<StringRef> NameOrErr = getSymbolName(Sym, StrTab, SymTab);
if (!NameOrErr)
return errorToErrorCode(NameOrErr.takeError());
R.Symbol = NameOrErr.get();
} else {
// We have some edge cases of relocations without a symbol associated,
// e.g. an object containing the invalid (according to the System V
// ABI) R_X86_64_NONE reloc. Create a symbol with an empty name instead
// of crashing.
R.Symbol = "";
}
return obj2yaml_error::success;
}
示例14: doList
static void doList(opt::InputArgList& Args) {
// lib.exe prints the contents of the first archive file.
std::unique_ptr<MemoryBuffer> B;
for (auto *Arg : Args.filtered(OPT_INPUT)) {
// Create or open the archive object.
ErrorOr<std::unique_ptr<MemoryBuffer>> MaybeBuf =
MemoryBuffer::getFile(Arg->getValue(), -1, false);
fatalOpenError(errorCodeToError(MaybeBuf.getError()), Arg->getValue());
if (identify_magic(MaybeBuf.get()->getBuffer()) == file_magic::archive) {
B = std::move(MaybeBuf.get());
break;
}
}
// lib.exe doesn't print an error if no .lib files are passed.
if (!B)
return;
Error Err = Error::success();
object::Archive Archive(B.get()->getMemBufferRef(), Err);
fatalOpenError(std::move(Err), B->getBufferIdentifier());
for (auto &C : Archive.children(Err)) {
Expected<StringRef> NameOrErr = C.getName();
fatalOpenError(NameOrErr.takeError(), B->getBufferIdentifier());
StringRef Name = NameOrErr.get();
llvm::outs() << Name << '\n';
}
fatalOpenError(std::move(Err), B->getBufferIdentifier());
}
示例15: LLVMRustLinkerAdd
extern "C" bool
LLVMRustLinkerAdd(RustLinker *L, char *BC, size_t Len) {
std::unique_ptr<MemoryBuffer> Buf =
MemoryBuffer::getMemBufferCopy(StringRef(BC, Len));
#if LLVM_VERSION_GE(4, 0)
Expected<std::unique_ptr<Module>> SrcOrError =
llvm::getLazyBitcodeModule(Buf->getMemBufferRef(), L->Ctx);
if (!SrcOrError) {
LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
return false;
}
auto Src = std::move(*SrcOrError);
#else
ErrorOr<std::unique_ptr<Module>> Src =
llvm::getLazyBitcodeModule(std::move(Buf), L->Ctx);
if (!Src) {
LLVMRustSetLastError(Src.getError().message().c_str());
return false;
}
#endif
#if LLVM_VERSION_GE(4, 0)
if (L->L.linkInModule(std::move(Src))) {
#else
if (L->L.linkInModule(std::move(Src.get()))) {
#endif
LLVMRustSetLastError("");
return false;
}
return true;
}