256#ifndef LLVM_PROFILEDATA_SAMPLEPROFREADER_H
257#define LLVM_PROFILEDATA_SAMPLEPROFREADER_H
282#include <system_error>
304 std::unique_ptr<SymbolRemappingReader> SRR,
307 assert(Remappings &&
"Remappings cannot be nullptr");
333 return Remappings->lookup(FunctionName);
342 std::unique_ptr<MemoryBuffer> Buffer;
343 std::unique_ptr<SymbolRemappingReader> Remappings;
352 bool RemappingApplied =
false;
391 FunctionId, std::ptrdiff_t,
392 const FunctionId *, FunctionId> {
396 : Table(Table), Idx(Idx) {}
399 return Table ==
RHS.Table && Idx ==
RHS.Idx;
409 "Dereferencing invalid or out-of-bounds iterator");
410 return (*Table)[Idx];
427 virtual size_t size()
const = 0;
434 "getEytzingerSpan is exclusively supported for Eytzinger layout");
447 mutable std::optional<DenseSet<uint64_t>>
GUIDSet;
450 return F.getHashCode();
453 return F.stringRef();
456 template <
typename SetT,
typename RangeT,
typename ProjT = llvm::
identity>
458 const RangeT &
Range, ProjT Proj = ProjT()) {
461 Set->reserve(
Range.size());
462 for (
const auto &Item :
Range)
463 Set->insert(Proj(Item));
470 const uint8_t *Start =
nullptr;
475 : Start(Start), Size(Size) {}
477 size_t size()
const override {
return Size; }
480 assert(Idx < Size &&
"Index out of bounds");
494 std::vector<FunctionId> Vec;
495 mutable std::optional<DenseSet<StringRef>> NameSet;
503 size_t size()
const override {
return Vec.size(); }
506 assert(Idx < Vec.size() &&
"Index out of bounds");
516 std::vector<FunctionId> Vec;
524 size_t size()
const override {
return Vec.size(); }
527 assert(Idx < Vec.size() &&
"Index out of bounds");
534 std::array<EytzingerTableSpan<support::ulittle64_t>,
540 size_t NumNested,
size_t NumFlat,
542 : Array(
Data, NumNested + NumFlat + NumInlinees),
543 Spans{{{
Data, NumNested},
544 {
Data + NumNested, NumFlat},
545 {
Data + NumNested + NumFlat, NumInlinees}}} {}
547 size_t size()
const override {
return Array.size(); }
561 [&](
const auto &Span) {
return Span.contains(GUID); });
594 if (std::error_code EC =
readImpl())
653 Fname = R->second.stringRef();
661 if (
auto NameInProfile =
Remapper->lookUpNameInProfile(Fname)) {
733 std::error_code EC =
read();
784 static std::unique_ptr<ProfileSummary>
786 return std::move(Reader.
Summary);
800 std::unique_ptr<SampleProfileReaderItaniumRemapper>
Remapper;
884 std::error_code readImpl()
override;
895 std::list<SampleContextFrameVector> CSNameTable;
905 std::error_code readHeader()
override;
908 std::error_code readImpl()
override;
937 template <
typename T>
ErrorOr<T> readNumber();
941 template <
typename T>
ErrorOr<T> readUnencodedNumber();
955 std::error_code readFuncProfile(
const uint8_t *Start);
956 std::error_code readFuncProfile(
const uint8_t *Start,
963 std::error_code readLBRProfile(
FunctionSamples &FProfile,
bool IsNested);
968 std::error_code readMagicIdent();
971 std::error_code readSummary();
974 std::error_code readNameTable();
993 std::error_code readVTableTypeCountMap(
TypeCountMap &M);
1020 std::error_code readSummaryEntry(std::vector<ProfileSummaryEntry> &Entries);
1021 virtual std::error_code verifySPMagic(
uint64_t Magic) = 0;
1026 std::error_code verifySPMagic(
uint64_t Magic)
override;
1071 size_t InitialCapacity = 0)
1073 InMemoryTable.reserve(InitialCapacity);
1080 FuncOffsetSpan(FuncOffsetSpan) {}
1085 "Cannot insert into a non-in-memory offset table");
1086 InMemoryTable[GUID] =
Offset;
1093 if (std::optional<size_t> Idx = NameSpan.findIndex(GUID)) {
1094 uint32_t RelOffset = FuncOffsetSpan[*Idx];
1095 if (RelOffset != UINT32_MAX)
1098 return std::nullopt;
1100 auto Iter = InMemoryTable.find(GUID);
1101 if (Iter != InMemoryTable.end())
1102 return Iter->second;
1103 return std::nullopt;
1110 "Cannot call getFuncOffsets() on non-Eytzinger table");
1111 return FuncOffsetSpan;
1116 "Cannot call getExpectedSize() on non-Eytzinger table");
1117 return NameSpan.size();
1151 std::error_code decompressSection(
const uint8_t *SecStart,
1153 const uint8_t *&DecompressBuf,
1173 bool IsEytzinger =
false);
1214 std::error_code readImpl()
override;
1231 bool collectFuncsFromModule()
override;
1249 std::error_code verifySPMagic(
uint64_t Magic)
override;
1250 std::error_code readCustomSection(
const SecHdrTableEntry &Entry)
override {
1287 std::error_code readHeader()
override;
1290 std::error_code readImpl()
override;
1296 std::error_code readNameTable();
1297 std::error_code readOneFunctionProfile(
const InlineCallStack &InlineStack,
1299 std::error_code readFunctionProfiles();
1300 std::error_code skipNextWord();
1301 template <
typename T>
ErrorOr<T> readNumber();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Provides ErrorOr<T> smart pointer.
This file defines the EytzingerTableSpan class, a non-owning view of a buffer formatted as a complete...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static Error readString(StringRef Buffer, const char *&Src, size_t MaxSize, StringRef &Val, Twine Desc)
Read a null-terminated string at the position Src from Buffer, with maximum byte size of MaxSize (inc...
static constexpr StringLiteral Filename
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains library features backported from future STL versions.
This file defines the SmallVector class.
StringSet - A set-like wrapper for the StringMap.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Implements a dense probed hash-table based set.
Diagnostic information for the sample profiler.
Represents either an error or a value T.
Tagged union holding either a T or a Error.
Non-owning view of a buffer formatted as a complete binary search tree in Eytzinger (breadth-first) o...
GCOVBuffer - A wrapper around MemoryBuffer to provide GCOV specific read operations.
This is an important class for using LLVM in a threaded context.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
A Module instance is used to store all the information related to an LLVM module.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
std::pair< iterator, bool > insert(const ValueT &V)
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
This class represents a function that is read from a sample profile.
Representation of the samples collected for a function.
static LLVM_ABI std::atomic< bool > UseMD5
Whether the profile uses MD5 to represent string.
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
This class is a wrapper to associative container MapT<KeyT, ValueT> using the hash value of the origi...
SampleProfileFuncOffsetTable()=delete
std::optional< uint64_t > lookup(uint64_t GUID) const
Query the offset table for the profile offset associated with the given GUID.
SampleProfileFuncOffsetTable & operator=(SampleProfileFuncOffsetTable &&)=delete
ArrayRef< support::ulittle32_t > getFuncOffsets() const
Direct read-only array (ArrayRef) of function offsets aligned parallel to the corresponding Eytzinger...
SampleProfileFuncOffsetTable(EytzingerModeT, EytzingerTableSpan< support::ulittle64_t > NameSpan, ArrayRef< support::ulittle32_t > FuncOffsetSpan)
void insert(uint64_t GUID, uint64_t Offset)
Insert a function GUID and its profile offset into the in-memory map.
SampleProfileFuncOffsetTable(InMemoryModeT, size_t InitialCapacity=0)
size_t getExpectedSize() const
SampleProfileFuncOffsetTable(const SampleProfileFuncOffsetTable &)=delete
SampleProfileFuncOffsetTable & operator=(const SampleProfileFuncOffsetTable &)=delete
SampleProfileFuncOffsetTable(SampleProfileFuncOffsetTable &&)=delete
This class provides operator overloads to the map container using MD5 as the key type,...
const uint8_t * Data
Points to the current location in the buffer.
std::unique_ptr< SampleProfileNameTable > NameTable
Function name table.
const uint64_t * MD5SampleContextStart
The starting address of the table of MD5 values of sample contexts.
bool contains(StringRef Key) const override
std::vector< SampleContextFrameVector > CSNameTable
CSNameTable is used to save full context vectors.
bool contains(uint64_t GUID) const override
SampleProfileReaderBinary(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_None)
std::vector< uint64_t > MD5SampleContextTable
Table to cache MD5 values of sample contexts corresponding to readSampleContextFromTable(),...
llvm::iterator_range< SampleProfileNameTable::iterator > getNameTable() const override
It includes all the names that have samples either in outline instance or inline instance.
const uint8_t * End
Points to the end of the buffer.
std::vector< SecHdrTableEntry > SecHdrTable
std::error_code readNameTableSecEytzinger(bool IsMD5, bool FixedLengthMD5)
std::error_code readCSNameTableSec()
std::error_code readEytzingerFuncOffsetTable(bool IsNested)
virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry)=0
std::error_code readFuncMetadata(DenseSet< FunctionSamples * > &Profiles)
std::vector< std::pair< SampleContext, uint64_t > > FuncOffsetList
The list version of FuncOffsetTable.
DenseSet< StringRef > FuncsToUse
The set containing the functions to use when compiling a module.
std::unique_ptr< ProfileSymbolList > ProfSymList
std::optional< SampleProfileFuncOffsetTable > FuncOffsetTable
The table mapping from a function context's MD5 to the offset of its FunctionSample towards file star...
std::error_code readNameTableSec(bool IsMD5, bool FixedLengthMD5, bool IsEytzinger=false)
std::error_code readSecHdrTable()
std::error_code readFuncProfiles()
bool useFuncOffsetList() const
Determine which container readFuncOffsetTable() should populate, the list FuncOffsetList or the map F...
std::error_code readSecHdrTableEntry(uint64_t Idx)
std::unique_ptr< ProfileSymbolList > getProfileSymbolList() override
virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry)
std::error_code verifySPMagic(uint64_t Magic) override=0
SampleProfileReaderExtBinaryBase(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format)
std::error_code readFuncOffsetTable(bool IsEytzinger, bool IsNested)
std::error_code readNameTableSecLegacy(bool IsMD5, bool FixedLengthMD5)
bool hasCompositeProfileSection() const override
Return whether the section table contains a composite profile section.
std::error_code readStringBasedProfileSymbolList()
std::error_code readLegacyFuncOffsetTable()
std::error_code readHeader() override
Read and validate the file header.
std::error_code readProfileSymbolList(bool IsMD5)
std::error_code readMD5ProfileSymbolList()
SampleProfileReaderExtBinary(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_Ext_Binary)
GCOVBuffer GcovBuffer
GCOV buffer containing the profile.
std::vector< std::string > Names
Function names in this profile.
SampleProfileReaderGCC(std::unique_ptr< MemoryBuffer > B, LLVMContext &C)
static const uint32_t GCOVTagAFDOFunction
static const uint32_t GCOVTagAFDOFileNames
GCOV tags used to separate sections in the profile file.
SampleProfileReaderItaniumRemapper remaps the profile data from a sample profile data reader,...
bool exist(StringRef FunctionName)
Query whether there is equivalent in the remapper which has been inserted.
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReaderItaniumRemapper > > create(StringRef Filename, vfs::FileSystem &FS, SampleProfileReader &Reader, LLVMContext &C)
Create a remapper from the given remapping file.
LLVM_ABI void applyRemapping(LLVMContext &Ctx)
Apply remappings to the profile read by Reader.
SampleProfileReaderItaniumRemapper(std::unique_ptr< MemoryBuffer > B, std::unique_ptr< SymbolRemappingReader > SRR, SampleProfileReader &R)
void insert(StringRef FunctionName)
Insert function name into remapper.
LLVM_ABI std::optional< StringRef > lookUpNameInProfile(StringRef FunctionName)
Return the equivalent name in the profile for FunctionName if it exists.
SampleProfileReaderRawBinary(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_Binary)
SampleProfileReaderText(std::unique_ptr< MemoryBuffer > B, LLVMContext &C)
void setProfileUseMD5() override
Text format sample profile does not support MD5 for now.
std::error_code readHeader() override
Read and validate the file header.
uint32_t MaskedBitFrom
Zero out the discriminator bits higher than bit MaskedBitFrom (0 based).
bool ReadVTableProf
If true, the profile has vtable profiles and reader should decode them to parse profiles correctly.
bool ProfileIsPreInlined
Whether function profile contains ShouldBeInlined contexts.
DenseMap< uint64_t, std::pair< const uint8_t *, const uint8_t * > > FuncMetadataIndex
SampleProfileMap & getProfiles()
Return all the profiles.
uint32_t CSProfileCount
Number of context-sensitive profiles.
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReader > > create(StringRef Filename, LLVMContext &C, vfs::FileSystem &FS, FSDiscriminatorPass P=FSDiscriminatorPass::Base, StringRef RemapFilename="")
Create a sample profile reader appropriate to the file format.
bool profileIsProbeBased() const
Whether input profile is based on pseudo probes.
FunctionSamples * getSamplesFor(const Function &F)
Return the samples collected for function F.
LLVM_ABI void dump(raw_ostream &OS=dbgs())
Print all the profiles on stream OS.
std::error_code dumpProfileTypeInfo(raw_ostream &OS)
Read the profile and print the structure of composite profile blocks.
bool useMD5() const
Return whether names in the profile are all MD5 numbers.
const Module * M
The current module being compiled if SampleProfileReader is used by compiler.
std::unique_ptr< MemoryBuffer > Buffer
Memory buffer holding the profile file.
std::unique_ptr< SampleProfileReaderItaniumRemapper > Remapper
bool ProfileHasAttribute
Whether the profile has attribute metadata.
void setFuncNameToProfNameMap(const HashKeyMap< DenseMap, FunctionId, FunctionId > &FPMap)
bool SkipFlatProf
If SkipFlatProf is true, skip functions marked with !Flat in text mode or sections with SecFlagFlat f...
bool profileIsPreInlined() const
Whether input profile contains ShouldBeInlined contexts.
std::error_code read()
The interface to read sample profiles from the associated file.
bool profileIsFS() const
Whether input profile is flow-sensitive.
MemoryBuffer * getBuffer() const
virtual ~SampleProfileReader()=default
ProfileSectionRange ProfileSecRange
Profile section most recently selected for on-demand loading.
SampleProfileReaderItaniumRemapper * getRemapper()
bool ProfileIsCS
Whether function profiles are context-sensitive flat profiles.
std::error_code read(const DenseSet< StringRef > &FuncsToUse)
Read sample profiles for the given functions.
bool ProfileIsMD5
Whether the profile uses MD5 for Sample Contexts and function names.
void setModule(const Module *Mod)
virtual bool contains(StringRef Key) const
static std::unique_ptr< ProfileSummary > takeSummary(SampleProfileReader &Reader)
Take ownership of the summary of this reader.
virtual llvm::iterator_range< SampleProfileNameTable::iterator > getNameTable() const
It includes all the names that have samples either in outline instance or inline instance.
ProfileSummary & getSummary() const
Return the profile summary.
const HashKeyMap< DenseMap, FunctionId, FunctionId > * FuncNameToProfNameMap
virtual bool hasCompositeProfileSection() const
Return whether the input contains a composite profile section.
SampleProfileFormat Format
The format of sample.
SampleProfileReader(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_None)
std::unique_ptr< ProfileSummary > Summary
Profile summary information.
virtual bool hasUniqSuffix()
Return whether any name in the profile contains ".__uniq." suffix.
LLVM_ABI void computeSummary()
Compute summary for this profile.
uint32_t getDiscriminatorMask() const
Get the bitmask the discriminators: For FS profiles, return the bit mask for this pass.
uint64_t getFormatVersion() const
Return the format version of the profile. For tests only.
bool HasUnknownProfileTypes
Whether reading skipped at least one unknown composite profile block.
virtual bool dumpSectionInfo(raw_ostream &OS=dbgs())
SampleProfileFormat getFormat() const
Return the profile format.
virtual void setProfileUseMD5()
Force the profile to use MD5 in Sample contexts, even if function names are present.
void setDiscriminatorMaskedBitFrom(FSDiscriminatorPass P)
Set the bits for FS discriminators.
virtual std::error_code read(const DenseSet< StringRef > &FuncsToUse, SampleProfileMap &Profiles)
Read sample profiles for the given functions and write them to the given profile map.
bool profileIsCS() const
Whether input profile is fully context-sensitive.
bool ProfileIsFS
Whether the function profiles use FS discriminators.
virtual bool collectFuncsFromModule()
Collect functions with definitions in Module M.
FunctionSamples * getSamplesFor(StringRef Fname)
Return the samples collected for function F.
virtual bool contains(uint64_t GUID) const
LLVM_ABI void dumpJson(raw_ostream &OS=dbgs())
Print all the profiles on stream OS in the JSON format.
SampleProfileMap Profiles
Map every function to its associated profile.
uint64_t FormatVersion
Format version of the profile.
virtual std::error_code readHeader()=0
Read and validate the file header.
void setSkipFlatProf(bool Skip)
Don't read profile without context if the flag is set.
LLVM_ABI void dumpFunctionProfile(const FunctionSamples &FS, raw_ostream &OS=dbgs())
Print the profile for FunctionSamples on stream OS.
bool ProfileIsProbeBased
Whether samples are collected based on pseudo probes.
bool hasUnknownProfileTypes() const
Return whether any unknown composite profile blocks were skipped.
void reportError(int64_t LineNumber, const Twine &Msg) const
Report a parse error message.
virtual std::unique_ptr< ProfileSymbolList > getProfileSymbolList()
raw_ostream * ProfileTypeInfoOS
Optional stream for composite block structure; null disables the output.
LLVMContext & Ctx
LLVM context used to emit diagnostics.
virtual std::error_code readImpl()=0
The implementaion to read sample profiles from the associated file.
The virtual file system interface.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ HIST_TYPE_INDIR_CALL_TOPN
constexpr EytzingerModeT EytzingerMode
constexpr InMemoryModeT InMemoryMode
SmallVector< FunctionSamples *, 10 > InlineCallStack
SortedVectorMap< FunctionId, uint64_t, 0 > TypeCountMap
Key represents type of a C++ polymorphic class type by its vtable and value represents its counter.
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
detail::packed_endian_specific_integral< uint64_t, llvm::endianness::little, unaligned > ulittle64_t
This is an optimization pass for GlobalISel generic memory operations.
static unsigned getFSPassBitEnd(sampleprof::FSDiscriminatorPass P)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Mod
The access may modify the value stored in memory.
static unsigned getN1Bits(int N)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Implement std::hash so that hash_code can be used in STL containers.
Tags to select the initialization mode of SampleProfileFuncOffsetTable.
A profile section retained for loading additional functions on demand.
bool IsComposite
Whether the retained section uses composite payload encoding.
const uint8_t * Start
First byte of the retained section.
const uint8_t * End
One-past-the-end byte of the retained section.