33 #include <system_error> 43 if (std::error_code EC = BufferOrErr.
getError())
45 return std::move(BufferOrErr.
get());
56 if (
Error E = BufferOrError.takeError())
67 if (Buffer->getBufferSize() == 0)
70 std::unique_ptr<InstrProfReader>
Result;
87 return std::move(Result);
94 if (
Error E = BufferOrError.takeError())
108 auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
117 void InstrProfIterator::Increment() {
118 if (
auto E = Reader->readNextRecord(
Record)) {
132 [](
char c) {
return isPrint(c) || ::isspace(c); });
140 bool IsIRInstr =
false;
141 if (!Line->startswith(
":")) {
142 IsIRLevelProfile =
false;
154 IsIRLevelProfile = IsIRInstr;
161 #define CHECK_LINE_END(Line) \ 162 if (Line.is_at_end()) \ 163 return error(instrprof_error::truncated); 164 #define READ_NUM(Str, Dst) \ 165 if ((Str).getAsInteger(10, (Dst))) \ 166 return error(instrprof_error::malformed); 167 #define VP_READ_ADVANCE(Val) \ 168 CHECK_LINE_END(Line); \ 170 READ_NUM((*Line), (Val)); \ 173 if (Line.is_at_end())
177 if (Line->getAsInteger(10, NumValueKinds)) {
181 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
185 for (
uint32_t VK = 0; VK < NumValueKinds; VK++) {
194 for (
uint32_t S = 0; S < NumValueSites; S++) {
197 std::vector<InstrProfValueData> CurrentValues;
198 for (
uint32_t V = 0; V < NumValueData; V++) {
200 std::pair<StringRef, StringRef> VD = Line->rsplit(
':');
201 uint64_t TakenCount,
Value;
202 if (
ValueKind == IPVK_IndirectCallTarget) {
214 CurrentValues.push_back({Value, TakenCount});
223 #undef CHECK_LINE_END 225 #undef VP_READ_ADVANCE 230 while (!Line.is_at_end() && (Line->empty() || Line->startswith(
"#")))
233 if (Line.is_at_end()) {
238 Record.
Name = *Line++;
240 return error(std::move(
E));
243 if (Line.is_at_end())
245 if ((Line++)->getAsInteger(0, Record.
Hash))
249 uint64_t NumCounters;
250 if (Line.is_at_end())
252 if ((Line++)->getAsInteger(10, NumCounters))
254 if (NumCounters == 0)
259 Record.
Counts.reserve(NumCounters);
260 for (uint64_t
I = 0;
I < NumCounters; ++
I) {
261 if (Line.is_at_end())
264 if ((Line++)->getAsInteger(10, Count))
266 Record.
Counts.push_back(Count);
270 if (
Error E = readValueProfileData(Record))
271 return error(std::move(
E));
276 template <
class IntPtrT>
282 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
286 template <
class IntPtrT>
288 if (!hasFormat(*DataBuffer))
293 DataBuffer->getBufferStart());
294 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
298 template <
class IntPtrT>
300 const char *End = DataBuffer->getBufferEnd();
302 while (CurrentPos != End && *CurrentPos == 0)
305 if (CurrentPos == End)
312 if (reinterpret_cast<size_t>(CurrentPos) %
alignof(uint64_t))
315 uint64_t
Magic = *
reinterpret_cast<const uint64_t *
>(CurrentPos);
316 if (Magic !=
swap(RawInstrProf::getMagic<IntPtrT>()))
324 template <
class IntPtrT>
327 return error(std::move(
E));
329 const IntPtrT FPtr =
swap(
I->FunctionPointer);
337 template <
class IntPtrT>
344 CountersDelta =
swap(Header.CountersDelta);
345 NamesDelta =
swap(Header.NamesDelta);
346 auto DataSize =
swap(Header.DataSize);
347 auto CountersSize =
swap(Header.CountersSize);
348 NamesSize =
swap(Header.NamesSize);
349 ValueKindLast =
swap(Header.ValueKindLast);
352 auto PaddingSize = getNumPaddingBytes(NamesSize);
355 ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
356 ptrdiff_t NamesOffset = CountersOffset +
sizeof(uint64_t) * CountersSize;
357 ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
359 auto *Start =
reinterpret_cast<const char *
>(&Header);
360 if (Start + ValueDataOffset > DataBuffer->getBufferEnd())
365 DataEnd =
Data + DataSize;
366 CountersStart =
reinterpret_cast<const uint64_t *
>(Start + CountersOffset);
367 NamesStart = Start + NamesOffset;
368 ValueDataStart =
reinterpret_cast<const uint8_t *
>(Start + ValueDataOffset);
370 std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
371 if (
Error E = createSymtab(*NewSymtab.get()))
374 Symtab = std::move(NewSymtab);
378 template <
class IntPtrT>
384 template <
class IntPtrT>
390 template <
class IntPtrT>
394 IntPtrT CounterPtr =
Data->CounterPtr;
395 if (NumCounters == 0)
398 auto RawCounts =
makeArrayRef(getCounter(CounterPtr), NumCounters);
399 auto *NamesStartAsCounter =
reinterpret_cast<const uint64_t *
>(NamesStart);
402 if (RawCounts.data() < CountersStart ||
403 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
406 if (ShouldSwapBytes) {
408 Record.
Counts.reserve(RawCounts.size());
409 for (uint64_t Count : RawCounts)
412 Record.
Counts = RawCounts;
417 template <
class IntPtrT>
421 CurValueDataSize = 0;
425 NumValueKinds += (
Data->NumValueSites[
I] != 0);
431 ValueProfData::getValueProfData(
432 ValueDataStart, (
const unsigned char *)DataBuffer->getBufferEnd(),
433 getDataEndianness());
441 VDataPtrOrErr.
get()->deserializeTo(Record, Symtab.get());
442 CurValueDataSize = VDataPtrOrErr.
get()->getSize();
446 template <
class IntPtrT>
450 if (
Error E = readNextHeader(getNextHeaderPos()))
451 return error(std::move(
E));
454 if (
Error E = readName(Record))
455 return error(std::move(
E));
458 if (
Error E = readFuncHash(Record))
459 return error(std::move(
E));
462 if (
Error E = readRawCounts(Record))
463 return error(std::move(
E));
466 if (
Error E = readValueProfilingData(Record))
467 return error(std::move(
E));
490 const unsigned char *&
D,
const unsigned char *
const End) {
492 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
497 VDataPtrOrErr.
get()->deserializeTo(DataBuffer.back(),
nullptr);
498 D += VDataPtrOrErr.
get()->TotalSize;
505 using namespace support;
508 if (N %
sizeof(uint64_t))
512 std::vector<uint64_t> CounterBuffer;
514 const unsigned char *End = D +
N;
517 if (D +
sizeof(uint64_t) >= End)
519 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(
D);
522 uint64_t CountsSize = N /
sizeof(uint64_t) - 1;
525 if (D +
sizeof(uint64_t) > End)
527 CountsSize = endian::readNext<uint64_t, little, unaligned>(
D);
530 if (D + CountsSize *
sizeof(uint64_t) > End)
533 CounterBuffer.clear();
534 CounterBuffer.reserve(CountsSize);
535 for (uint64_t J = 0; J < CountsSize; ++J)
536 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
538 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
542 !readValueProfilingData(D, End)) {
550 template <
typename HashTableImpl>
553 auto Iter = HashTable->find(FuncName);
554 if (Iter == HashTable->end())
564 template <
typename HashTableImpl>
570 Data = *RecordIterator;
578 template <
typename HashTableImpl>
580 const unsigned char *Buckets,
const unsigned char *
const Payload,
584 HashTable.reset(HashTableImpl::Create(
585 Buckets, Payload, Base,
586 typename HashTableImpl::InfoType(HashType, Version)));
587 RecordIterator = HashTable->data_begin();
591 using namespace support;
596 endian::read<uint64_t, little, aligned>(DataBuffer.
getBufferStart());
601 const unsigned char *
603 const unsigned char *Cur) {
604 using namespace IndexedInstrProf;
605 using namespace support;
616 std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
619 const uint64_t *Src =
reinterpret_cast<const uint64_t *
>(SummaryInLE);
620 uint64_t *Dst =
reinterpret_cast<uint64_t *
>(SummaryData.get());
621 for (
unsigned I = 0;
I < SummarySize /
sizeof(uint64_t);
I++)
622 Dst[
I] = endian::byte_swap<uint64_t, little>(Src[
I]);
625 for (
unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
631 this->Summary = llvm::make_unique<ProfileSummary>(
633 SummaryData->get(Summary::TotalBlockCount),
634 SummaryData->get(Summary::MaxBlockCount),
635 SummaryData->get(Summary::MaxInternalBlockCount),
636 SummaryData->get(Summary::MaxFunctionCount),
637 SummaryData->get(Summary::TotalNumBlocks),
638 SummaryData->get(Summary::TotalNumFunctions));
639 return Cur + SummarySize;
642 using namespace IndexedInstrProf;
653 using namespace support;
655 const unsigned char *Start =
656 (
const unsigned char *)DataBuffer->getBufferStart();
657 const unsigned char *Cur = Start;
658 if ((
const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
665 uint64_t
Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
670 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
671 if (GET_VERSION(FormatVersion) >
679 endian::byte_swap<uint64_t, little>(Header->HashType));
683 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
688 Start + HashOffset, Cur, Start,
HashType, FormatVersion);
689 Index.reset(IndexPtr);
695 return *Symtab.get();
697 std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
698 if (
Error E =
Index->populateSymtab(*NewSymtab.get())) {
702 Symtab = std::move(NewSymtab);
703 return *Symtab.get();
710 Error Err =
Index->getRecords(FuncName, Data);
712 return std::move(Err);
714 for (
unsigned I = 0,
E = Data.
size();
I <
E; ++
I) {
716 if (Data[
I].Hash == FuncHash) {
717 return std::move(Data[
I]);
725 std::vector<uint64_t> &Counts) {
728 return error(std::move(
E));
730 Counts = Record.
get().Counts;
739 return error(std::move(E));
741 Record = Data[RecordIndex++];
742 if (RecordIndex >= Data.
size()) {
743 Index->advanceToNextKey();
#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...
Error readHeader() override
Read the header. Required before reading first record.
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
uint64_t NumCutoffEntries
bool isPrint(char C)
Checks whether character C is printable.
Compute iterated dominance frontiers using a linear time algorithm.
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.
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.
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.
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.
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)...
Reader for the simple text based instrprof format.
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
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)
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
uint64_t ComputeHash(StringRef K)
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.
static ErrorSuccess success()
Create a success value.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
RawInstrProfReader< uint32_t > RawInstrProfReader32
std::unique_ptr< ProfileSummary > getSummary()
A file format agnostic iterator over profiling data.
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)
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.
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.
const char * getBufferStart() const
Provides ErrorOr<T> smart pointer.
LLVM Value Representation.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path)
Factory method to create an indexed reader.
Lightweight error class with error context and mandatory checking.
StringRef - Represent a constant reference to a string, i.e.
Reader for the indexed binary instrprof format.
std::vector< ProfileSummaryEntry > SummaryEntryVector
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)