14#ifndef LLVM_PROFILEDATA_INSTRPROFREADER_H
15#define LLVM_PROFILEDATA_INSTRPROFREADER_H
53template <
class record_type = NamedInstrProfRecord,
54 class reader_type = InstrProfReader>
64 reader_type *Reader =
nullptr;
84 return Reader ==
RHS.Reader;
87 return Reader !=
RHS.Reader;
97 std::string LastErrorMsg;
174 LastErrorMsg = ErrMsg;
177 return make_error<InstrProfError>(Err, ErrMsg);
182 LastError = IPE.
get();
185 return make_error<InstrProfError>(LastError, LastErrorMsg);
201 return make_error<InstrProfError>(LastError, LastErrorMsg);
213 std::function<
void(
Error)> Warn =
nullptr);
216 std::unique_ptr<MemoryBuffer> Buffer,
221 std::function<
void(
Error)> Warn =
nullptr);
249 std::unique_ptr<MemoryBuffer> DataBuffer;
257 Error readTemporalProfTraceData();
261 : DataBuffer(
std::
move(DataBuffer_)), Line(*DataBuffer,
true,
'#') {}
272 return static_cast<bool>(ProfileKind & InstrProfKind::IRInstrumentation);
276 return static_cast<bool>(ProfileKind & InstrProfKind::ContextSensitive);
280 return static_cast<bool>(ProfileKind &
281 InstrProfKind::FunctionEntryInstrumentation);
285 return static_cast<bool>(ProfileKind &
286 InstrProfKind::LoopEntriesInstrumentation);
290 return static_cast<bool>(ProfileKind & InstrProfKind::SingleByteCoverage);
294 return static_cast<bool>(ProfileKind & InstrProfKind::FunctionEntryOnly);
303 return static_cast<bool>(ProfileKind & InstrProfKind::TemporalProfile);
309 Error readHeader()
override;
327template <
class IntPtrT>
331 std::unique_ptr<MemoryBuffer> DataBuffer;
339 std::unique_ptr<InstrProfCorrelator> BIDFetcherCorrelator;
344 std::vector<std::pair<uint64_t, uint64_t>> TemporalProfTimestamps;
345 bool ShouldSwapBytes;
357 const char *CountersStart;
358 const char *CountersEnd;
359 const char *BitmapStart;
360 const char *BitmapEnd;
361 const char *NamesStart;
362 const char *NamesEnd;
363 const char *VNamesStart =
nullptr;
364 const char *VNamesEnd =
nullptr;
370 std::vector<llvm::object::BuildID> BinaryIds;
372 std::function<void(
Error)> Warn;
375 static const uint64_t MaxCounterValue = (1ULL << 56);
379 std::unique_ptr<MemoryBuffer> DataBuffer,
383 std::function<
void(
Error)> Warn)
384 : DataBuffer(
std::
move(DataBuffer)),
387 BIDFetcher(BIDFetcher),
388 BIDFetcherCorrelatorKind(BIDFetcherCorrelatorKind), Warn(Warn) {}
402 return (Version & VARIANT_MASK_IR_PROF) != 0;
406 return (Version & VARIANT_MASK_CSIR_PROF) != 0;
410 return (Version & VARIANT_MASK_INSTR_ENTRY) != 0;
414 return (Version & VARIANT_MASK_INSTR_LOOP_ENTRIES) != 0;
418 return (Version & VARIANT_MASK_BYTE_COVERAGE) != 0;
422 return (Version & VARIANT_MASK_FUNCTION_ENTRY_ONLY) != 0;
427 assert(!(Version & VARIANT_MASK_MEMPROF));
432 return (Version & VARIANT_MASK_TEMPORAL_PROF) != 0;
447 Error createSymtab(InstrProfSymtab &
Symtab);
448 Error readNextHeader(
const char *CurrentPos);
449 Error
readHeader(
const RawInstrProf::Header &Header);
451 template <
class IntT> IntT swap(IntT
Int)
const {
456 if (!ShouldSwapBytes)
468 Error readName(NamedInstrProfRecord &Record);
469 Error readFuncHash(NamedInstrProfRecord &Record);
470 Error readRawCounts(InstrProfRecord &Record);
471 Error readRawBitmapBytes(InstrProfRecord &Record);
472 Error readValueProfilingData(InstrProfRecord &Record);
473 bool atEnd()
const {
return Data == DataEnd; }
477 if (!Correlator && !BIDFetcherCorrelator) {
483 CountersDelta -=
sizeof(*Data);
484 BitmapDelta -=
sizeof(*Data);
487 ValueDataStart += CurValueDataSize;
490 const char *getNextHeaderPos()
const {
492 return (
const char *)ValueDataStart;
495 StringRef getName(
uint64_t NameRef)
const {
496 return Symtab->getFuncOrVarName(swap(NameRef));
499 int getCounterTypeSize()
const {
507namespace IndexedInstrProf {
516 std::vector<NamedInstrProfRecord> DataBuffer;
518 unsigned FormatVersion;
526 : HashType(HashType), FormatVersion(FormatVersion) {}
541 static std::pair<offset_type, offset_type>
543 using namespace support;
546 endian::readNext<offset_type, llvm::endianness::little>(
D);
548 endian::readNext<offset_type, llvm::endianness::little>(
D);
549 return std::make_pair(KeyLen, DataLen);
557 const unsigned char *
const End);
563 ValueProfDataEndianness = Endianness;
603template <
typename HashTableImpl>
606template <
typename HashTableImpl>
609 std::unique_ptr<HashTableImpl> HashTable;
610 typename HashTableImpl::data_iterator RecordIterator;
617 const unsigned char *
const Payload,
618 const unsigned char *
const Base,
628 return RecordIterator == HashTable->data_end();
632 HashTable->getInfoObj().setValueProfDataEndianness(Endianness);
638 return (FormatVersion & VARIANT_MASK_IR_PROF) != 0;
642 return (FormatVersion & VARIANT_MASK_CSIR_PROF) != 0;
646 return (FormatVersion & VARIANT_MASK_INSTR_ENTRY) != 0;
650 return (FormatVersion & VARIANT_MASK_INSTR_LOOP_ENTRIES) != 0;
654 return (FormatVersion & VARIANT_MASK_BYTE_COVERAGE) != 0;
658 return (FormatVersion & VARIANT_MASK_FUNCTION_ENTRY_ONLY) != 0;
662 return (FormatVersion & VARIANT_MASK_MEMPROF) != 0;
666 return (FormatVersion & VARIANT_MASK_TEMPORAL_PROF) != 0;
678 return Symtab.
create(HashTable->keys());
697 std::unique_ptr<memprof::MemProfSummary> MemProfSum;
701 std::unique_ptr<MemProfRecordHashTable> MemProfRecordTable;
703 std::unique_ptr<MemProfFrameHashTable> MemProfFrameTable;
705 std::unique_ptr<MemProfCallStackHashTable> MemProfCallStackTable;
707 const unsigned char *FrameBase =
nullptr;
709 const unsigned char *CallStackBase =
nullptr;
711 unsigned RadixTreeSize = 0;
713 std::unique_ptr<memprof::DataAccessProfData> DataAccessProfileData;
715 Error deserializeV2(
const unsigned char *Start,
const unsigned char *
Ptr);
716 Error deserializeRadixTreeBased(
const unsigned char *Start,
717 const unsigned char *
Ptr,
734 return DataAccessProfileData.get();
747 std::unique_ptr<MemoryBuffer> DataBuffer;
749 std::unique_ptr<MemoryBuffer> RemappingBuffer;
751 std::unique_ptr<InstrProfReaderIndexBase>
Index;
753 std::unique_ptr<InstrProfReaderRemapper> Remapper;
755 std::unique_ptr<ProfileSummary> Summary;
757 std::unique_ptr<ProfileSummary> CS_Summary;
767 unsigned RecordIndex = 0;
773 const unsigned char *Cur,
bool UseCS);
777 std::unique_ptr<MemoryBuffer> DataBuffer,
778 std::unique_ptr<MemoryBuffer> RemappingBuffer =
nullptr)
779 : DataBuffer(
std::
move(DataBuffer)),
780 RemappingBuffer(
std::
move(RemappingBuffer)) {}
788 return Index->hasCSIRLevelProfile();
792 return Index->instrEntryBBEnabled();
796 return Index->instrLoopEntriesEnabled();
800 return Index->hasSingleByteCoverage();
808 return Index->hasTemporalProfile();
814 return Index->getProfileKind();
821 Error readHeader()
override;
835 uint64_t *MismatchedFuncSum =
nullptr);
854 std::vector<uint64_t> &Counts);
864 assert(CS_Summary &&
"No context sensitive profile summary");
865 return CS_Summary->getMaxFunctionCount();
867 assert(Summary &&
"No profile summary");
868 return Summary->getMaxFunctionCount();
875 const Twine &RemappingPath =
"");
878 create(std::unique_ptr<MemoryBuffer> Buffer,
879 std::unique_ptr<MemoryBuffer> RemappingBuffer =
nullptr);
883 Index->setValueProfDataEndianness(Endianness);
895 assert(CS_Summary &&
"No context sensitive summary");
898 assert(Summary &&
"No profile summary");
914 Error readBinaryIds(std::vector<llvm::object::BuildID> &BinaryIds)
override;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a library for handling Build IDs and using them to find debug info.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
InstrProfLookupTrait::offset_type offset_type
InstrProfLookupTrait::data_type data_type
Defines facilities for reading and writing on-disk hash tables.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Reader for the indexed binary instrprof format.
uint64_t getVersion() const override
Return the profile version.
IndexedInstrProfReader(const IndexedInstrProfReader &)=delete
bool hasTemporalProfile() const override
Return true if this has a temporal profile.
Expected< memprof::MemProfRecord > getMemProfRecord(uint64_t FuncNameHash)
Return the memprof record for the function identified by llvm::md5(Name).
bool hasSingleByteCoverage() const override
Return true if the profile has single byte counters representing coverage.
bool instrLoopEntriesEnabled() const override
Return true if the profile instruments all loop entries.
memprof::MemProfSummary * getMemProfSummary() const
Return the MemProf summary. Will be null if unavailable (version < 4).
ProfileSummary & getSummary(bool UseCS)
Return the profile summary.
bool hasMemoryProfile() const override
Return true if profile includes a memory profile.
bool functionEntryOnly() const override
Return true if the profile only instruments function entries.
uint64_t getMaximumFunctionCount(bool UseCS)
Return the maximum of all known function counts.
DenseMap< uint64_t, SmallVector< memprof::CallEdgeTy, 0 > > getMemProfCallerCalleePairs()
InstrProfKind getProfileKind() const override
Returns a BitsetEnum describing the attributes of the indexed instr profile.
void setValueProfDataEndianness(llvm::endianness Endianness)
memprof::DataAccessProfData * getDataAccessProfileData() const
Returns non-owned pointer to the data access profile data.
memprof::AllMemProfData getAllMemProfData() const
IndexedInstrProfReader(std::unique_ptr< MemoryBuffer > DataBuffer, std::unique_ptr< MemoryBuffer > RemappingBuffer=nullptr)
bool hasCSIRLevelProfile() const override
IndexedInstrProfReader & operator=(const IndexedInstrProfReader &)=delete
bool instrEntryBBEnabled() const override
bool isIRLevelProfile() const override
LLVM_ABI Error deserialize(const unsigned char *Start, uint64_t MemProfOffset)
IndexedMemProfReader()=default
memprof::MemProfSummary * getSummary() const
LLVM_ABI memprof::DataAccessProfData * getDataAccessProfileData() const
LLVM_ABI memprof::AllMemProfData getAllMemProfData() const
LLVM_ABI Expected< memprof::MemProfRecord > getMemProfRecord(const uint64_t FuncNameHash) const
LLVM_ABI DenseMap< uint64_t, SmallVector< memprof::CallEdgeTy, 0 > > getMemProfCallerCalleePairs() const
InstrProfCorrelatorImpl - A child of InstrProfCorrelator with a template pointer type so that the Pro...
InstrProfCorrelator - A base class used to create raw instrumentation data to their functions.
ProfCorrelatorKind
Indicate if we should use the debug info or profile metadata sections to correlate.
static std::pair< instrprof_error, std::string > take(Error E)
Consume an Error and return the raw enum value contained within it, and the optional error message.
const std::string & getMessage() const
instrprof_error get() const
A file format agnostic iterator over profiling data.
bool operator==(const InstrProfIterator &RHS) const
InstrProfIterator(reader_type *Reader)
InstrProfIterator & operator++()
bool operator!=(const InstrProfIterator &RHS) const
value_type * operator->()
std::ptrdiff_t difference_type
std::input_iterator_tag iterator_category
InstrProfIterator()=default
Trait for lookups into the on-disk hash table for the binary instrprof format.
InstrProfLookupTrait(IndexedInstrProf::HashT HashType, unsigned FormatVersion)
void setValueProfDataEndianness(llvm::endianness Endianness)
StringRef ReadKey(const unsigned char *D, offset_type N)
static std::pair< offset_type, offset_type > ReadKeyDataLength(const unsigned char *&D)
static StringRef GetExternalKey(StringRef K)
LLVM_ABI data_type ReadData(StringRef K, const unsigned char *D, offset_type N)
LLVM_ABI bool readValueProfilingData(const unsigned char *&D, const unsigned char *const End)
LLVM_ABI hash_value_type ComputeHash(StringRef K)
static bool EqualKey(StringRef A, StringRef B)
static StringRef GetInternalKey(StringRef K)
Error populateSymtab(InstrProfSymtab &Symtab) override
bool hasSingleByteCoverage() const override
void advanceToNextKey() override
bool hasCSIRLevelProfile() const override
void setValueProfDataEndianness(llvm::endianness Endianness) override
InstrProfKind getProfileKind() const override
Error getRecords(ArrayRef< NamedInstrProfRecord > &Data) override
bool functionEntryOnly() const override
~InstrProfReaderIndex() override=default
bool instrLoopEntriesEnabled() const override
uint64_t getVersion() const override
bool isIRLevelProfile() const override
bool hasMemoryProfile() const override
bool hasTemporalProfile() const override
bool instrEntryBBEnabled() const override
bool atEnd() const override
A remapper that applies remappings based on a symbol remapping file.
Name matcher supporting fuzzy matching of symbol names to names in profiles.
virtual Error getRecords(StringRef FuncName, ArrayRef< NamedInstrProfRecord > &Data)=0
virtual ~InstrProfReaderRemapper()=default
virtual Error populateRemappings()
Base class and interface for reading profiling data of any known instrprof format.
InstrProfIterator begin()
Iterator over profile data.
virtual bool instrEntryBBEnabled() const =0
virtual Error readNextRecord(NamedInstrProfRecord &Record)=0
Read a single record.
virtual Error readBinaryIds(std::vector< llvm::object::BuildID > &BinaryIds)
Read a list of binary ids.
virtual bool functionEntryOnly() const =0
Return true if the profile only instruments function entries.
std::unique_ptr< InstrProfSymtab > Symtab
Error getError()
Get the current error.
virtual InstrProfSymtab & getSymtab()=0
Return the PGO symtab.
InstrProfReader()=default
virtual bool hasSingleByteCoverage() const =0
Return true if the profile has single byte counters representing coverage.
virtual bool hasTemporalProfile() const =0
Return true if this has a temporal profile.
Error success()
Clear the current error and return a successful one.
bool hasError()
Return true if the reader encountered an error reading profiling data.
virtual InstrProfKind getProfileKind() const =0
Returns a BitsetEnum describing the attributes of the profile.
SmallVector< TemporalProfTraceTy > TemporalProfTraces
A list of temporal profile traces.
uint64_t TemporalProfTraceStreamSize
The total number of temporal profile traces seen.
virtual Error printBinaryIds(raw_ostream &OS)
Print binary ids.
uint64_t getTemporalProfTraceStreamSize()
virtual uint64_t getVersion() const =0
Return the profile version.
virtual bool hasMemoryProfile() const =0
Return true if profile includes a memory profile.
virtual bool instrLoopEntriesEnabled() const =0
Return true if the profile instruments all loop entries.
virtual SmallVector< TemporalProfTraceTy > & getTemporalProfTraces(std::optional< uint64_t > Weight={})
virtual bool hasCSIRLevelProfile() const =0
virtual bool isIRLevelProfile() const =0
virtual ~InstrProfReader()=default
virtual Error readHeader()=0
Read the header. Required before reading first record.
Error error(instrprof_error Err, const std::string &ErrMsg="")
Set the current error and return same.
LLVM_ABI void accumulateCounts(CountSumOrPercent &Sum, bool IsCS)
Compute the sum of counts and return in Sum.
static LLVM_ABI Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const InstrProfCorrelator *Correlator=nullptr, const object::BuildIDFetcher *BIDFetcher=nullptr, const InstrProfCorrelator::ProfCorrelatorKind BIDFetcherCorrelatorKind=InstrProfCorrelator::ProfCorrelatorKind::NONE, std::function< void(Error)> Warn=nullptr)
Factory method to create an appropriately typed reader for the given instrprof file.
bool isEOF()
Return true if the reader has finished reading the profile data.
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
LLVM_ABI Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Provides lookup and iteration over an on disk hash table.
Reader for the raw instrprof binary format from runtime.
bool functionEntryOnly() const override
Return true if the profile only instruments function entries.
RawInstrProfReader(std::unique_ptr< MemoryBuffer > DataBuffer, const InstrProfCorrelator *Correlator, const object::BuildIDFetcher *BIDFetcher, const InstrProfCorrelator::ProfCorrelatorKind BIDFetcherCorrelatorKind, std::function< void(Error)> Warn)
Error readHeader() override
Read the header. Required before reading first record.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
Error printBinaryIds(raw_ostream &OS) override
Print binary ids.
static bool hasFormat(const MemoryBuffer &DataBuffer)
RawInstrProfReader & operator=(const RawInstrProfReader &)=delete
bool hasSingleByteCoverage() const override
Return true if the profile has single byte counters representing coverage.
bool isIRLevelProfile() const override
InstrProfKind getProfileKind() const override
Returns a BitsetEnum describing the attributes of the raw instr profile.
bool hasMemoryProfile() const override
Return true if profile includes a memory profile.
bool instrLoopEntriesEnabled() const override
Return true if the profile instruments all loop entries.
InstrProfSymtab & getSymtab() override
Return the PGO symtab.
Error readBinaryIds(std::vector< llvm::object::BuildID > &BinaryIds) override
Read a list of binary ids.
bool hasTemporalProfile() const override
Return true if this has a temporal profile.
bool instrEntryBBEnabled() const override
uint64_t getVersion() const override
Return the profile version.
SmallVector< TemporalProfTraceTy > & getTemporalProfTraces(std::optional< uint64_t > Weight={}) override
RawInstrProfReader(const RawInstrProfReader &)=delete
bool hasCSIRLevelProfile() const override
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Reader for the simple text based instrprof format.
bool isIRLevelProfile() const override
uint64_t getVersion() const override
Return the profile version.
TextInstrProfReader(std::unique_ptr< MemoryBuffer > DataBuffer_)
bool hasSingleByteCoverage() const override
Return true if the profile has single byte counters representing coverage.
TextInstrProfReader(const TextInstrProfReader &)=delete
bool hasMemoryProfile() const override
Return true if profile includes a memory profile.
bool hasCSIRLevelProfile() const override
InstrProfSymtab & getSymtab() override
Return the PGO symtab.
bool instrEntryBBEnabled() const override
bool functionEntryOnly() const override
Return true if the profile only instruments function entries.
InstrProfKind getProfileKind() const override
Returns a BitsetEnum describing the attributes of the profile.
bool hasTemporalProfile() const override
Return true if this has a temporal profile.
TextInstrProfReader & operator=(const TextInstrProfReader &)=delete
bool instrLoopEntriesEnabled() const override
Return true if the profile instruments all loop entries.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
A forward iterator which reads text lines from a buffer.
Encapsulates the data access profile data and the methods to operate on it.
BuildIDFetcher searches local cache directories for debug info.
This class implements an extremely fast bulk output stream that can only output to a stream.
The virtual file system interface.
constexpr uint64_t MinimumSupportedVersion
This is an optimization pass for GlobalISel generic memory operations.
constexpr T byteswap(T V) noexcept
Reverses the bytes in the given integer value V.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
auto dyn_cast_or_null(const Y &Val)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
InstrProfKind
An enum describing the attributes of an instrumented profile.
Implement std::hash so that hash_code can be used in STL containers.
virtual Error populateSymtab(InstrProfSymtab &)=0
virtual Error getRecords(ArrayRef< NamedInstrProfRecord > &Data)=0
virtual ~InstrProfReaderIndexBase()=default
virtual bool instrLoopEntriesEnabled() const =0
virtual InstrProfKind getProfileKind() const =0
virtual bool hasTemporalProfile() const =0
virtual bool isIRLevelProfile() const =0
virtual void advanceToNextKey()=0
virtual bool hasMemoryProfile() const =0
virtual bool hasCSIRLevelProfile() const =0
virtual uint64_t getVersion() const =0
virtual bool atEnd() const =0
virtual bool instrEntryBBEnabled() const =0
virtual Error getRecords(StringRef FuncName, ArrayRef< NamedInstrProfRecord > &Data)=0
virtual void setValueProfDataEndianness(llvm::endianness Endianness)=0
virtual bool functionEntryOnly() const =0
virtual bool hasSingleByteCoverage() const =0
Profiling information for a single function.