Path: blob/main/contrib/llvm-project/llvm/lib/ProfileData/InstrProfReader.cpp
35234 views
//===- InstrProfReader.cpp - Instrumented profiling reader ----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains support for reading profiling data for clang's9// instrumentation based PGO and coverage.10//11//===----------------------------------------------------------------------===//1213#include "llvm/ProfileData/InstrProfReader.h"14#include "llvm/ADT/ArrayRef.h"15#include "llvm/ADT/DenseMap.h"16#include "llvm/ADT/StringExtras.h"17#include "llvm/ADT/StringRef.h"18#include "llvm/IR/ProfileSummary.h"19#include "llvm/ProfileData/InstrProf.h"20#include "llvm/ProfileData/MemProf.h"21#include "llvm/ProfileData/ProfileCommon.h"22#include "llvm/ProfileData/SymbolRemappingReader.h"23#include "llvm/Support/Endian.h"24#include "llvm/Support/Error.h"25#include "llvm/Support/ErrorOr.h"26#include "llvm/Support/FormatVariadic.h"27#include "llvm/Support/MemoryBuffer.h"28#include "llvm/Support/SwapByteOrder.h"29#include "llvm/Support/VirtualFileSystem.h"30#include <algorithm>31#include <cstddef>32#include <cstdint>33#include <limits>34#include <memory>35#include <optional>36#include <system_error>37#include <utility>38#include <vector>3940using namespace llvm;4142// Extracts the variant information from the top 32 bits in the version and43// returns an enum specifying the variants present.44static InstrProfKind getProfileKindFromVersion(uint64_t Version) {45InstrProfKind ProfileKind = InstrProfKind::Unknown;46if (Version & VARIANT_MASK_IR_PROF) {47ProfileKind |= InstrProfKind::IRInstrumentation;48}49if (Version & VARIANT_MASK_CSIR_PROF) {50ProfileKind |= InstrProfKind::ContextSensitive;51}52if (Version & VARIANT_MASK_INSTR_ENTRY) {53ProfileKind |= InstrProfKind::FunctionEntryInstrumentation;54}55if (Version & VARIANT_MASK_BYTE_COVERAGE) {56ProfileKind |= InstrProfKind::SingleByteCoverage;57}58if (Version & VARIANT_MASK_FUNCTION_ENTRY_ONLY) {59ProfileKind |= InstrProfKind::FunctionEntryOnly;60}61if (Version & VARIANT_MASK_MEMPROF) {62ProfileKind |= InstrProfKind::MemProf;63}64if (Version & VARIANT_MASK_TEMPORAL_PROF) {65ProfileKind |= InstrProfKind::TemporalProfile;66}67return ProfileKind;68}6970static Expected<std::unique_ptr<MemoryBuffer>>71setupMemoryBuffer(const Twine &Filename, vfs::FileSystem &FS) {72auto BufferOrErr = Filename.str() == "-" ? MemoryBuffer::getSTDIN()73: FS.getBufferForFile(Filename);74if (std::error_code EC = BufferOrErr.getError())75return errorCodeToError(EC);76return std::move(BufferOrErr.get());77}7879static Error initializeReader(InstrProfReader &Reader) {80return Reader.readHeader();81}8283/// Read a list of binary ids from a profile that consist of84/// a. uint64_t binary id length85/// b. uint8_t binary id data86/// c. uint8_t padding (if necessary)87/// This function is shared between raw and indexed profiles.88/// Raw profiles are in host-endian format, and indexed profiles are in89/// little-endian format. So, this function takes an argument indicating the90/// associated endian format to read the binary ids correctly.91static Error92readBinaryIdsInternal(const MemoryBuffer &DataBuffer,93ArrayRef<uint8_t> BinaryIdsBuffer,94std::vector<llvm::object::BuildID> &BinaryIds,95const llvm::endianness Endian) {96using namespace support;9798const uint64_t BinaryIdsSize = BinaryIdsBuffer.size();99const uint8_t *BinaryIdsStart = BinaryIdsBuffer.data();100101if (BinaryIdsSize == 0)102return Error::success();103104const uint8_t *BI = BinaryIdsStart;105const uint8_t *BIEnd = BinaryIdsStart + BinaryIdsSize;106const uint8_t *End =107reinterpret_cast<const uint8_t *>(DataBuffer.getBufferEnd());108109while (BI < BIEnd) {110size_t Remaining = BIEnd - BI;111// There should be enough left to read the binary id length.112if (Remaining < sizeof(uint64_t))113return make_error<InstrProfError>(114instrprof_error::malformed,115"not enough data to read binary id length");116117uint64_t BILen = endian::readNext<uint64_t>(BI, Endian);118if (BILen == 0)119return make_error<InstrProfError>(instrprof_error::malformed,120"binary id length is 0");121122Remaining = BIEnd - BI;123// There should be enough left to read the binary id data.124if (Remaining < alignToPowerOf2(BILen, sizeof(uint64_t)))125return make_error<InstrProfError>(126instrprof_error::malformed, "not enough data to read binary id data");127128// Add binary id to the binary ids list.129BinaryIds.push_back(object::BuildID(BI, BI + BILen));130131// Increment by binary id data length, which aligned to the size of uint64.132BI += alignToPowerOf2(BILen, sizeof(uint64_t));133if (BI > End)134return make_error<InstrProfError>(135instrprof_error::malformed,136"binary id section is greater than buffer size");137}138139return Error::success();140}141142static void printBinaryIdsInternal(raw_ostream &OS,143ArrayRef<llvm::object::BuildID> BinaryIds) {144OS << "Binary IDs: \n";145for (const auto &BI : BinaryIds) {146for (auto I : BI)147OS << format("%02x", I);148OS << "\n";149}150}151152Expected<std::unique_ptr<InstrProfReader>>153InstrProfReader::create(const Twine &Path, vfs::FileSystem &FS,154const InstrProfCorrelator *Correlator,155std::function<void(Error)> Warn) {156// Set up the buffer to read.157auto BufferOrError = setupMemoryBuffer(Path, FS);158if (Error E = BufferOrError.takeError())159return std::move(E);160return InstrProfReader::create(std::move(BufferOrError.get()), Correlator,161Warn);162}163164Expected<std::unique_ptr<InstrProfReader>>165InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer,166const InstrProfCorrelator *Correlator,167std::function<void(Error)> Warn) {168if (Buffer->getBufferSize() == 0)169return make_error<InstrProfError>(instrprof_error::empty_raw_profile);170171std::unique_ptr<InstrProfReader> Result;172// Create the reader.173if (IndexedInstrProfReader::hasFormat(*Buffer))174Result.reset(new IndexedInstrProfReader(std::move(Buffer)));175else if (RawInstrProfReader64::hasFormat(*Buffer))176Result.reset(new RawInstrProfReader64(std::move(Buffer), Correlator, Warn));177else if (RawInstrProfReader32::hasFormat(*Buffer))178Result.reset(new RawInstrProfReader32(std::move(Buffer), Correlator, Warn));179else if (TextInstrProfReader::hasFormat(*Buffer))180Result.reset(new TextInstrProfReader(std::move(Buffer)));181else182return make_error<InstrProfError>(instrprof_error::unrecognized_format);183184// Initialize the reader and return the result.185if (Error E = initializeReader(*Result))186return std::move(E);187188return std::move(Result);189}190191Expected<std::unique_ptr<IndexedInstrProfReader>>192IndexedInstrProfReader::create(const Twine &Path, vfs::FileSystem &FS,193const Twine &RemappingPath) {194// Set up the buffer to read.195auto BufferOrError = setupMemoryBuffer(Path, FS);196if (Error E = BufferOrError.takeError())197return std::move(E);198199// Set up the remapping buffer if requested.200std::unique_ptr<MemoryBuffer> RemappingBuffer;201std::string RemappingPathStr = RemappingPath.str();202if (!RemappingPathStr.empty()) {203auto RemappingBufferOrError = setupMemoryBuffer(RemappingPathStr, FS);204if (Error E = RemappingBufferOrError.takeError())205return std::move(E);206RemappingBuffer = std::move(RemappingBufferOrError.get());207}208209return IndexedInstrProfReader::create(std::move(BufferOrError.get()),210std::move(RemappingBuffer));211}212213Expected<std::unique_ptr<IndexedInstrProfReader>>214IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer,215std::unique_ptr<MemoryBuffer> RemappingBuffer) {216// Create the reader.217if (!IndexedInstrProfReader::hasFormat(*Buffer))218return make_error<InstrProfError>(instrprof_error::bad_magic);219auto Result = std::make_unique<IndexedInstrProfReader>(220std::move(Buffer), std::move(RemappingBuffer));221222// Initialize the reader and return the result.223if (Error E = initializeReader(*Result))224return std::move(E);225226return std::move(Result);227}228229bool TextInstrProfReader::hasFormat(const MemoryBuffer &Buffer) {230// Verify that this really looks like plain ASCII text by checking a231// 'reasonable' number of characters (up to profile magic size).232size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));233StringRef buffer = Buffer.getBufferStart();234return count == 0 ||235std::all_of(buffer.begin(), buffer.begin() + count,236[](char c) { return isPrint(c) || isSpace(c); });237}238239// Read the profile variant flag from the header: ":FE" means this is a FE240// generated profile. ":IR" means this is an IR level profile. Other strings241// with a leading ':' will be reported an error format.242Error TextInstrProfReader::readHeader() {243Symtab.reset(new InstrProfSymtab());244245while (Line->starts_with(":")) {246StringRef Str = Line->substr(1);247if (Str.equals_insensitive("ir"))248ProfileKind |= InstrProfKind::IRInstrumentation;249else if (Str.equals_insensitive("fe"))250ProfileKind |= InstrProfKind::FrontendInstrumentation;251else if (Str.equals_insensitive("csir")) {252ProfileKind |= InstrProfKind::IRInstrumentation;253ProfileKind |= InstrProfKind::ContextSensitive;254} else if (Str.equals_insensitive("entry_first"))255ProfileKind |= InstrProfKind::FunctionEntryInstrumentation;256else if (Str.equals_insensitive("not_entry_first"))257ProfileKind &= ~InstrProfKind::FunctionEntryInstrumentation;258else if (Str.equals_insensitive("single_byte_coverage"))259ProfileKind |= InstrProfKind::SingleByteCoverage;260else if (Str.equals_insensitive("temporal_prof_traces")) {261ProfileKind |= InstrProfKind::TemporalProfile;262if (auto Err = readTemporalProfTraceData())263return error(std::move(Err));264} else265return error(instrprof_error::bad_header);266++Line;267}268return success();269}270271/// Temporal profile trace data is stored in the header immediately after272/// ":temporal_prof_traces". The first integer is the number of traces, the273/// second integer is the stream size, then the following lines are the actual274/// traces which consist of a weight and a comma separated list of function275/// names.276Error TextInstrProfReader::readTemporalProfTraceData() {277if ((++Line).is_at_end())278return error(instrprof_error::eof);279280uint32_t NumTraces;281if (Line->getAsInteger(0, NumTraces))282return error(instrprof_error::malformed);283284if ((++Line).is_at_end())285return error(instrprof_error::eof);286287if (Line->getAsInteger(0, TemporalProfTraceStreamSize))288return error(instrprof_error::malformed);289290for (uint32_t i = 0; i < NumTraces; i++) {291if ((++Line).is_at_end())292return error(instrprof_error::eof);293294TemporalProfTraceTy Trace;295if (Line->getAsInteger(0, Trace.Weight))296return error(instrprof_error::malformed);297298if ((++Line).is_at_end())299return error(instrprof_error::eof);300301SmallVector<StringRef> FuncNames;302Line->split(FuncNames, ",", /*MaxSplit=*/-1, /*KeepEmpty=*/false);303for (auto &FuncName : FuncNames)304Trace.FunctionNameRefs.push_back(305IndexedInstrProf::ComputeHash(FuncName.trim()));306TemporalProfTraces.push_back(std::move(Trace));307}308return success();309}310311Error312TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {313314#define CHECK_LINE_END(Line) \315if (Line.is_at_end()) \316return error(instrprof_error::truncated);317#define READ_NUM(Str, Dst) \318if ((Str).getAsInteger(10, (Dst))) \319return error(instrprof_error::malformed);320#define VP_READ_ADVANCE(Val) \321CHECK_LINE_END(Line); \322uint32_t Val; \323READ_NUM((*Line), (Val)); \324Line++;325326if (Line.is_at_end())327return success();328329uint32_t NumValueKinds;330if (Line->getAsInteger(10, NumValueKinds)) {331// No value profile data332return success();333}334if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)335return error(instrprof_error::malformed,336"number of value kinds is invalid");337Line++;338339for (uint32_t VK = 0; VK < NumValueKinds; VK++) {340VP_READ_ADVANCE(ValueKind);341if (ValueKind > IPVK_Last)342return error(instrprof_error::malformed, "value kind is invalid");343;344VP_READ_ADVANCE(NumValueSites);345if (!NumValueSites)346continue;347348Record.reserveSites(VK, NumValueSites);349for (uint32_t S = 0; S < NumValueSites; S++) {350VP_READ_ADVANCE(NumValueData);351352std::vector<InstrProfValueData> CurrentValues;353for (uint32_t V = 0; V < NumValueData; V++) {354CHECK_LINE_END(Line);355std::pair<StringRef, StringRef> VD = Line->rsplit(':');356uint64_t TakenCount, Value;357if (ValueKind == IPVK_IndirectCallTarget) {358if (InstrProfSymtab::isExternalSymbol(VD.first)) {359Value = 0;360} else {361if (Error E = Symtab->addFuncName(VD.first))362return E;363Value = IndexedInstrProf::ComputeHash(VD.first);364}365} else if (ValueKind == IPVK_VTableTarget) {366if (InstrProfSymtab::isExternalSymbol(VD.first))367Value = 0;368else {369if (Error E = Symtab->addVTableName(VD.first))370return E;371Value = IndexedInstrProf::ComputeHash(VD.first);372}373} else {374READ_NUM(VD.first, Value);375}376READ_NUM(VD.second, TakenCount);377CurrentValues.push_back({Value, TakenCount});378Line++;379}380assert(CurrentValues.size() == NumValueData);381Record.addValueData(ValueKind, S, CurrentValues, nullptr);382}383}384return success();385386#undef CHECK_LINE_END387#undef READ_NUM388#undef VP_READ_ADVANCE389}390391Error TextInstrProfReader::readNextRecord(NamedInstrProfRecord &Record) {392// Skip empty lines and comments.393while (!Line.is_at_end() && (Line->empty() || Line->starts_with("#")))394++Line;395// If we hit EOF while looking for a name, we're done.396if (Line.is_at_end()) {397return error(instrprof_error::eof);398}399400// Read the function name.401Record.Name = *Line++;402if (Error E = Symtab->addFuncName(Record.Name))403return error(std::move(E));404405// Read the function hash.406if (Line.is_at_end())407return error(instrprof_error::truncated);408if ((Line++)->getAsInteger(0, Record.Hash))409return error(instrprof_error::malformed,410"function hash is not a valid integer");411412// Read the number of counters.413uint64_t NumCounters;414if (Line.is_at_end())415return error(instrprof_error::truncated);416if ((Line++)->getAsInteger(10, NumCounters))417return error(instrprof_error::malformed,418"number of counters is not a valid integer");419if (NumCounters == 0)420return error(instrprof_error::malformed, "number of counters is zero");421422// Read each counter and fill our internal storage with the values.423Record.Clear();424Record.Counts.reserve(NumCounters);425for (uint64_t I = 0; I < NumCounters; ++I) {426if (Line.is_at_end())427return error(instrprof_error::truncated);428uint64_t Count;429if ((Line++)->getAsInteger(10, Count))430return error(instrprof_error::malformed, "count is invalid");431Record.Counts.push_back(Count);432}433434// Bitmap byte information is indicated with special character.435if (Line->starts_with("$")) {436Record.BitmapBytes.clear();437// Read the number of bitmap bytes.438uint64_t NumBitmapBytes;439if ((Line++)->drop_front(1).trim().getAsInteger(0, NumBitmapBytes))440return error(instrprof_error::malformed,441"number of bitmap bytes is not a valid integer");442if (NumBitmapBytes != 0) {443// Read each bitmap and fill our internal storage with the values.444Record.BitmapBytes.reserve(NumBitmapBytes);445for (uint8_t I = 0; I < NumBitmapBytes; ++I) {446if (Line.is_at_end())447return error(instrprof_error::truncated);448uint8_t BitmapByte;449if ((Line++)->getAsInteger(0, BitmapByte))450return error(instrprof_error::malformed,451"bitmap byte is not a valid integer");452Record.BitmapBytes.push_back(BitmapByte);453}454}455}456457// Check if value profile data exists and read it if so.458if (Error E = readValueProfileData(Record))459return error(std::move(E));460461return success();462}463464template <class IntPtrT>465InstrProfKind RawInstrProfReader<IntPtrT>::getProfileKind() const {466return getProfileKindFromVersion(Version);467}468469template <class IntPtrT>470SmallVector<TemporalProfTraceTy> &471RawInstrProfReader<IntPtrT>::getTemporalProfTraces(472std::optional<uint64_t> Weight) {473if (TemporalProfTimestamps.empty()) {474assert(TemporalProfTraces.empty());475return TemporalProfTraces;476}477// Sort functions by their timestamps to build the trace.478std::sort(TemporalProfTimestamps.begin(), TemporalProfTimestamps.end());479TemporalProfTraceTy Trace;480if (Weight)481Trace.Weight = *Weight;482for (auto &[TimestampValue, NameRef] : TemporalProfTimestamps)483Trace.FunctionNameRefs.push_back(NameRef);484TemporalProfTraces = {std::move(Trace)};485return TemporalProfTraces;486}487488template <class IntPtrT>489bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {490if (DataBuffer.getBufferSize() < sizeof(uint64_t))491return false;492uint64_t Magic =493*reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());494return RawInstrProf::getMagic<IntPtrT>() == Magic ||495llvm::byteswap(RawInstrProf::getMagic<IntPtrT>()) == Magic;496}497498template <class IntPtrT>499Error RawInstrProfReader<IntPtrT>::readHeader() {500if (!hasFormat(*DataBuffer))501return error(instrprof_error::bad_magic);502if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))503return error(instrprof_error::bad_header);504auto *Header = reinterpret_cast<const RawInstrProf::Header *>(505DataBuffer->getBufferStart());506ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();507return readHeader(*Header);508}509510template <class IntPtrT>511Error RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {512const char *End = DataBuffer->getBufferEnd();513// Skip zero padding between profiles.514while (CurrentPos != End && *CurrentPos == 0)515++CurrentPos;516// If there's nothing left, we're done.517if (CurrentPos == End)518return make_error<InstrProfError>(instrprof_error::eof);519// If there isn't enough space for another header, this is probably just520// garbage at the end of the file.521if (CurrentPos + sizeof(RawInstrProf::Header) > End)522return make_error<InstrProfError>(instrprof_error::malformed,523"not enough space for another header");524// The writer ensures each profile is padded to start at an aligned address.525if (reinterpret_cast<size_t>(CurrentPos) % alignof(uint64_t))526return make_error<InstrProfError>(instrprof_error::malformed,527"insufficient padding");528// The magic should have the same byte order as in the previous header.529uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);530if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))531return make_error<InstrProfError>(instrprof_error::bad_magic);532533// There's another profile to read, so we need to process the header.534auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);535return readHeader(*Header);536}537538template <class IntPtrT>539Error RawInstrProfReader<IntPtrT>::createSymtab(InstrProfSymtab &Symtab) {540if (Error E = Symtab.create(StringRef(NamesStart, NamesEnd - NamesStart),541StringRef(VNamesStart, VNamesEnd - VNamesStart)))542return error(std::move(E));543for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {544const IntPtrT FPtr = swap(I->FunctionPointer);545if (!FPtr)546continue;547Symtab.mapAddress(FPtr, swap(I->NameRef));548}549550if (VTableBegin != nullptr && VTableEnd != nullptr) {551for (const RawInstrProf::VTableProfileData<IntPtrT> *I = VTableBegin;552I != VTableEnd; ++I) {553const IntPtrT VPtr = swap(I->VTablePointer);554if (!VPtr)555continue;556// Map both begin and end address to the name hash, since the instrumented557// address could be somewhere in the middle.558// VPtr is of type uint32_t or uint64_t so 'VPtr + I->VTableSize' marks559// the end of vtable address.560Symtab.mapVTableAddress(VPtr, VPtr + swap(I->VTableSize),561swap(I->VTableNameHash));562}563}564return success();565}566567template <class IntPtrT>568Error RawInstrProfReader<IntPtrT>::readHeader(569const RawInstrProf::Header &Header) {570Version = swap(Header.Version);571if (GET_VERSION(Version) != RawInstrProf::Version)572return error(instrprof_error::raw_profile_version_mismatch,573("Profile uses raw profile format version = " +574Twine(GET_VERSION(Version)) +575"; expected version = " + Twine(RawInstrProf::Version) +576"\nPLEASE update this tool to version in the raw profile, or "577"regenerate raw profile with expected version.")578.str());579580uint64_t BinaryIdSize = swap(Header.BinaryIdsSize);581// Binary id start just after the header if exists.582const uint8_t *BinaryIdStart =583reinterpret_cast<const uint8_t *>(&Header) + sizeof(RawInstrProf::Header);584const uint8_t *BinaryIdEnd = BinaryIdStart + BinaryIdSize;585const uint8_t *BufferEnd = (const uint8_t *)DataBuffer->getBufferEnd();586if (BinaryIdSize % sizeof(uint64_t) || BinaryIdEnd > BufferEnd)587return error(instrprof_error::bad_header);588ArrayRef<uint8_t> BinaryIdsBuffer(BinaryIdStart, BinaryIdSize);589if (!BinaryIdsBuffer.empty()) {590if (Error Err = readBinaryIdsInternal(*DataBuffer, BinaryIdsBuffer,591BinaryIds, getDataEndianness()))592return Err;593}594595CountersDelta = swap(Header.CountersDelta);596BitmapDelta = swap(Header.BitmapDelta);597NamesDelta = swap(Header.NamesDelta);598auto NumData = swap(Header.NumData);599auto PaddingBytesBeforeCounters = swap(Header.PaddingBytesBeforeCounters);600auto CountersSize = swap(Header.NumCounters) * getCounterTypeSize();601auto PaddingBytesAfterCounters = swap(Header.PaddingBytesAfterCounters);602auto NumBitmapBytes = swap(Header.NumBitmapBytes);603auto PaddingBytesAfterBitmapBytes = swap(Header.PaddingBytesAfterBitmapBytes);604auto NamesSize = swap(Header.NamesSize);605auto VTableNameSize = swap(Header.VNamesSize);606auto NumVTables = swap(Header.NumVTables);607ValueKindLast = swap(Header.ValueKindLast);608609auto DataSize = NumData * sizeof(RawInstrProf::ProfileData<IntPtrT>);610auto PaddingBytesAfterNames = getNumPaddingBytes(NamesSize);611auto PaddingBytesAfterVTableNames = getNumPaddingBytes(VTableNameSize);612613auto VTableSectionSize =614NumVTables * sizeof(RawInstrProf::VTableProfileData<IntPtrT>);615auto PaddingBytesAfterVTableProfData = getNumPaddingBytes(VTableSectionSize);616617// Profile data starts after profile header and binary ids if exist.618ptrdiff_t DataOffset = sizeof(RawInstrProf::Header) + BinaryIdSize;619ptrdiff_t CountersOffset = DataOffset + DataSize + PaddingBytesBeforeCounters;620ptrdiff_t BitmapOffset =621CountersOffset + CountersSize + PaddingBytesAfterCounters;622ptrdiff_t NamesOffset =623BitmapOffset + NumBitmapBytes + PaddingBytesAfterBitmapBytes;624ptrdiff_t VTableProfDataOffset =625NamesOffset + NamesSize + PaddingBytesAfterNames;626ptrdiff_t VTableNameOffset = VTableProfDataOffset + VTableSectionSize +627PaddingBytesAfterVTableProfData;628ptrdiff_t ValueDataOffset =629VTableNameOffset + VTableNameSize + PaddingBytesAfterVTableNames;630631auto *Start = reinterpret_cast<const char *>(&Header);632if (Start + ValueDataOffset > DataBuffer->getBufferEnd())633return error(instrprof_error::bad_header);634635if (Correlator) {636// These sizes in the raw file are zero because we constructed them in the637// Correlator.638if (!(DataSize == 0 && NamesSize == 0 && CountersDelta == 0 &&639NamesDelta == 0))640return error(instrprof_error::unexpected_correlation_info);641Data = Correlator->getDataPointer();642DataEnd = Data + Correlator->getDataSize();643NamesStart = Correlator->getNamesPointer();644NamesEnd = NamesStart + Correlator->getNamesSize();645} else {646Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(647Start + DataOffset);648DataEnd = Data + NumData;649VTableBegin =650reinterpret_cast<const RawInstrProf::VTableProfileData<IntPtrT> *>(651Start + VTableProfDataOffset);652VTableEnd = VTableBegin + NumVTables;653NamesStart = Start + NamesOffset;654NamesEnd = NamesStart + NamesSize;655VNamesStart = Start + VTableNameOffset;656VNamesEnd = VNamesStart + VTableNameSize;657}658659CountersStart = Start + CountersOffset;660CountersEnd = CountersStart + CountersSize;661BitmapStart = Start + BitmapOffset;662BitmapEnd = BitmapStart + NumBitmapBytes;663ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset);664665std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>();666if (Error E = createSymtab(*NewSymtab))667return E;668669Symtab = std::move(NewSymtab);670return success();671}672673template <class IntPtrT>674Error RawInstrProfReader<IntPtrT>::readName(NamedInstrProfRecord &Record) {675Record.Name = getName(Data->NameRef);676return success();677}678679template <class IntPtrT>680Error RawInstrProfReader<IntPtrT>::readFuncHash(NamedInstrProfRecord &Record) {681Record.Hash = swap(Data->FuncHash);682return success();683}684685template <class IntPtrT>686Error RawInstrProfReader<IntPtrT>::readRawCounts(687InstrProfRecord &Record) {688uint32_t NumCounters = swap(Data->NumCounters);689if (NumCounters == 0)690return error(instrprof_error::malformed, "number of counters is zero");691692ptrdiff_t CounterBaseOffset = swap(Data->CounterPtr) - CountersDelta;693if (CounterBaseOffset < 0)694return error(695instrprof_error::malformed,696("counter offset " + Twine(CounterBaseOffset) + " is negative").str());697698if (CounterBaseOffset >= CountersEnd - CountersStart)699return error(instrprof_error::malformed,700("counter offset " + Twine(CounterBaseOffset) +701" is greater than the maximum counter offset " +702Twine(CountersEnd - CountersStart - 1))703.str());704705uint64_t MaxNumCounters =706(CountersEnd - (CountersStart + CounterBaseOffset)) /707getCounterTypeSize();708if (NumCounters > MaxNumCounters)709return error(instrprof_error::malformed,710("number of counters " + Twine(NumCounters) +711" is greater than the maximum number of counters " +712Twine(MaxNumCounters))713.str());714715Record.Counts.clear();716Record.Counts.reserve(NumCounters);717for (uint32_t I = 0; I < NumCounters; I++) {718const char *Ptr =719CountersStart + CounterBaseOffset + I * getCounterTypeSize();720if (I == 0 && hasTemporalProfile()) {721uint64_t TimestampValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));722if (TimestampValue != 0 &&723TimestampValue != std::numeric_limits<uint64_t>::max()) {724TemporalProfTimestamps.emplace_back(TimestampValue,725swap(Data->NameRef));726TemporalProfTraceStreamSize = 1;727}728if (hasSingleByteCoverage()) {729// In coverage mode, getCounterTypeSize() returns 1 byte but our730// timestamp field has size uint64_t. Increment I so that the next731// iteration of this for loop points to the byte after the timestamp732// field, i.e., I += 8.733I += 7;734}735continue;736}737if (hasSingleByteCoverage()) {738// A value of zero signifies the block is covered.739Record.Counts.push_back(*Ptr == 0 ? 1 : 0);740} else {741uint64_t CounterValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));742if (CounterValue > MaxCounterValue && Warn)743Warn(make_error<InstrProfError>(744instrprof_error::counter_value_too_large, Twine(CounterValue)));745746Record.Counts.push_back(CounterValue);747}748}749750return success();751}752753template <class IntPtrT>754Error RawInstrProfReader<IntPtrT>::readRawBitmapBytes(InstrProfRecord &Record) {755uint32_t NumBitmapBytes = swap(Data->NumBitmapBytes);756757Record.BitmapBytes.clear();758Record.BitmapBytes.reserve(NumBitmapBytes);759760// It's possible MCDC is either not enabled or only used for some functions761// and not others. So if we record 0 bytes, just move on.762if (NumBitmapBytes == 0)763return success();764765// BitmapDelta decreases as we advance to the next data record.766ptrdiff_t BitmapOffset = swap(Data->BitmapPtr) - BitmapDelta;767if (BitmapOffset < 0)768return error(769instrprof_error::malformed,770("bitmap offset " + Twine(BitmapOffset) + " is negative").str());771772if (BitmapOffset >= BitmapEnd - BitmapStart)773return error(instrprof_error::malformed,774("bitmap offset " + Twine(BitmapOffset) +775" is greater than the maximum bitmap offset " +776Twine(BitmapEnd - BitmapStart - 1))777.str());778779uint64_t MaxNumBitmapBytes =780(BitmapEnd - (BitmapStart + BitmapOffset)) / sizeof(uint8_t);781if (NumBitmapBytes > MaxNumBitmapBytes)782return error(instrprof_error::malformed,783("number of bitmap bytes " + Twine(NumBitmapBytes) +784" is greater than the maximum number of bitmap bytes " +785Twine(MaxNumBitmapBytes))786.str());787788for (uint32_t I = 0; I < NumBitmapBytes; I++) {789const char *Ptr = BitmapStart + BitmapOffset + I;790Record.BitmapBytes.push_back(swap(*Ptr));791}792793return success();794}795796template <class IntPtrT>797Error RawInstrProfReader<IntPtrT>::readValueProfilingData(798InstrProfRecord &Record) {799Record.clearValueData();800CurValueDataSize = 0;801// Need to match the logic in value profile dumper code in compiler-rt:802uint32_t NumValueKinds = 0;803for (uint32_t I = 0; I < IPVK_Last + 1; I++)804NumValueKinds += (Data->NumValueSites[I] != 0);805806if (!NumValueKinds)807return success();808809Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =810ValueProfData::getValueProfData(811ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(),812getDataEndianness());813814if (Error E = VDataPtrOrErr.takeError())815return E;816817// Note that besides deserialization, this also performs the conversion for818// indirect call targets. The function pointers from the raw profile are819// remapped into function name hashes.820VDataPtrOrErr.get()->deserializeTo(Record, Symtab.get());821CurValueDataSize = VDataPtrOrErr.get()->getSize();822return success();823}824825template <class IntPtrT>826Error RawInstrProfReader<IntPtrT>::readNextRecord(NamedInstrProfRecord &Record) {827// Keep reading profiles that consist of only headers and no profile data and828// counters.829while (atEnd())830// At this point, ValueDataStart field points to the next header.831if (Error E = readNextHeader(getNextHeaderPos()))832return error(std::move(E));833834// Read name and set it in Record.835if (Error E = readName(Record))836return error(std::move(E));837838// Read FuncHash and set it in Record.839if (Error E = readFuncHash(Record))840return error(std::move(E));841842// Read raw counts and set Record.843if (Error E = readRawCounts(Record))844return error(std::move(E));845846// Read raw bitmap bytes and set Record.847if (Error E = readRawBitmapBytes(Record))848return error(std::move(E));849850// Read value data and set Record.851if (Error E = readValueProfilingData(Record))852return error(std::move(E));853854// Iterate.855advanceData();856return success();857}858859template <class IntPtrT>860Error RawInstrProfReader<IntPtrT>::readBinaryIds(861std::vector<llvm::object::BuildID> &BinaryIds) {862BinaryIds.insert(BinaryIds.begin(), this->BinaryIds.begin(),863this->BinaryIds.end());864return Error::success();865}866867template <class IntPtrT>868Error RawInstrProfReader<IntPtrT>::printBinaryIds(raw_ostream &OS) {869if (!BinaryIds.empty())870printBinaryIdsInternal(OS, BinaryIds);871return Error::success();872}873874namespace llvm {875876template class RawInstrProfReader<uint32_t>;877template class RawInstrProfReader<uint64_t>;878879} // end namespace llvm880881InstrProfLookupTrait::hash_value_type882InstrProfLookupTrait::ComputeHash(StringRef K) {883return IndexedInstrProf::ComputeHash(HashType, K);884}885886using data_type = InstrProfLookupTrait::data_type;887using offset_type = InstrProfLookupTrait::offset_type;888889bool InstrProfLookupTrait::readValueProfilingData(890const unsigned char *&D, const unsigned char *const End) {891Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =892ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);893894if (VDataPtrOrErr.takeError())895return false;896897VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);898D += VDataPtrOrErr.get()->TotalSize;899900return true;901}902903data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,904offset_type N) {905using namespace support;906907// Check if the data is corrupt. If so, don't try to read it.908if (N % sizeof(uint64_t))909return data_type();910911DataBuffer.clear();912std::vector<uint64_t> CounterBuffer;913std::vector<uint8_t> BitmapByteBuffer;914915const unsigned char *End = D + N;916while (D < End) {917// Read hash.918if (D + sizeof(uint64_t) >= End)919return data_type();920uint64_t Hash = endian::readNext<uint64_t, llvm::endianness::little>(D);921922// Initialize number of counters for GET_VERSION(FormatVersion) == 1.923uint64_t CountsSize = N / sizeof(uint64_t) - 1;924// If format version is different then read the number of counters.925if (GET_VERSION(FormatVersion) != IndexedInstrProf::ProfVersion::Version1) {926if (D + sizeof(uint64_t) > End)927return data_type();928CountsSize = endian::readNext<uint64_t, llvm::endianness::little>(D);929}930// Read counter values.931if (D + CountsSize * sizeof(uint64_t) > End)932return data_type();933934CounterBuffer.clear();935CounterBuffer.reserve(CountsSize);936for (uint64_t J = 0; J < CountsSize; ++J)937CounterBuffer.push_back(938endian::readNext<uint64_t, llvm::endianness::little>(D));939940// Read bitmap bytes for GET_VERSION(FormatVersion) > 10.941if (GET_VERSION(FormatVersion) > IndexedInstrProf::ProfVersion::Version10) {942uint64_t BitmapBytes = 0;943if (D + sizeof(uint64_t) > End)944return data_type();945BitmapBytes = endian::readNext<uint64_t, llvm::endianness::little>(D);946// Read bitmap byte values.947if (D + BitmapBytes * sizeof(uint8_t) > End)948return data_type();949BitmapByteBuffer.clear();950BitmapByteBuffer.reserve(BitmapBytes);951for (uint64_t J = 0; J < BitmapBytes; ++J)952BitmapByteBuffer.push_back(static_cast<uint8_t>(953endian::readNext<uint64_t, llvm::endianness::little>(D)));954}955956DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer),957std::move(BitmapByteBuffer));958959// Read value profiling data.960if (GET_VERSION(FormatVersion) > IndexedInstrProf::ProfVersion::Version2 &&961!readValueProfilingData(D, End)) {962DataBuffer.clear();963return data_type();964}965}966return DataBuffer;967}968969template <typename HashTableImpl>970Error InstrProfReaderIndex<HashTableImpl>::getRecords(971StringRef FuncName, ArrayRef<NamedInstrProfRecord> &Data) {972auto Iter = HashTable->find(FuncName);973if (Iter == HashTable->end())974return make_error<InstrProfError>(instrprof_error::unknown_function);975976Data = (*Iter);977if (Data.empty())978return make_error<InstrProfError>(instrprof_error::malformed,979"profile data is empty");980981return Error::success();982}983984template <typename HashTableImpl>985Error InstrProfReaderIndex<HashTableImpl>::getRecords(986ArrayRef<NamedInstrProfRecord> &Data) {987if (atEnd())988return make_error<InstrProfError>(instrprof_error::eof);989990Data = *RecordIterator;991992if (Data.empty())993return make_error<InstrProfError>(instrprof_error::malformed,994"profile data is empty");995996return Error::success();997}998999template <typename HashTableImpl>1000InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(1001const unsigned char *Buckets, const unsigned char *const Payload,1002const unsigned char *const Base, IndexedInstrProf::HashT HashType,1003uint64_t Version) {1004FormatVersion = Version;1005HashTable.reset(HashTableImpl::Create(1006Buckets, Payload, Base,1007typename HashTableImpl::InfoType(HashType, Version)));1008RecordIterator = HashTable->data_begin();1009}10101011template <typename HashTableImpl>1012InstrProfKind InstrProfReaderIndex<HashTableImpl>::getProfileKind() const {1013return getProfileKindFromVersion(FormatVersion);1014}10151016namespace {1017/// A remapper that does not apply any remappings.1018class InstrProfReaderNullRemapper : public InstrProfReaderRemapper {1019InstrProfReaderIndexBase &Underlying;10201021public:1022InstrProfReaderNullRemapper(InstrProfReaderIndexBase &Underlying)1023: Underlying(Underlying) {}10241025Error getRecords(StringRef FuncName,1026ArrayRef<NamedInstrProfRecord> &Data) override {1027return Underlying.getRecords(FuncName, Data);1028}1029};1030} // namespace10311032/// A remapper that applies remappings based on a symbol remapping file.1033template <typename HashTableImpl>1034class llvm::InstrProfReaderItaniumRemapper1035: public InstrProfReaderRemapper {1036public:1037InstrProfReaderItaniumRemapper(1038std::unique_ptr<MemoryBuffer> RemapBuffer,1039InstrProfReaderIndex<HashTableImpl> &Underlying)1040: RemapBuffer(std::move(RemapBuffer)), Underlying(Underlying) {1041}10421043/// Extract the original function name from a PGO function name.1044static StringRef extractName(StringRef Name) {1045// We can have multiple pieces separated by kGlobalIdentifierDelimiter (1046// semicolon now and colon in older profiles); there can be pieces both1047// before and after the mangled name. Find the first part that starts with1048// '_Z'; we'll assume that's the mangled name we want.1049std::pair<StringRef, StringRef> Parts = {StringRef(), Name};1050while (true) {1051Parts = Parts.second.split(GlobalIdentifierDelimiter);1052if (Parts.first.starts_with("_Z"))1053return Parts.first;1054if (Parts.second.empty())1055return Name;1056}1057}10581059/// Given a mangled name extracted from a PGO function name, and a new1060/// form for that mangled name, reconstitute the name.1061static void reconstituteName(StringRef OrigName, StringRef ExtractedName,1062StringRef Replacement,1063SmallVectorImpl<char> &Out) {1064Out.reserve(OrigName.size() + Replacement.size() - ExtractedName.size());1065Out.insert(Out.end(), OrigName.begin(), ExtractedName.begin());1066Out.insert(Out.end(), Replacement.begin(), Replacement.end());1067Out.insert(Out.end(), ExtractedName.end(), OrigName.end());1068}10691070Error populateRemappings() override {1071if (Error E = Remappings.read(*RemapBuffer))1072return E;1073for (StringRef Name : Underlying.HashTable->keys()) {1074StringRef RealName = extractName(Name);1075if (auto Key = Remappings.insert(RealName)) {1076// FIXME: We could theoretically map the same equivalence class to1077// multiple names in the profile data. If that happens, we should1078// return NamedInstrProfRecords from all of them.1079MappedNames.insert({Key, RealName});1080}1081}1082return Error::success();1083}10841085Error getRecords(StringRef FuncName,1086ArrayRef<NamedInstrProfRecord> &Data) override {1087StringRef RealName = extractName(FuncName);1088if (auto Key = Remappings.lookup(RealName)) {1089StringRef Remapped = MappedNames.lookup(Key);1090if (!Remapped.empty()) {1091if (RealName.begin() == FuncName.begin() &&1092RealName.end() == FuncName.end())1093FuncName = Remapped;1094else {1095// Try rebuilding the name from the given remapping.1096SmallString<256> Reconstituted;1097reconstituteName(FuncName, RealName, Remapped, Reconstituted);1098Error E = Underlying.getRecords(Reconstituted, Data);1099if (!E)1100return E;11011102// If we failed because the name doesn't exist, fall back to asking1103// about the original name.1104if (Error Unhandled = handleErrors(1105std::move(E), [](std::unique_ptr<InstrProfError> Err) {1106return Err->get() == instrprof_error::unknown_function1107? Error::success()1108: Error(std::move(Err));1109}))1110return Unhandled;1111}1112}1113}1114return Underlying.getRecords(FuncName, Data);1115}11161117private:1118/// The memory buffer containing the remapping configuration. Remappings1119/// holds pointers into this buffer.1120std::unique_ptr<MemoryBuffer> RemapBuffer;11211122/// The mangling remapper.1123SymbolRemappingReader Remappings;11241125/// Mapping from mangled name keys to the name used for the key in the1126/// profile data.1127/// FIXME: Can we store a location within the on-disk hash table instead of1128/// redoing lookup?1129DenseMap<SymbolRemappingReader::Key, StringRef> MappedNames;11301131/// The real profile data reader.1132InstrProfReaderIndex<HashTableImpl> &Underlying;1133};11341135bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {1136using namespace support;11371138if (DataBuffer.getBufferSize() < 8)1139return false;1140uint64_t Magic = endian::read<uint64_t, llvm::endianness::little, aligned>(1141DataBuffer.getBufferStart());1142// Verify that it's magical.1143return Magic == IndexedInstrProf::Magic;1144}11451146const unsigned char *1147IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version,1148const unsigned char *Cur, bool UseCS) {1149using namespace IndexedInstrProf;1150using namespace support;11511152if (Version >= IndexedInstrProf::Version4) {1153const IndexedInstrProf::Summary *SummaryInLE =1154reinterpret_cast<const IndexedInstrProf::Summary *>(Cur);1155uint64_t NFields = endian::byte_swap<uint64_t, llvm::endianness::little>(1156SummaryInLE->NumSummaryFields);1157uint64_t NEntries = endian::byte_swap<uint64_t, llvm::endianness::little>(1158SummaryInLE->NumCutoffEntries);1159uint32_t SummarySize =1160IndexedInstrProf::Summary::getSize(NFields, NEntries);1161std::unique_ptr<IndexedInstrProf::Summary> SummaryData =1162IndexedInstrProf::allocSummary(SummarySize);11631164const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE);1165uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get());1166for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)1167Dst[I] = endian::byte_swap<uint64_t, llvm::endianness::little>(Src[I]);11681169SummaryEntryVector DetailedSummary;1170for (unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {1171const IndexedInstrProf::Summary::Entry &Ent = SummaryData->getEntry(I);1172DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,1173Ent.NumBlocks);1174}1175std::unique_ptr<llvm::ProfileSummary> &Summary =1176UseCS ? this->CS_Summary : this->Summary;11771178// initialize InstrProfSummary using the SummaryData from disk.1179Summary = std::make_unique<ProfileSummary>(1180UseCS ? ProfileSummary::PSK_CSInstr : ProfileSummary::PSK_Instr,1181DetailedSummary, SummaryData->get(Summary::TotalBlockCount),1182SummaryData->get(Summary::MaxBlockCount),1183SummaryData->get(Summary::MaxInternalBlockCount),1184SummaryData->get(Summary::MaxFunctionCount),1185SummaryData->get(Summary::TotalNumBlocks),1186SummaryData->get(Summary::TotalNumFunctions));1187return Cur + SummarySize;1188} else {1189// The older versions do not support a profile summary. This just computes1190// an empty summary, which will not result in accurate hot/cold detection.1191// We would need to call addRecord for all NamedInstrProfRecords to get the1192// correct summary. However, this version is old (prior to early 2016) and1193// has not been supporting an accurate summary for several years.1194InstrProfSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);1195Summary = Builder.getSummary();1196return Cur;1197}1198}11991200Error IndexedMemProfReader::deserializeV012(const unsigned char *Start,1201const unsigned char *Ptr,1202uint64_t FirstWord) {1203// The value returned from RecordTableGenerator.Emit.1204const uint64_t RecordTableOffset =1205Version == memprof::Version01206? FirstWord1207: support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1208// The offset in the stream right before invoking1209// FrameTableGenerator.Emit.1210const uint64_t FramePayloadOffset =1211support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1212// The value returned from FrameTableGenerator.Emit.1213const uint64_t FrameTableOffset =1214support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);12151216// The offset in the stream right before invoking1217// CallStackTableGenerator.Emit.1218uint64_t CallStackPayloadOffset = 0;1219// The value returned from CallStackTableGenerator.Emit.1220uint64_t CallStackTableOffset = 0;1221if (Version >= memprof::Version2) {1222CallStackPayloadOffset =1223support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1224CallStackTableOffset =1225support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1226}12271228// Read the schema.1229auto SchemaOr = memprof::readMemProfSchema(Ptr);1230if (!SchemaOr)1231return SchemaOr.takeError();1232Schema = SchemaOr.get();12331234// Now initialize the table reader with a pointer into data buffer.1235MemProfRecordTable.reset(MemProfRecordHashTable::Create(1236/*Buckets=*/Start + RecordTableOffset,1237/*Payload=*/Ptr,1238/*Base=*/Start, memprof::RecordLookupTrait(Version, Schema)));12391240// Initialize the frame table reader with the payload and bucket offsets.1241MemProfFrameTable.reset(MemProfFrameHashTable::Create(1242/*Buckets=*/Start + FrameTableOffset,1243/*Payload=*/Start + FramePayloadOffset,1244/*Base=*/Start));12451246if (Version >= memprof::Version2)1247MemProfCallStackTable.reset(MemProfCallStackHashTable::Create(1248/*Buckets=*/Start + CallStackTableOffset,1249/*Payload=*/Start + CallStackPayloadOffset,1250/*Base=*/Start));12511252return Error::success();1253}12541255Error IndexedMemProfReader::deserializeV3(const unsigned char *Start,1256const unsigned char *Ptr) {1257// The offset in the stream right before invoking1258// CallStackTableGenerator.Emit.1259const uint64_t CallStackPayloadOffset =1260support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1261// The offset in the stream right before invoking RecordTableGenerator.Emit.1262const uint64_t RecordPayloadOffset =1263support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1264// The value returned from RecordTableGenerator.Emit.1265const uint64_t RecordTableOffset =1266support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);12671268// Read the schema.1269auto SchemaOr = memprof::readMemProfSchema(Ptr);1270if (!SchemaOr)1271return SchemaOr.takeError();1272Schema = SchemaOr.get();12731274FrameBase = Ptr;1275CallStackBase = Start + CallStackPayloadOffset;12761277// Now initialize the table reader with a pointer into data buffer.1278MemProfRecordTable.reset(MemProfRecordHashTable::Create(1279/*Buckets=*/Start + RecordTableOffset,1280/*Payload=*/Start + RecordPayloadOffset,1281/*Base=*/Start, memprof::RecordLookupTrait(memprof::Version3, Schema)));12821283return Error::success();1284}12851286Error IndexedMemProfReader::deserialize(const unsigned char *Start,1287uint64_t MemProfOffset) {1288const unsigned char *Ptr = Start + MemProfOffset;12891290// Read the first 64-bit word, which may be RecordTableOffset in1291// memprof::MemProfVersion0 or the MemProf version number in1292// memprof::MemProfVersion1 and above.1293const uint64_t FirstWord =1294support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);12951296if (FirstWord == memprof::Version1 || FirstWord == memprof::Version2 ||1297FirstWord == memprof::Version3) {1298// Everything is good. We can proceed to deserialize the rest.1299Version = static_cast<memprof::IndexedVersion>(FirstWord);1300} else if (FirstWord >= 24) {1301// This is a heuristic/hack to detect memprof::MemProfVersion0,1302// which does not have a version field in the header.1303// In memprof::MemProfVersion0, FirstWord will be RecordTableOffset,1304// which should be at least 24 because of the MemProf header size.1305Version = memprof::Version0;1306} else {1307return make_error<InstrProfError>(1308instrprof_error::unsupported_version,1309formatv("MemProf version {} not supported; "1310"requires version between {} and {}, inclusive",1311FirstWord, memprof::MinimumSupportedVersion,1312memprof::MaximumSupportedVersion));1313}13141315switch (Version) {1316case memprof::Version0:1317case memprof::Version1:1318case memprof::Version2:1319if (Error E = deserializeV012(Start, Ptr, FirstWord))1320return E;1321break;1322case memprof::Version3:1323if (Error E = deserializeV3(Start, Ptr))1324return E;1325break;1326}13271328#ifdef EXPENSIVE_CHECKS1329// Go through all the records and verify that CSId has been correctly1330// populated. Do this only under EXPENSIVE_CHECKS. Otherwise, we1331// would defeat the purpose of OnDiskIterableChainedHashTable.1332// Note that we can compare CSId against actual call stacks only for1333// Version0 and Version1 because IndexedAllocationInfo::CallStack and1334// IndexedMemProfRecord::CallSites are not populated in Version2.1335if (Version <= memprof::Version1)1336for (const auto &Record : MemProfRecordTable->data())1337verifyIndexedMemProfRecord(Record);1338#endif13391340return Error::success();1341}13421343Error IndexedInstrProfReader::readHeader() {1344using namespace support;13451346const unsigned char *Start =1347(const unsigned char *)DataBuffer->getBufferStart();1348const unsigned char *Cur = Start;1349if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)1350return error(instrprof_error::truncated);13511352auto HeaderOr = IndexedInstrProf::Header::readFromBuffer(Start);1353if (!HeaderOr)1354return HeaderOr.takeError();13551356const IndexedInstrProf::Header *Header = &HeaderOr.get();1357Cur += Header->size();13581359Cur = readSummary((IndexedInstrProf::ProfVersion)Header->Version, Cur,1360/* UseCS */ false);1361if (Header->Version & VARIANT_MASK_CSIR_PROF)1362Cur = readSummary((IndexedInstrProf::ProfVersion)Header->Version, Cur,1363/* UseCS */ true);1364// Read the hash type and start offset.1365IndexedInstrProf::HashT HashType =1366static_cast<IndexedInstrProf::HashT>(Header->HashType);1367if (HashType > IndexedInstrProf::HashT::Last)1368return error(instrprof_error::unsupported_hash_type);13691370// The hash table with profile counts comes next.1371auto IndexPtr = std::make_unique<InstrProfReaderIndex<OnDiskHashTableImplV3>>(1372Start + Header->HashOffset, Cur, Start, HashType, Header->Version);13731374// The MemProfOffset field in the header is only valid when the format1375// version is higher than 8 (when it was introduced).1376if (Header->getIndexedProfileVersion() >= 8 &&1377Header->Version & VARIANT_MASK_MEMPROF) {1378if (Error E = MemProfReader.deserialize(Start, Header->MemProfOffset))1379return E;1380}13811382// BinaryIdOffset field in the header is only valid when the format version1383// is higher than 9 (when it was introduced).1384if (Header->getIndexedProfileVersion() >= 9) {1385const unsigned char *Ptr = Start + Header->BinaryIdOffset;1386// Read binary ids size.1387uint64_t BinaryIdsSize =1388support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1389if (BinaryIdsSize % sizeof(uint64_t))1390return error(instrprof_error::bad_header);1391// Set the binary ids start.1392BinaryIdsBuffer = ArrayRef<uint8_t>(Ptr, BinaryIdsSize);1393if (Ptr > (const unsigned char *)DataBuffer->getBufferEnd())1394return make_error<InstrProfError>(instrprof_error::malformed,1395"corrupted binary ids");1396}13971398if (Header->getIndexedProfileVersion() >= 12) {1399const unsigned char *Ptr = Start + Header->VTableNamesOffset;14001401uint64_t CompressedVTableNamesLen =1402support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);14031404// Writer first writes the length of compressed string, and then the actual1405// content.1406const char *VTableNamePtr = (const char *)Ptr;1407if (VTableNamePtr > (const char *)DataBuffer->getBufferEnd())1408return make_error<InstrProfError>(instrprof_error::truncated);14091410VTableName = StringRef(VTableNamePtr, CompressedVTableNamesLen);1411}14121413if (Header->getIndexedProfileVersion() >= 10 &&1414Header->Version & VARIANT_MASK_TEMPORAL_PROF) {1415const unsigned char *Ptr = Start + Header->TemporalProfTracesOffset;1416const auto *PtrEnd = (const unsigned char *)DataBuffer->getBufferEnd();1417// Expect at least two 64 bit fields: NumTraces, and TraceStreamSize1418if (Ptr + 2 * sizeof(uint64_t) > PtrEnd)1419return error(instrprof_error::truncated);1420const uint64_t NumTraces =1421support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1422TemporalProfTraceStreamSize =1423support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1424for (unsigned i = 0; i < NumTraces; i++) {1425// Expect at least two 64 bit fields: Weight and NumFunctions1426if (Ptr + 2 * sizeof(uint64_t) > PtrEnd)1427return error(instrprof_error::truncated);1428TemporalProfTraceTy Trace;1429Trace.Weight =1430support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1431const uint64_t NumFunctions =1432support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1433// Expect at least NumFunctions 64 bit fields1434if (Ptr + NumFunctions * sizeof(uint64_t) > PtrEnd)1435return error(instrprof_error::truncated);1436for (unsigned j = 0; j < NumFunctions; j++) {1437const uint64_t NameRef =1438support::endian::readNext<uint64_t, llvm::endianness::little>(Ptr);1439Trace.FunctionNameRefs.push_back(NameRef);1440}1441TemporalProfTraces.push_back(std::move(Trace));1442}1443}14441445// Load the remapping table now if requested.1446if (RemappingBuffer) {1447Remapper =1448std::make_unique<InstrProfReaderItaniumRemapper<OnDiskHashTableImplV3>>(1449std::move(RemappingBuffer), *IndexPtr);1450if (Error E = Remapper->populateRemappings())1451return E;1452} else {1453Remapper = std::make_unique<InstrProfReaderNullRemapper>(*IndexPtr);1454}1455Index = std::move(IndexPtr);14561457return success();1458}14591460InstrProfSymtab &IndexedInstrProfReader::getSymtab() {1461if (Symtab)1462return *Symtab;14631464auto NewSymtab = std::make_unique<InstrProfSymtab>();14651466if (Error E = NewSymtab->initVTableNamesFromCompressedStrings(VTableName)) {1467auto [ErrCode, Msg] = InstrProfError::take(std::move(E));1468consumeError(error(ErrCode, Msg));1469}14701471// finalizeSymtab is called inside populateSymtab.1472if (Error E = Index->populateSymtab(*NewSymtab)) {1473auto [ErrCode, Msg] = InstrProfError::take(std::move(E));1474consumeError(error(ErrCode, Msg));1475}14761477Symtab = std::move(NewSymtab);1478return *Symtab;1479}14801481Expected<InstrProfRecord> IndexedInstrProfReader::getInstrProfRecord(1482StringRef FuncName, uint64_t FuncHash, StringRef DeprecatedFuncName,1483uint64_t *MismatchedFuncSum) {1484ArrayRef<NamedInstrProfRecord> Data;1485uint64_t FuncSum = 0;1486auto Err = Remapper->getRecords(FuncName, Data);1487if (Err) {1488// If we don't find FuncName, try DeprecatedFuncName to handle profiles1489// built by older compilers.1490auto Err2 =1491handleErrors(std::move(Err), [&](const InstrProfError &IE) -> Error {1492if (IE.get() != instrprof_error::unknown_function)1493return make_error<InstrProfError>(IE);1494if (auto Err = Remapper->getRecords(DeprecatedFuncName, Data))1495return Err;1496return Error::success();1497});1498if (Err2)1499return std::move(Err2);1500}1501// Found it. Look for counters with the right hash.15021503// A flag to indicate if the records are from the same type1504// of profile (i.e cs vs nocs).1505bool CSBitMatch = false;1506auto getFuncSum = [](ArrayRef<uint64_t> Counts) {1507uint64_t ValueSum = 0;1508for (uint64_t CountValue : Counts) {1509if (CountValue == (uint64_t)-1)1510continue;1511// Handle overflow -- if that happens, return max.1512if (std::numeric_limits<uint64_t>::max() - CountValue <= ValueSum)1513return std::numeric_limits<uint64_t>::max();1514ValueSum += CountValue;1515}1516return ValueSum;1517};15181519for (const NamedInstrProfRecord &I : Data) {1520// Check for a match and fill the vector if there is one.1521if (I.Hash == FuncHash)1522return std::move(I);1523if (NamedInstrProfRecord::hasCSFlagInHash(I.Hash) ==1524NamedInstrProfRecord::hasCSFlagInHash(FuncHash)) {1525CSBitMatch = true;1526if (MismatchedFuncSum == nullptr)1527continue;1528FuncSum = std::max(FuncSum, getFuncSum(I.Counts));1529}1530}1531if (CSBitMatch) {1532if (MismatchedFuncSum != nullptr)1533*MismatchedFuncSum = FuncSum;1534return error(instrprof_error::hash_mismatch);1535}1536return error(instrprof_error::unknown_function);1537}15381539static Expected<memprof::MemProfRecord>1540getMemProfRecordV0(const memprof::IndexedMemProfRecord &IndexedRecord,1541MemProfFrameHashTable &MemProfFrameTable) {1542memprof::FrameIdConverter<MemProfFrameHashTable> FrameIdConv(1543MemProfFrameTable);15441545memprof::MemProfRecord Record =1546memprof::MemProfRecord(IndexedRecord, FrameIdConv);15471548// Check that all frame ids were successfully converted to frames.1549if (FrameIdConv.LastUnmappedId) {1550return make_error<InstrProfError>(instrprof_error::hash_mismatch,1551"memprof frame not found for frame id " +1552Twine(*FrameIdConv.LastUnmappedId));1553}15541555return Record;1556}15571558static Expected<memprof::MemProfRecord>1559getMemProfRecordV2(const memprof::IndexedMemProfRecord &IndexedRecord,1560MemProfFrameHashTable &MemProfFrameTable,1561MemProfCallStackHashTable &MemProfCallStackTable) {1562memprof::FrameIdConverter<MemProfFrameHashTable> FrameIdConv(1563MemProfFrameTable);15641565memprof::CallStackIdConverter<MemProfCallStackHashTable> CSIdConv(1566MemProfCallStackTable, FrameIdConv);15671568memprof::MemProfRecord Record = IndexedRecord.toMemProfRecord(CSIdConv);15691570// Check that all call stack ids were successfully converted to call stacks.1571if (CSIdConv.LastUnmappedId) {1572return make_error<InstrProfError>(1573instrprof_error::hash_mismatch,1574"memprof call stack not found for call stack id " +1575Twine(*CSIdConv.LastUnmappedId));1576}15771578// Check that all frame ids were successfully converted to frames.1579if (FrameIdConv.LastUnmappedId) {1580return make_error<InstrProfError>(instrprof_error::hash_mismatch,1581"memprof frame not found for frame id " +1582Twine(*FrameIdConv.LastUnmappedId));1583}15841585return Record;1586}15871588static Expected<memprof::MemProfRecord>1589getMemProfRecordV3(const memprof::IndexedMemProfRecord &IndexedRecord,1590const unsigned char *FrameBase,1591const unsigned char *CallStackBase) {1592memprof::LinearFrameIdConverter FrameIdConv(FrameBase);1593memprof::LinearCallStackIdConverter CSIdConv(CallStackBase, FrameIdConv);1594memprof::MemProfRecord Record = IndexedRecord.toMemProfRecord(CSIdConv);1595return Record;1596}15971598Expected<memprof::MemProfRecord>1599IndexedMemProfReader::getMemProfRecord(const uint64_t FuncNameHash) const {1600// TODO: Add memprof specific errors.1601if (MemProfRecordTable == nullptr)1602return make_error<InstrProfError>(instrprof_error::invalid_prof,1603"no memprof data available in profile");1604auto Iter = MemProfRecordTable->find(FuncNameHash);1605if (Iter == MemProfRecordTable->end())1606return make_error<InstrProfError>(1607instrprof_error::unknown_function,1608"memprof record not found for function hash " + Twine(FuncNameHash));16091610const memprof::IndexedMemProfRecord &IndexedRecord = *Iter;1611switch (Version) {1612case memprof::Version0:1613case memprof::Version1:1614assert(MemProfFrameTable && "MemProfFrameTable must be available");1615assert(!MemProfCallStackTable &&1616"MemProfCallStackTable must not be available");1617return getMemProfRecordV0(IndexedRecord, *MemProfFrameTable);1618case memprof::Version2:1619assert(MemProfFrameTable && "MemProfFrameTable must be available");1620assert(MemProfCallStackTable && "MemProfCallStackTable must be available");1621return getMemProfRecordV2(IndexedRecord, *MemProfFrameTable,1622*MemProfCallStackTable);1623case memprof::Version3:1624assert(!MemProfFrameTable && "MemProfFrameTable must not be available");1625assert(!MemProfCallStackTable &&1626"MemProfCallStackTable must not be available");1627assert(FrameBase && "FrameBase must be available");1628assert(CallStackBase && "CallStackBase must be available");1629return getMemProfRecordV3(IndexedRecord, FrameBase, CallStackBase);1630}16311632return make_error<InstrProfError>(1633instrprof_error::unsupported_version,1634formatv("MemProf version {} not supported; "1635"requires version between {} and {}, inclusive",1636Version, memprof::MinimumSupportedVersion,1637memprof::MaximumSupportedVersion));1638}16391640Error IndexedInstrProfReader::getFunctionCounts(StringRef FuncName,1641uint64_t FuncHash,1642std::vector<uint64_t> &Counts) {1643Expected<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);1644if (Error E = Record.takeError())1645return error(std::move(E));16461647Counts = Record.get().Counts;1648return success();1649}16501651Error IndexedInstrProfReader::getFunctionBitmap(StringRef FuncName,1652uint64_t FuncHash,1653BitVector &Bitmap) {1654Expected<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);1655if (Error E = Record.takeError())1656return error(std::move(E));16571658const auto &BitmapBytes = Record.get().BitmapBytes;1659size_t I = 0, E = BitmapBytes.size();1660Bitmap.resize(E * CHAR_BIT);1661BitVector::apply(1662[&](auto X) {1663using XTy = decltype(X);1664alignas(XTy) uint8_t W[sizeof(X)];1665size_t N = std::min(E - I, sizeof(W));1666std::memset(W, 0, sizeof(W));1667std::memcpy(W, &BitmapBytes[I], N);1668I += N;1669return support::endian::read<XTy, llvm::endianness::little,1670support::aligned>(W);1671},1672Bitmap, Bitmap);1673assert(I == E);16741675return success();1676}16771678Error IndexedInstrProfReader::readNextRecord(NamedInstrProfRecord &Record) {1679ArrayRef<NamedInstrProfRecord> Data;16801681Error E = Index->getRecords(Data);1682if (E)1683return error(std::move(E));16841685Record = Data[RecordIndex++];1686if (RecordIndex >= Data.size()) {1687Index->advanceToNextKey();1688RecordIndex = 0;1689}1690return success();1691}16921693Error IndexedInstrProfReader::readBinaryIds(1694std::vector<llvm::object::BuildID> &BinaryIds) {1695return readBinaryIdsInternal(*DataBuffer, BinaryIdsBuffer, BinaryIds,1696llvm::endianness::little);1697}16981699Error IndexedInstrProfReader::printBinaryIds(raw_ostream &OS) {1700std::vector<llvm::object::BuildID> BinaryIds;1701if (Error E = readBinaryIds(BinaryIds))1702return E;1703printBinaryIdsInternal(OS, BinaryIds);1704return Error::success();1705}17061707void InstrProfReader::accumulateCounts(CountSumOrPercent &Sum, bool IsCS) {1708uint64_t NumFuncs = 0;1709for (const auto &Func : *this) {1710if (isIRLevelProfile()) {1711bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);1712if (FuncIsCS != IsCS)1713continue;1714}1715Func.accumulateCounts(Sum);1716++NumFuncs;1717}1718Sum.NumEntries = NumFuncs;1719}172017211722