LLVM 24.0.0git
InstrProfReader.h
Go to the documentation of this file.
1//===- InstrProfReader.h - Instrumented profiling readers -------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for reading profiling data for instrumentation
10// based PGO and coverage.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_PROFILEDATA_INSTRPROFREADER_H
15#define LLVM_PROFILEDATA_INSTRPROFREADER_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/StringRef.h"
20#include "llvm/Object/BuildID.h"
28#include "llvm/Support/Endian.h"
29#include "llvm/Support/Error.h"
36#include <algorithm>
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <iterator>
41#include <memory>
42#include <optional>
43#include <utility>
44#include <vector>
45
46namespace llvm {
47
48class InstrProfReader;
49
50/// A file format agnostic iterator over profiling data.
51template <class record_type = NamedInstrProfRecord,
52 class reader_type = InstrProfReader>
54public:
55 using iterator_category = std::input_iterator_tag;
56 using value_type = record_type;
57 using difference_type = std::ptrdiff_t;
60
61private:
62 reader_type *Reader = nullptr;
63 value_type Record;
64
65 void increment() {
66 if (Error E = Reader->readNextRecord(Record)) {
67 // Handle errors in the reader.
68 InstrProfError::take(std::move(E));
69 *this = InstrProfIterator();
70 }
71 }
72
73public:
74 InstrProfIterator() = default;
75 InstrProfIterator(reader_type *Reader) : Reader(Reader) { increment(); }
76
78 increment();
79 return *this;
80 }
81 bool operator==(const InstrProfIterator &RHS) const {
82 return Reader == RHS.Reader;
83 }
84 bool operator!=(const InstrProfIterator &RHS) const {
85 return Reader != RHS.Reader;
86 }
87 value_type &operator*() { return Record; }
88 value_type *operator->() { return &Record; }
89};
90
91/// Base class and interface for reading profiling data of any known instrprof
92/// format. Provides an iterator over NamedInstrProfRecords.
95 std::string LastErrorMsg;
96
97public:
98 InstrProfReader() = default;
99 virtual ~InstrProfReader() = default;
100
101 /// Read the header. Required before reading first record.
102 virtual Error readHeader() = 0;
103
104 /// Read a single record.
106
107 /// Read a list of binary ids.
108 virtual Error readBinaryIds(std::vector<llvm::object::BuildID> &BinaryIds) {
109 return success();
110 }
111
112 /// Print binary ids.
113 virtual Error printBinaryIds(raw_ostream &OS) { return success(); };
114
115 /// Iterator over profile data.
118
119 /// Return the profile version.
120 virtual uint64_t getVersion() const = 0;
121
122 virtual bool isIRLevelProfile() const = 0;
123
124 virtual bool hasCSIRLevelProfile() const = 0;
125
126 virtual bool instrEntryBBEnabled() const = 0;
127
128 /// Return true if the profile instruments all loop entries.
129 virtual bool instrLoopEntriesEnabled() const = 0;
130
131 /// Return true if the profile has single byte counters representing coverage.
132 virtual bool hasSingleByteCoverage() const = 0;
133
134 /// Return true if the profile only instruments function entries.
135 virtual bool functionEntryOnly() const = 0;
136
137 /// Return true if profile includes a memory profile.
138 virtual bool hasMemoryProfile() const = 0;
139
140 /// Return true if this has a temporal profile.
141 virtual bool hasTemporalProfile() const = 0;
142
143 /// Returns a BitsetEnum describing the attributes of the profile. To check
144 /// individual attributes prefer using the helpers above.
145 virtual InstrProfKind getProfileKind() const = 0;
146
147 /// Return the PGO symtab. There are three different readers:
148 /// Raw, Text, and Indexed profile readers. The first two types
149 /// of readers are used only by llvm-profdata tool, while the indexed
150 /// profile reader is also used by llvm-cov tool and the compiler (
151 /// backend or frontend). Since creating PGO symtab can create
152 /// significant runtime and memory overhead (as it touches data
153 /// for the whole program), InstrProfSymtab for the indexed profile
154 /// reader should be created on demand and it is recommended to be
155 /// only used for dumping purpose with llvm-proftool, not with the
156 /// compiler.
158
159 /// Compute the sum of counts and return in Sum.
160 LLVM_ABI void accumulateCounts(CountSumOrPercent &Sum, bool IsCS);
161
162protected:
163 std::unique_ptr<InstrProfSymtab> Symtab;
164 /// A list of temporal profile traces.
166 /// The total number of temporal profile traces seen.
168
169 /// Set the current error and return same.
170 Error error(instrprof_error Err, const std::string &ErrMsg = "") {
171 LastError = Err;
172 LastErrorMsg = ErrMsg;
173 if (Err == instrprof_error::success)
174 return Error::success();
175 return make_error<InstrProfError>(Err, ErrMsg);
176 }
177
179 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
180 LastError = IPE.get();
181 LastErrorMsg = IPE.getMessage();
182 });
183 return make_error<InstrProfError>(LastError, LastErrorMsg);
184 }
185
186 /// Clear the current error and return a successful one.
188
189public:
190 /// Return true if the reader has finished reading the profile data.
191 bool isEOF() { return LastError == instrprof_error::eof; }
192
193 /// Return true if the reader encountered an error reading profiling data.
194 bool hasError() { return LastError != instrprof_error::success && !isEOF(); }
195
196 /// Get the current error.
198 if (hasError())
199 return make_error<InstrProfError>(LastError, LastErrorMsg);
200 return Error::success();
201 }
202
203 /// Factory method to create an appropriately typed reader for the given
204 /// instrprof file.
206 const Twine &Path, vfs::FileSystem &FS,
207 const InstrProfCorrelator *Correlator = nullptr,
208 const object::BuildIDFetcher *BIDFetcher = nullptr,
209 std::optional<ProfCorrelatorKind> BIDFetcherCorrelatorKind = std::nullopt,
210 std::function<void(Error)> Warn = nullptr);
211
213 std::unique_ptr<MemoryBuffer> Buffer,
214 const InstrProfCorrelator *Correlator = nullptr,
215 const object::BuildIDFetcher *BIDFetcher = nullptr,
216 std::optional<ProfCorrelatorKind> BIDFetcherCorrelatorKind = std::nullopt,
217 std::function<void(Error)> Warn = nullptr);
218
219 /// \param Weight for raw profiles use this as the temporal profile trace
220 /// weight
221 /// \returns a list of temporal profile traces.
223 getTemporalProfTraces(std::optional<uint64_t> Weight = {}) {
224 // For non-raw profiles we ignore the input weight and instead use the
225 // weights already in the traces.
226 return TemporalProfTraces;
227 }
228 /// \returns the total number of temporal profile traces seen.
232};
233
234/// Reader for the simple text based instrprof format.
235///
236/// This format is a simple text format that's suitable for test data. Records
237/// are separated by one or more blank lines, and record fields are separated by
238/// new lines.
239///
240/// Each record consists of a function name, a function hash, a number of
241/// counters, and then each counter value, in that order.
243private:
244 /// The profile data file contents.
245 std::unique_ptr<MemoryBuffer> DataBuffer;
246 /// Iterator over the profile data.
247 line_iterator Line;
248 /// The attributes of the current profile.
250
251 Error readValueProfileData(InstrProfRecord &Record);
252
253 Error readTemporalProfTraceData();
254
255public:
256 TextInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer_)
257 : DataBuffer(std::move(DataBuffer_)), Line(*DataBuffer, true, '#') {}
260
261 /// Return true if the given buffer is in text instrprof format.
262 static bool hasFormat(const MemoryBuffer &Buffer);
263
264 // Text format does not have version, so return 0.
265 uint64_t getVersion() const override { return 0; }
266
267 bool isIRLevelProfile() const override {
268 return static_cast<bool>(ProfileKind & InstrProfKind::IRInstrumentation);
269 }
270
271 bool hasCSIRLevelProfile() const override {
272 return static_cast<bool>(ProfileKind & InstrProfKind::ContextSensitive);
273 }
274
275 bool instrEntryBBEnabled() const override {
276 return static_cast<bool>(ProfileKind &
278 }
279
280 bool instrLoopEntriesEnabled() const override {
281 return static_cast<bool>(ProfileKind &
283 }
284
285 bool hasSingleByteCoverage() const override {
286 return static_cast<bool>(ProfileKind & InstrProfKind::SingleByteCoverage);
287 }
288
289 bool functionEntryOnly() const override {
290 return static_cast<bool>(ProfileKind & InstrProfKind::FunctionEntryOnly);
291 }
292
293 bool hasMemoryProfile() const override {
294 // TODO: Add support for text format memory profiles.
295 return false;
296 }
297
298 bool hasTemporalProfile() const override {
299 return static_cast<bool>(ProfileKind & InstrProfKind::TemporalProfile);
300 }
301
302 InstrProfKind getProfileKind() const override { return ProfileKind; }
303
304 /// Read the header.
305 Error readHeader() override;
306
307 /// Read a single record.
308 Error readNextRecord(NamedInstrProfRecord &Record) override;
309
311 assert(Symtab);
312 return *Symtab;
313 }
314};
315
316/// Reader for the raw instrprof binary format from runtime.
317///
318/// This format is a raw memory dump of the instrumentation-based profiling data
319/// from the runtime. It has no index.
320///
321/// Templated on the unsigned type whose size matches pointers on the platform
322/// that wrote the profile.
323template <class IntPtrT>
325private:
326 /// The profile data file contents.
327 std::unique_ptr<MemoryBuffer> DataBuffer;
328 /// If available, this hold the ProfileData array used to correlate raw
329 /// instrumentation data to their functions.
330 const InstrProfCorrelatorImpl<IntPtrT> *Correlator;
331 /// Fetches debuginfo by build id to correlate profiles.
332 const object::BuildIDFetcher *BIDFetcher;
333 /// Correlates profiles with build id fetcher by fetching debuginfo with build
334 /// ID.
335 std::unique_ptr<InstrProfCorrelator> BIDFetcherCorrelator;
336 /// Indicates if should use debuginfo or binary to correlate with build id
337 /// fetcher.
338 std::optional<ProfCorrelatorKind> BIDFetcherCorrelatorKind;
339 /// A list of timestamps paired with a function name reference.
340 std::vector<std::pair<uint64_t, uint64_t>> TemporalProfTimestamps;
341 bool ShouldSwapBytes;
342 // The value of the version field of the raw profile data header. The lower 32
343 // bits specifies the format version and the most significant 32 bits specify
344 // the variant types of the profile.
345 uint64_t Version;
346 uint64_t CountersDelta;
347 uint64_t BitmapDelta;
348 uint64_t UniformCountersDelta;
349 uint64_t NamesDelta;
352 const RawInstrProf::VTableProfileData<IntPtrT> *VTableBegin = nullptr;
353 const RawInstrProf::VTableProfileData<IntPtrT> *VTableEnd = nullptr;
354 const char *CountersStart;
355 const char *CountersEnd;
356 const char *BitmapStart;
357 const char *BitmapEnd;
358 const char *UniformCountersStart;
359 const char *UniformCountersEnd;
360 const char *NamesStart;
361 const char *NamesEnd;
362 const char *VNamesStart = nullptr;
363 const char *VNamesEnd = nullptr;
364 // After value profile is all read, this pointer points to
365 // the header of next profile data (if exists)
366 const uint8_t *ValueDataStart;
367 uint32_t ValueKindLast;
368 uint32_t CurValueDataSize;
369 std::vector<llvm::object::BuildID> BinaryIds;
370
371 std::function<void(Error)> Warn;
372
373 /// Maxium counter value 2^56.
374 static const uint64_t MaxCounterValue = (1ULL << 56);
375
376public:
377 RawInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer,
378 const InstrProfCorrelator *Correlator,
379 const object::BuildIDFetcher *BIDFetcher,
380 std::optional<ProfCorrelatorKind> BIDFetcherCorrelatorKind,
381 std::function<void(Error)> Warn)
382 : DataBuffer(std::move(DataBuffer)),
384 Correlator)),
385 BIDFetcher(BIDFetcher),
386 BIDFetcherCorrelatorKind(BIDFetcherCorrelatorKind), Warn(Warn) {
387 assert((!BIDFetcher || BIDFetcherCorrelatorKind) &&
388 "a build ID fetcher needs a correlation kind");
389 }
390
393
394 static bool hasFormat(const MemoryBuffer &DataBuffer);
395 Error readHeader() override;
397 Error readBinaryIds(std::vector<llvm::object::BuildID> &BinaryIds) override;
399
400 uint64_t getVersion() const override { return Version; }
401
402 bool isIRLevelProfile() const override {
403 return (Version & VARIANT_MASK_IR_PROF) != 0;
404 }
405
406 bool hasCSIRLevelProfile() const override {
407 return (Version & VARIANT_MASK_CSIR_PROF) != 0;
408 }
409
410 bool instrEntryBBEnabled() const override {
411 return (Version & VARIANT_MASK_INSTR_ENTRY) != 0;
412 }
413
414 bool instrLoopEntriesEnabled() const override {
415 return (Version & VARIANT_MASK_INSTR_LOOP_ENTRIES) != 0;
416 }
417
418 bool hasSingleByteCoverage() const override {
419 return (Version & VARIANT_MASK_BYTE_COVERAGE) != 0;
420 }
421
422 bool functionEntryOnly() const override {
423 return (Version & VARIANT_MASK_FUNCTION_ENTRY_ONLY) != 0;
424 }
425
426 bool hasMemoryProfile() const override {
427 // Memory profiles have a separate raw format, so this should never be set.
428 assert(!(Version & VARIANT_MASK_MEMPROF));
429 return false;
430 }
431
432 bool hasTemporalProfile() const override {
433 return (Version & VARIANT_MASK_TEMPORAL_PROF) != 0;
434 }
435
436 /// Returns a BitsetEnum describing the attributes of the raw instr profile.
438
440 assert(Symtab.get());
441 return *Symtab.get();
442 }
443
445 getTemporalProfTraces(std::optional<uint64_t> Weight = {}) override;
446
447private:
448 Error createSymtab(InstrProfSymtab &Symtab);
449 Error readNextHeader(const char *CurrentPos);
451
452 template <class IntT> IntT swap(IntT Int) const {
453 return ShouldSwapBytes ? llvm::byteswap(Int) : Int;
454 }
455
456 llvm::endianness getDataEndianness() const {
457 if (!ShouldSwapBytes)
461 else
463 }
464
465 inline uint8_t getNumPaddingBytes(uint64_t SizeInBytes) {
466 return 7 & (sizeof(uint64_t) - SizeInBytes % sizeof(uint64_t));
467 }
468
469 Error readName(NamedInstrProfRecord &Record);
470 Error readFuncHash(NamedInstrProfRecord &Record);
471 Error readRawCounts(InstrProfRecord &Record);
472 Error readRawBitmapBytes(InstrProfRecord &Record);
473 Error readRawUniformCounters(InstrProfRecord &Record);
474 Error readValueProfilingData(InstrProfRecord &Record);
475 bool atEnd() const { return Data == DataEnd; }
476
477 void advanceData() {
478 // `CountersDelta` and `BitmapDelta` are constant zero when using debug info
479 // correlation.
480 if (!Correlator && !BIDFetcherCorrelator) {
481 // The initial CountersDelta is the in-memory address difference between
482 // the data and counts sections:
483 // start(__llvm_prf_cnts) - start(__llvm_prf_data)
484 // As we advance to the next record, we maintain the correct CountersDelta
485 // with respect to the next record.
486 CountersDelta -= sizeof(*Data);
487 BitmapDelta -= sizeof(*Data);
488 UniformCountersDelta -= sizeof(*Data);
489 }
490 Data++;
491 ValueDataStart += CurValueDataSize;
492 }
493
494 const char *getNextHeaderPos() const {
495 assert(atEnd());
496 return (const char *)ValueDataStart;
497 }
498
499 StringRef getName(uint64_t NameRef) const {
500 return Symtab->getFuncOrVarName(swap(NameRef));
501 }
502
503 int getCounterTypeSize() const {
504 return hasSingleByteCoverage() ? sizeof(uint8_t) : sizeof(uint64_t);
505 }
506};
507
510
511namespace IndexedInstrProf {
512
513enum class HashT : uint32_t;
514
515} // end namespace IndexedInstrProf
516
517/// Trait for lookups into the on-disk hash table for the binary instrprof
518/// format.
520 std::vector<NamedInstrProfRecord> DataBuffer;
522 unsigned FormatVersion;
523 // Endianness of the input value profile data.
524 // It should be LE by default, but can be changed
525 // for testing purpose.
526 llvm::endianness ValueProfDataEndianness = llvm::endianness::little;
527
528public:
529 InstrProfLookupTrait(IndexedInstrProf::HashT HashType, unsigned FormatVersion)
530 : HashType(HashType), FormatVersion(FormatVersion) {}
531
533
538
539 static bool EqualKey(StringRef A, StringRef B) { return A == B; }
542
543 LLVM_ABI hash_value_type ComputeHash(StringRef K);
544
545 static std::pair<offset_type, offset_type>
546 ReadKeyDataLength(const unsigned char *&D) {
547 using namespace support;
548
549 offset_type KeyLen =
551 offset_type DataLen =
553 return std::make_pair(KeyLen, DataLen);
554 }
555
556 StringRef ReadKey(const unsigned char *D, offset_type N) {
557 return StringRef((const char *)D, N);
558 }
559
560 LLVM_ABI bool readValueProfilingData(const unsigned char *&D,
561 const unsigned char *const End);
562 LLVM_ABI data_type ReadData(StringRef K, const unsigned char *D,
563 offset_type N);
564
565 // Used for testing purpose only.
567 ValueProfDataEndianness = Endianness;
568 }
569};
570
572 virtual ~InstrProfReaderIndexBase() = default;
573
574 // Read all the profile records with the same key pointed to the current
575 // iterator.
577
578 // Read all the profile records with the key equal to FuncName
579 virtual Error getRecords(StringRef FuncName,
581 virtual void advanceToNextKey() = 0;
582 virtual bool atEnd() const = 0;
583 virtual void setValueProfDataEndianness(llvm::endianness Endianness) = 0;
584 virtual uint64_t getVersion() const = 0;
585 virtual bool isIRLevelProfile() const = 0;
586 virtual bool hasCSIRLevelProfile() const = 0;
587 virtual bool instrEntryBBEnabled() const = 0;
588 virtual bool instrLoopEntriesEnabled() const = 0;
589 virtual bool hasSingleByteCoverage() const = 0;
590 virtual bool functionEntryOnly() const = 0;
591 virtual bool hasMemoryProfile() const = 0;
592 virtual bool hasTemporalProfile() const = 0;
593 virtual InstrProfKind getProfileKind() const = 0;
595};
596
599
602
603template <typename HashTableImpl>
605
606template <typename HashTableImpl>
608private:
609 std::unique_ptr<HashTableImpl> HashTable;
610 typename HashTableImpl::data_iterator RecordIterator;
611 uint64_t FormatVersion;
612
613 friend class InstrProfReaderItaniumRemapper<HashTableImpl>;
614
615public:
616 InstrProfReaderIndex(const unsigned char *Buckets,
617 const unsigned char *const Payload,
618 const unsigned char *const Base,
620 ~InstrProfReaderIndex() override = default;
621
623 Error getRecords(StringRef FuncName,
625 void advanceToNextKey() override { RecordIterator++; }
626
627 bool atEnd() const override {
628 return RecordIterator == HashTable->data_end();
629 }
630
632 HashTable->getInfoObj().setValueProfDataEndianness(Endianness);
633 }
634
635 uint64_t getVersion() const override { return GET_VERSION(FormatVersion); }
636
637 bool isIRLevelProfile() const override {
638 return (FormatVersion & VARIANT_MASK_IR_PROF) != 0;
639 }
640
641 bool hasCSIRLevelProfile() const override {
642 return (FormatVersion & VARIANT_MASK_CSIR_PROF) != 0;
643 }
644
645 bool instrEntryBBEnabled() const override {
646 return (FormatVersion & VARIANT_MASK_INSTR_ENTRY) != 0;
647 }
648
649 bool instrLoopEntriesEnabled() const override {
650 return (FormatVersion & VARIANT_MASK_INSTR_LOOP_ENTRIES) != 0;
651 }
652
653 bool hasSingleByteCoverage() const override {
654 return (FormatVersion & VARIANT_MASK_BYTE_COVERAGE) != 0;
655 }
656
657 bool functionEntryOnly() const override {
658 return (FormatVersion & VARIANT_MASK_FUNCTION_ENTRY_ONLY) != 0;
659 }
660
661 bool hasMemoryProfile() const override {
662 return (FormatVersion & VARIANT_MASK_MEMPROF) != 0;
663 }
664
665 bool hasTemporalProfile() const override {
666 return (FormatVersion & VARIANT_MASK_TEMPORAL_PROF) != 0;
667 }
668
669 InstrProfKind getProfileKind() const override;
670
672 // FIXME: the create method calls 'finalizeSymtab' and sorts a bunch of
673 // arrays/maps. Since there are other data sources other than 'HashTable' to
674 // populate a symtab, it might make sense to have something like this
675 // 1. Let each data source populate Symtab and init the arrays/maps without
676 // calling 'finalizeSymtab'
677 // 2. Call 'finalizeSymtab' once to get all arrays/maps sorted if needed.
678 return Symtab.create(HashTable->keys());
679 }
680};
681
682/// Name matcher supporting fuzzy matching of symbol names to names in profiles.
684public:
685 virtual ~InstrProfReaderRemapper() = default;
687 virtual Error getRecords(StringRef FuncName,
689};
690
692private:
693 /// The MemProf version.
696 /// MemProf summary (if available, version >= 4).
697 std::unique_ptr<memprof::MemProfSummary> MemProfSum;
698 /// MemProf profile schema (if available).
700 /// MemProf record profile data on-disk indexed via llvm::md5(FunctionName).
701 std::unique_ptr<MemProfRecordHashTable> MemProfRecordTable;
702 /// The starting address of the frame array.
703 const unsigned char *FrameBase = nullptr;
704 /// The starting address of the call stack array.
705 const unsigned char *CallStackBase = nullptr;
706 // The number of elements in the radix tree array.
707 unsigned RadixTreeSize = 0;
708 /// The data access profiles, deserialized from binary data.
709 std::unique_ptr<memprof::DataAccessProfData> DataAccessProfileData;
710
711 Error deserializeRadixTreeBased(const unsigned char *Start,
712 const unsigned char *Ptr,
714
715public:
717
718 LLVM_ABI Error deserialize(const unsigned char *Start,
719 uint64_t MemProfOffset);
720
722 getMemProfRecord(const uint64_t FuncNameHash) const;
723
726
727 // Returns non-owned pointer to data access profile data.
729 return DataAccessProfileData.get();
730 }
731
732 // Return the entire MemProf profile.
734
735 memprof::MemProfSummary *getSummary() const { return MemProfSum.get(); }
736};
737
738/// Reader for the indexed binary instrprof format.
740private:
741 /// The profile data file contents.
742 std::unique_ptr<MemoryBuffer> DataBuffer;
743 /// The profile remapping file contents.
744 std::unique_ptr<MemoryBuffer> RemappingBuffer;
745 /// The index into the profile data.
746 std::unique_ptr<InstrProfReaderIndexBase> Index;
747 /// The profile remapping file contents.
748 std::unique_ptr<InstrProfReaderRemapper> Remapper;
749 /// Profile summary data.
750 std::unique_ptr<ProfileSummary> Summary;
751 /// Context sensitive profile summary data.
752 std::unique_ptr<ProfileSummary> CS_Summary;
753 IndexedMemProfReader MemProfReader;
754 /// The compressed vtable names, to be used for symtab construction.
755 /// A compiler that reads indexed profiles could construct symtab from module
756 /// IR so it doesn't need the decompressed names.
757 StringRef VTableName;
758 /// A memory buffer holding binary ids.
759 ArrayRef<uint8_t> BinaryIdsBuffer;
760
761 // Index to the current record in the record array.
762 unsigned RecordIndex = 0;
763
764 // Read the profile summary. Return a pointer pointing to one byte past the
765 // end of the summary data if it exists or the input \c Cur.
766 // \c UseCS indicates whether to use the context-sensitive profile summary.
767 const unsigned char *readSummary(IndexedInstrProf::ProfVersion Version,
768 const unsigned char *Cur, bool UseCS);
769
770public:
772 std::unique_ptr<MemoryBuffer> DataBuffer,
773 std::unique_ptr<MemoryBuffer> RemappingBuffer = nullptr)
774 : DataBuffer(std::move(DataBuffer)),
775 RemappingBuffer(std::move(RemappingBuffer)) {}
778
779 /// Return the profile version.
780 uint64_t getVersion() const override { return Index->getVersion(); }
781 bool isIRLevelProfile() const override { return Index->isIRLevelProfile(); }
782 bool hasCSIRLevelProfile() const override {
783 return Index->hasCSIRLevelProfile();
784 }
785
786 bool instrEntryBBEnabled() const override {
787 return Index->instrEntryBBEnabled();
788 }
789
790 bool instrLoopEntriesEnabled() const override {
791 return Index->instrLoopEntriesEnabled();
792 }
793
794 bool hasSingleByteCoverage() const override {
795 return Index->hasSingleByteCoverage();
796 }
797
798 bool functionEntryOnly() const override { return Index->functionEntryOnly(); }
799
800 bool hasMemoryProfile() const override { return Index->hasMemoryProfile(); }
801
802 bool hasTemporalProfile() const override {
803 return Index->hasTemporalProfile();
804 }
805
806 /// Returns a BitsetEnum describing the attributes of the indexed instr
807 /// profile.
808 InstrProfKind getProfileKind() const override {
809 return Index->getProfileKind();
810 }
811
812 /// Return true if the given buffer is in an indexed instrprof format.
813 static bool hasFormat(const MemoryBuffer &DataBuffer);
814
815 /// Read the file header.
816 Error readHeader() override;
817 /// Read a single record.
818 Error readNextRecord(NamedInstrProfRecord &Record) override;
819
820 /// Return the NamedInstrProfRecord associated with FuncName and FuncHash.
821 /// When return a hash_mismatch error and MismatchedFuncSum is not nullptr,
822 /// the sum of all counters in the mismatched function will be set to
823 /// MismatchedFuncSum. If there are multiple instances of mismatched
824 /// functions, MismatchedFuncSum returns the maximum. If \c FuncName is not
825 /// found, try to lookup \c DeprecatedFuncName to handle profiles built by
826 /// older compilers.
828 getInstrProfRecord(StringRef FuncName, uint64_t FuncHash,
829 StringRef DeprecatedFuncName = "",
830 uint64_t *MismatchedFuncSum = nullptr);
831
832 /// Return the memprof record for the function identified by
833 /// llvm::md5(Name).
835 return MemProfReader.getMemProfRecord(FuncNameHash);
836 }
837
840 return MemProfReader.getMemProfCallerCalleePairs();
841 }
842
844 return MemProfReader.getAllMemProfData();
845 }
846
847 /// Fill Counts with the profile data for the given function name.
848 Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
849 std::vector<uint64_t> &Counts);
850
851 /// Fill Bitmap with the profile data for the given function name.
852 Error getFunctionBitmap(StringRef FuncName, uint64_t FuncHash,
853 BitVector &Bitmap);
854
855 /// Return the maximum of all known function counts.
856 /// \c UseCS indicates whether to use the context-sensitive count.
858 if (UseCS) {
859 assert(CS_Summary && "No context sensitive profile summary");
860 return CS_Summary->getMaxFunctionCount();
861 } else {
862 assert(Summary && "No profile summary");
863 return Summary->getMaxFunctionCount();
864 }
865 }
866
867 /// Factory method to create an indexed reader.
869 create(const Twine &Path, vfs::FileSystem &FS,
870 const Twine &RemappingPath = "");
871
873 create(std::unique_ptr<MemoryBuffer> Buffer,
874 std::unique_ptr<MemoryBuffer> RemappingBuffer = nullptr);
875
876 // Used for testing purpose only.
878 Index->setValueProfDataEndianness(Endianness);
879 }
880
881 // See description in the base class. This interface is designed
882 // to be used by llvm-profdata (for dumping). Avoid using this when
883 // the client is the compiler.
884 InstrProfSymtab &getSymtab() override;
885
886 /// Return the profile summary.
887 /// \c UseCS indicates whether to use the context-sensitive summary.
889 if (UseCS) {
890 assert(CS_Summary && "No context sensitive summary");
891 return *CS_Summary;
892 } else {
893 assert(Summary && "No profile summary");
894 return *Summary;
895 }
896 }
897
898 /// Return the MemProf summary. Will be null if unavailable (version < 4).
900 return MemProfReader.getSummary();
901 }
902
903 /// Returns non-owned pointer to the data access profile data.
904 /// Will be null if unavailable (version < 4).
906 return MemProfReader.getDataAccessProfileData();
907 }
908
909 Error readBinaryIds(std::vector<llvm::object::BuildID> &BinaryIds) override;
910 Error printBinaryIds(raw_ostream &OS) override;
911};
912
913} // end namespace llvm
914
915#endif // LLVM_PROFILEDATA_INSTRPROFREADER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned uint64_t
This file declares a library for handling Build IDs and using them to find debug info.
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")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
InstrProfLookupTrait::offset_type offset_type
InstrProfLookupTrait::data_type data_type
#define GET_VERSION(V)
#define VARIANT_MASK_CSIR_PROF
#define VARIANT_MASK_MEMPROF
#define VARIANT_MASK_TEMPORAL_PROF
#define VARIANT_MASK_IR_PROF
#define VARIANT_MASK_BYTE_COVERAGE
#define VARIANT_MASK_INSTR_ENTRY
#define VARIANT_MASK_FUNCTION_ENTRY_ONLY
#define VARIANT_MASK_INSTR_LOOP_ENTRIES
Defines facilities for reading and writing on-disk hash tables.
#define error(X)
Contains the forward declaration for vfs::FileSystem, as well as the IntrusiveRefCntPtrInfo specializ...
Value * RHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
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)
memprof::MemProfSummary * getSummary() const
LLVM_ABI memprof::AllMemProfData getAllMemProfData() const
memprof::DataAccessProfData * getDataAccessProfileData() 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.
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.
Definition InstrProf.h:465
const std::string & getMessage() const
Definition InstrProf.h:460
instrprof_error get() const
Definition InstrProf.h:459
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
std::ptrdiff_t difference_type
std::input_iterator_tag iterator_category
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)
ArrayRef< NamedInstrProfRecord > data_type
Error populateSymtab(InstrProfSymtab &Symtab) override
bool hasSingleByteCoverage() const 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
InstrProfReaderIndex(const unsigned char *Buckets, const unsigned char *const Payload, const unsigned char *const Base, IndexedInstrProf::HashT HashType, uint64_t Version)
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
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.
Error error(Error &&E)
InstrProfIterator end()
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.
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.
static LLVM_ABI Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const InstrProfCorrelator *Correlator=nullptr, const object::BuildIDFetcher *BIDFetcher=nullptr, std::optional< ProfCorrelatorKind > BIDFetcherCorrelatorKind=std::nullopt, std::function< void(Error)> Warn=nullptr)
Factory method to create an appropriately typed reader for the given instrprof file.
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.
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,...
Definition InstrProf.h:500
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.
RawInstrProfReader(std::unique_ptr< MemoryBuffer > DataBuffer, const InstrProfCorrelator *Correlator, const object::BuildIDFetcher *BIDFetcher, std::optional< ProfCorrelatorKind > BIDFetcherCorrelatorKind, std::function< void(Error)> Warn)
bool functionEntryOnly() const override
Return true if the profile only instruments function entries.
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool isIRLevelProfile() const override
uint64_t getVersion() const override
Return the profile version.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if the given buffer is in text instrprof format.
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...
Definition Twine.h:82
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.
Definition BuildID.h:41
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
The virtual file system interface.
llvm::SmallVector< Meta, static_cast< int >(Meta::Size)> MemProfSchema
Definition MemProf.h:74
constexpr uint64_t MinimumSupportedVersion
Definition MemProf.h:50
value_type readNext(const CharT *&memory, endianness endian)
Read a value of a particular endianness from a buffer, and increment the buffer past that value.
Definition Endian.h:67
This is an optimization pass for GlobalISel generic memory operations.
RawInstrProfReader< uint64_t > RawInstrProfReader64
OnDiskIterableChainedHashTable< InstrProfLookupTrait > OnDiskHashTableImplV3
OnDiskIterableChainedHashTable< memprof::RecordLookupTrait > MemProfRecordHashTable
constexpr T byteswap(T V) noexcept
Reverses the bytes in the given integer value V.
Definition bit.h:102
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
FuncHash
Definition InstrProf.h:78
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
instrprof_error
Definition InstrProf.h:391
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
endianness
Definition bit.h:71
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
InstrProfKind
An enum describing the attributes of an instrumented profile.
Definition InstrProf.h:366
RawInstrProfReader< uint32_t > RawInstrProfReader32
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
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.
Definition InstrProf.h:893