34 #include <system_error> 44 if (std::error_code EC = BufferOrErr.
getError())
46 return std::move(BufferOrErr.
get());
57 if (
Error E = BufferOrError.takeError())
68 if (Buffer->getBufferSize() == 0)
71 std::unique_ptr<InstrProfReader> Result;
88 return std::move(Result);
95 if (
Error E = BufferOrError.takeError())
99 std::unique_ptr<MemoryBuffer> RemappingBuffer;
100 std::string RemappingPathStr = RemappingPath.
str();
101 if (!RemappingPathStr.empty()) {
103 if (
Error E = RemappingBufferOrError.takeError())
105 RemappingBuffer = std::move(RemappingBufferOrError.get());
109 std::move(RemappingBuffer));
114 std::unique_ptr<MemoryBuffer> RemappingBuffer) {
122 auto Result = std::make_unique<IndexedInstrProfReader>(
123 std::move(Buffer), std::move(RemappingBuffer));
129 return std::move(Result);
132 void InstrProfIterator::Increment() {
133 if (
auto E = Reader->readNextRecord(
Record)) {
147 [](
char c) {
return isPrint(c) || ::isspace(c); });
155 bool IsIRInstr =
false;
156 if (!Line->startswith(
":")) {
157 IsIRLevelProfile =
false;
167 HasCSIRLevelProfile =
true;
172 IsIRLevelProfile = IsIRInstr;
179 #define CHECK_LINE_END(Line) \ 180 if (Line.is_at_end()) \ 181 return error(instrprof_error::truncated); 182 #define READ_NUM(Str, Dst) \ 183 if ((Str).getAsInteger(10, (Dst))) \ 184 return error(instrprof_error::malformed); 185 #define VP_READ_ADVANCE(Val) \ 186 CHECK_LINE_END(Line); \ 188 READ_NUM((*Line), (Val)); \ 191 if (Line.is_at_end())
195 if (Line->getAsInteger(10, NumValueKinds)) {
199 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
203 for (
uint32_t VK = 0; VK < NumValueKinds; VK++) {
212 for (
uint32_t S = 0; S < NumValueSites; S++) {
215 std::vector<InstrProfValueData> CurrentValues;
216 for (
uint32_t V = 0; V < NumValueData; V++) {
218 std::pair<StringRef, StringRef> VD = Line->rsplit(
':');
219 uint64_t TakenCount,
Value;
220 if (
ValueKind == IPVK_IndirectCallTarget) {
232 CurrentValues.push_back({
Value, TakenCount});
241 #undef CHECK_LINE_END 243 #undef VP_READ_ADVANCE 248 while (!Line.is_at_end() && (Line->empty() || Line->startswith(
"#")))
251 if (Line.is_at_end()) {
256 Record.
Name = *Line++;
258 return error(std::move(
E));
261 if (Line.is_at_end())
263 if ((Line++)->getAsInteger(0, Record.
Hash))
267 uint64_t NumCounters;
268 if (Line.is_at_end())
270 if ((Line++)->getAsInteger(10, NumCounters))
272 if (NumCounters == 0)
277 Record.
Counts.reserve(NumCounters);
278 for (uint64_t
I = 0;
I < NumCounters; ++
I) {
279 if (Line.is_at_end())
282 if ((Line++)->getAsInteger(10, Count))
284 Record.
Counts.push_back(Count);
288 if (
Error E = readValueProfileData(Record))
289 return error(std::move(
E));
294 template <
class IntPtrT>
300 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
304 template <
class IntPtrT>
306 if (!hasFormat(*DataBuffer))
311 DataBuffer->getBufferStart());
312 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
316 template <
class IntPtrT>
318 const char *End = DataBuffer->getBufferEnd();
320 while (CurrentPos != End && *CurrentPos == 0)
323 if (CurrentPos == End)
330 if (reinterpret_cast<size_t>(CurrentPos) %
alignof(uint64_t))
333 uint64_t
Magic = *
reinterpret_cast<const uint64_t *
>(CurrentPos);
334 if (Magic !=
swap(RawInstrProf::getMagic<IntPtrT>()))
342 template <
class IntPtrT>
345 return error(std::move(
E));
347 const IntPtrT FPtr =
swap(
I->FunctionPointer);
355 template <
class IntPtrT>
362 CountersDelta =
swap(Header.CountersDelta);
363 NamesDelta =
swap(Header.NamesDelta);
364 auto DataSize =
swap(Header.DataSize);
365 auto PaddingBytesBeforeCounters =
swap(Header.PaddingBytesBeforeCounters);
366 auto CountersSize =
swap(Header.CountersSize);
367 auto PaddingBytesAfterCounters =
swap(Header.PaddingBytesAfterCounters);
368 NamesSize =
swap(Header.NamesSize);
369 ValueKindLast =
swap(Header.ValueKindLast);
372 auto PaddingSize = getNumPaddingBytes(NamesSize);
376 DataOffset + DataSizeInBytes + PaddingBytesBeforeCounters;
377 ptrdiff_t NamesOffset = CountersOffset + (
sizeof(uint64_t) * CountersSize) +
378 PaddingBytesAfterCounters;
379 ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
381 auto *Start =
reinterpret_cast<const char *
>(&Header);
382 if (Start + ValueDataOffset > DataBuffer->getBufferEnd())
387 DataEnd =
Data + DataSize;
388 CountersStart =
reinterpret_cast<const uint64_t *
>(Start + CountersOffset);
389 NamesStart = Start + NamesOffset;
390 ValueDataStart =
reinterpret_cast<const uint8_t *
>(Start + ValueDataOffset);
392 std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>();
393 if (
Error E = createSymtab(*NewSymtab.get()))
396 Symtab = std::move(NewSymtab);
400 template <
class IntPtrT>
406 template <
class IntPtrT>
412 template <
class IntPtrT>
416 IntPtrT CounterPtr =
Data->CounterPtr;
417 if (NumCounters == 0)
420 auto *NamesStartAsCounter =
reinterpret_cast<const uint64_t *
>(NamesStart);
421 ptrdiff_t MaxNumCounters = NamesStartAsCounter - CountersStart;
425 if (NumCounters > MaxNumCounters)
427 ptrdiff_t CounterOffset = getCounterOffset(CounterPtr);
428 if (CounterOffset < 0 || CounterOffset > MaxNumCounters ||
429 (CounterOffset + NumCounters) > MaxNumCounters)
432 auto RawCounts =
makeArrayRef(getCounter(CounterOffset), NumCounters);
434 if (ShouldSwapBytes) {
436 Record.
Counts.reserve(RawCounts.size());
437 for (uint64_t Count : RawCounts)
440 Record.
Counts = RawCounts;
445 template <
class IntPtrT>
449 CurValueDataSize = 0;
453 NumValueKinds += (
Data->NumValueSites[
I] != 0);
459 ValueProfData::getValueProfData(
460 ValueDataStart, (
const unsigned char *)DataBuffer->getBufferEnd(),
461 getDataEndianness());
469 VDataPtrOrErr.
get()->deserializeTo(Record, Symtab.get());
470 CurValueDataSize = VDataPtrOrErr.
get()->getSize();
474 template <
class IntPtrT>
478 if (
Error E = readNextHeader(getNextHeaderPos()))
479 return error(std::move(
E));
482 if (
Error E = readName(Record))
483 return error(std::move(
E));
486 if (
Error E = readFuncHash(Record))
487 return error(std::move(
E));
490 if (
Error E = readRawCounts(Record))
491 return error(std::move(
E));
494 if (
Error E = readValueProfilingData(Record))
495 return error(std::move(
E));
518 const unsigned char *&
D,
const unsigned char *
const End) {
520 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
525 VDataPtrOrErr.
get()->deserializeTo(DataBuffer.back(),
nullptr);
526 D += VDataPtrOrErr.
get()->TotalSize;
533 using namespace support;
536 if (N %
sizeof(uint64_t))
540 std::vector<uint64_t> CounterBuffer;
542 const unsigned char *End = D +
N;
545 if (D +
sizeof(uint64_t) >= End)
547 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(
D);
550 uint64_t CountsSize = N /
sizeof(uint64_t) - 1;
553 if (D +
sizeof(uint64_t) > End)
555 CountsSize = endian::readNext<uint64_t, little, unaligned>(
D);
558 if (D + CountsSize *
sizeof(uint64_t) > End)
561 CounterBuffer.clear();
562 CounterBuffer.reserve(CountsSize);
563 for (uint64_t J = 0; J < CountsSize; ++J)
564 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
566 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
570 !readValueProfilingData(D, End)) {
578 template <
typename HashTableImpl>
581 auto Iter = HashTable->find(FuncName);
582 if (Iter == HashTable->end())
592 template <
typename HashTableImpl>
598 Data = *RecordIterator;
606 template <
typename HashTableImpl>
608 const unsigned char *Buckets,
const unsigned char *
const Payload,
612 HashTable.reset(HashTableImpl::Create(
613 Buckets, Payload, Base,
615 RecordIterator = HashTable->data_begin();
635 template <
typename HashTableImpl>
640 std::unique_ptr<MemoryBuffer> RemapBuffer,
642 : RemapBuffer(
std::move(RemapBuffer)), Underlying(Underlying) {
650 std::pair<StringRef, StringRef> Parts = {
StringRef(), Name};
652 Parts = Parts.second.
split(
':');
653 if (Parts.first.startswith(
"_Z"))
655 if (Parts.second.empty())
672 if (
Error E = Remappings.read(*RemapBuffer))
676 if (
auto Key = Remappings.insert(RealName)) {
680 MappedNames.insert({
Key, RealName});
688 StringRef RealName = extractName(FuncName);
689 if (
auto Key = Remappings.lookup(RealName)) {
691 if (!Remapped.
empty()) {
693 RealName.
end() == FuncName.
end())
698 reconstituteName(FuncName, RealName, Remapped, Reconstituted);
706 std::move(E), [](std::unique_ptr<InstrProfError> Err) {
709 :
Error(std::move(Err));
721 std::unique_ptr<MemoryBuffer> RemapBuffer;
737 using namespace support;
742 endian::read<uint64_t, little, aligned>(DataBuffer.
getBufferStart());
747 const unsigned char *
749 const unsigned char *Cur,
bool UseCS) {
750 using namespace IndexedInstrProf;
751 using namespace support;
762 std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
765 const uint64_t *Src =
reinterpret_cast<const uint64_t *
>(SummaryInLE);
766 uint64_t *Dst =
reinterpret_cast<uint64_t *
>(SummaryData.get());
767 for (
unsigned I = 0;
I < SummarySize /
sizeof(uint64_t);
I++)
768 Dst[
I] = endian::byte_swap<uint64_t, little>(Src[
I]);
771 for (
unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
776 std::unique_ptr<llvm::ProfileSummary> &Summary =
777 UseCS ? this->CS_Summary : this->Summary;
780 Summary = std::make_unique<ProfileSummary>(
782 DetailedSummary, SummaryData->get(Summary::TotalBlockCount),
783 SummaryData->get(Summary::MaxBlockCount),
784 SummaryData->get(Summary::MaxInternalBlockCount),
785 SummaryData->get(Summary::MaxFunctionCount),
786 SummaryData->get(Summary::TotalNumBlocks),
787 SummaryData->get(Summary::TotalNumFunctions));
788 return Cur + SummarySize;
802 using namespace support;
804 const unsigned char *Start =
805 (
const unsigned char *)DataBuffer->getBufferStart();
806 const unsigned char *Cur = Start;
807 if ((
const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
814 uint64_t
Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
819 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
820 if (GET_VERSION(FormatVersion) >
826 if (FormatVersion & VARIANT_MASK_CSIR_PROF)
832 endian::byte_swap<uint64_t, little>(Header->HashType));
836 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
840 std::make_unique<InstrProfReaderIndex<OnDiskHashTableImplV3>>(
841 Start + HashOffset, Cur, Start,
HashType, FormatVersion);
844 if (RemappingBuffer) {
845 Remapper = std::make_unique<
847 std::move(RemappingBuffer), *IndexPtr);
848 if (
Error E = Remapper->populateRemappings())
851 Remapper = std::make_unique<InstrProfReaderNullRemapper>(*IndexPtr);
853 Index = std::move(IndexPtr);
860 return *Symtab.get();
862 std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>();
863 if (
Error E =
Index->populateSymtab(*NewSymtab.get())) {
867 Symtab = std::move(NewSymtab);
868 return *Symtab.get();
875 Error Err = Remapper->getRecords(FuncName, Data);
877 return std::move(Err);
879 for (
unsigned I = 0,
E = Data.
size();
I <
E; ++
I) {
881 if (Data[
I].Hash == FuncHash) {
882 return std::move(Data[
I]);
890 std::vector<uint64_t> &Counts) {
893 return error(std::move(
E));
895 Counts = Record.
get().Counts;
904 return error(std::move(E));
906 Record = Data[RecordIndex++];
907 if (RecordIndex >= Data.
size()) {
908 Index->advanceToNextKey();
915 uint64_t NumFuncs = 0;
916 for (
const auto &Func : *
this) {
919 if (FuncIsCS != IsCS)
922 Func.accumulateCounts(Sum);
#define VP_READ_ADVANCE(Val)
Represents either an error or a value T.
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
InfoType
FunctionInfo information type that is used to encode the optional data that is associated with a Func...
Error readHeader() override
Read the header. Required before reading first record.
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
uint64_t NumCutoffEntries
bool isPrint(char C)
Checks whether character C is printable.
This class represents lattice values for constants.
uint64_t MinBlockCount
The minimum execution count for this percentile.
LLVM_NODISCARD bool equals_lower(StringRef RHS) const
equals_lower - Check for string equality, ignoring case.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
void addValueData(uint32_t ValueKind, uint32_t Site, InstrProfValueData *VData, uint32_t N, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
static bool hasFormat(const MemoryBuffer &DataBuffer)
Return true if the given buffer is in an indexed instrprof format.
static instrprof_error take(Error E)
Consume an Error and return the raw enum value contained within it.
static bool isExternalSymbol(const StringRef &Symbol)
True if Symbol is the value used to represent external symbols.
A remapper that applies remappings based on a symbol remapping file.
Error error(instrprof_error Err)
Set the current error and return same.
std::unique_ptr< Summary > allocSummary(uint32_t TotalSize)
static const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
InstrProfSymtab & getSymtab() override
Return the PGO symtab.
size_t getBufferSize() const
Error takeError()
Take ownership of the stored error.
void reserve(size_type N)
InstrProfLookupTrait::offset_type offset_type
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Error readHeader() override
Read the header.
data_type ReadData(StringRef K, const unsigned char *D, offset_type N)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path)
Factory method to create an appropriately typed reader for the given instrprof file.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
static StringRef getName(Value *V)
Tagged union holding either a T or a Error.
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
uint64_t NumSummaryFields
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if the given buffer is in text instrprof format.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
LLVM_NODISCARD size_t size() const
size - Get the string size.
static StringRef extractName(StringRef Name)
Extract the original function name from a PGO function name.
Reader for the simple text based instrprof format.
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
Error getRecords(StringRef FuncName, ArrayRef< NamedInstrProfRecord > &Data) override
static bool hasFormat(const MemoryBuffer &DataBuffer)
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
InstrProfLookupTrait::data_type data_type
hash_value_type ComputeHash(StringRef K)
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
ArrayRef< NamedInstrProfRecord > data_type
Base class and interface for reading profiling data of any known instrprof format.
uint64_t Cutoff
The required percentile of total execution count.
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
std::error_code getError() const
bool readValueProfilingData(const unsigned char *&D, const unsigned char *const End)
std::unique_ptr< InstrProfSymtab > Symtab
std::underlying_type< E >::type Underlying(E Val)
Check that Val is in range for E, and return Val cast to E's underlying type.
static bool hasCSFlagInHash(uint64_t FuncHash)
uint64_t ComputeHash(StringRef K)
virtual Error getRecords(ArrayRef< NamedInstrProfRecord > &Data)=0
Error getRecords(ArrayRef< NamedInstrProfRecord > &Data) override
void consumeError(Error Err)
Consume a Error without doing anything.
#define CHECK_LINE_END(Line)
#define READ_NUM(Str, Dst)
void clearValueData()
Clear value data entries.
static const char *const Magic
static Expected< std::unique_ptr< MemoryBuffer > > setupMemoryBuffer(const Twine &Path)
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
Name matcher supporting fuzzy matching of symbol names to names in profiles.
static ErrorSuccess success()
Create a success value.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
Align max(MaybeAlign Lhs, Align Rhs)
RawInstrProfReader< uint32_t > RawInstrProfReader32
std::unique_ptr< ProfileSummary > getSummary()
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
A file format agnostic iterator over profiling data.
void accumulateCounts(CountSumOrPercent &Sum, bool IsCS)
Compute the sum of counts and return in Sum.
Reader for the raw instrprof binary format from runtime.
reference get()
Returns a reference to the stored T value.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
RawInstrProfReader< uint64_t > RawInstrProfReader64
This interface provides simple read-only access to a block of memory, and provides simple methods for...
InstrProfReaderIndex(const unsigned char *Buckets, const unsigned char *const Payload, const unsigned char *const Base, IndexedInstrProf::HashT HashType, uint64_t Version)
InstrProfReaderItaniumRemapper(std::unique_ptr< MemoryBuffer > RemapBuffer, InstrProfReaderIndex< HashTableImpl > &Underlying)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
iterator insert(iterator I, T &&Elt)
unsigned char getSwappedBytes(unsigned char C)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
std::vector< uint64_t > Counts
Error readHeader() override
Read the file header.
virtual Error readHeader()=0
Read the header. Required before reading first record.
Profiling information for a single function.
Expected< InstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
Reader for symbol remapping files.
static void reconstituteName(StringRef OrigName, StringRef ExtractedName, StringRef Replacement, SmallVectorImpl< char > &Out)
Given a mangled name extracted from a PGO function name, and a new form for that mangled name...
Error populateRemappings() override
const char * getBufferStart() const
virtual bool isIRLevelProfile() const =0
std::string str() const
Return the twine contents as a std::string.
Provides ErrorOr<T> smart pointer.
Lightweight error class with error context and mandatory checking.
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
StringRef - Represent a constant reference to a string, i.e.
Reader for the indexed binary instrprof format.
std::vector< ProfileSummaryEntry > SummaryEntryVector
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, const Twine &RemappingPath="")
Factory method to create an indexed reader.
void Clear()
Clear value data entries and edge counters.
bool empty() const
empty - Check if the array is empty.
Error success()
Clear the current error and return a successful one.
Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash, std::vector< uint64_t > &Counts)
Fill Counts with the profile data for the given function name.
static Error initializeReader(InstrProfReader &Reader)