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 CurValueDataSize;
368 std::vector<llvm::object::BuildID> BinaryIds;
369
370 std::function<void(Error)> Warn;
371
372 /// Maxium counter value 2^56.
373 static const uint64_t MaxCounterValue = (1ULL << 56);
374
375public:
376 RawInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer,
377 const InstrProfCorrelator *Correlator,
378 const object::BuildIDFetcher *BIDFetcher,
379 std::optional<ProfCorrelatorKind> BIDFetcherCorrelatorKind,
380 std::function<void(Error)> Warn)
381 : DataBuffer(std::move(DataBuffer)),
383 Correlator)),
384 BIDFetcher(BIDFetcher),
385 BIDFetcherCorrelatorKind(BIDFetcherCorrelatorKind), Warn(Warn) {
386 assert((!BIDFetcher || BIDFetcherCorrelatorKind) &&
387 "a build ID fetcher needs a correlation kind");
388 }
389
392
393 static bool hasFormat(const MemoryBuffer &DataBuffer);
394 Error readHeader() override;
396 Error readBinaryIds(std::vector<llvm::object::BuildID> &BinaryIds) override;
398
399 uint64_t getVersion() const override { return Version; }
400
401 bool isIRLevelProfile() const override {
402 return (Version & VARIANT_MASK_IR_PROF) != 0;
403 }
404
405 bool hasCSIRLevelProfile() const override {
406 return (Version & VARIANT_MASK_CSIR_PROF) != 0;
407 }
408
409 bool instrEntryBBEnabled() const override {
410 return (Version & VARIANT_MASK_INSTR_ENTRY) != 0;
411 }
412
413 bool instrLoopEntriesEnabled() const override {
414 return (Version & VARIANT_MASK_INSTR_LOOP_ENTRIES) != 0;
415 }
416
417 bool hasSingleByteCoverage() const override {
418 return (Version & VARIANT_MASK_BYTE_COVERAGE) != 0;
419 }
420
421 bool functionEntryOnly() const override {
422 return (Version & VARIANT_MASK_FUNCTION_ENTRY_ONLY) != 0;
423 }
424
425 bool hasMemoryProfile() const override {
426 // Memory profiles have a separate raw format, so this should never be set.
427 assert(!(Version & VARIANT_MASK_MEMPROF));
428 return false;
429 }
430
431 bool hasTemporalProfile() const override {
432 return (Version & VARIANT_MASK_TEMPORAL_PROF) != 0;
433 }
434
435 /// Returns a BitsetEnum describing the attributes of the raw instr profile.
437
439 assert(Symtab.get());
440 return *Symtab.get();
441 }
442
444 getTemporalProfTraces(std::optional<uint64_t> Weight = {}) override;
445
446private:
447 Error createSymtab(InstrProfSymtab &Symtab);
448 Error readNextHeader(const char *CurrentPos);
450
451 template <class IntT> IntT swap(IntT Int) const {
452 return ShouldSwapBytes ? llvm::byteswap(Int) : Int;
453 }
454
455 llvm::endianness getDataEndianness() const {
456 if (!ShouldSwapBytes)
460 else
462 }
463
464 inline uint8_t getNumPaddingBytes(uint64_t SizeInBytes) {
465 return 7 & (sizeof(uint64_t) - SizeInBytes % sizeof(uint64_t));
466 }
467
468 Error readName(NamedInstrProfRecord &Record);
469 Error readFuncHash(NamedInstrProfRecord &Record);
470 Error readRawCounts(InstrProfRecord &Record);
471 Error readRawBitmapBytes(InstrProfRecord &Record);
472 Error readRawUniformCounters(InstrProfRecord &Record);
473 Error readValueProfilingData(InstrProfRecord &Record);
474 bool atEnd() const { return Data == DataEnd; }
475
476 void advanceData() {
477 // `CountersDelta` and `BitmapDelta` are constant zero when using debug info
478 // correlation.
479 if (!Correlator && !BIDFetcherCorrelator) {
480 // The initial CountersDelta is the in-memory address difference between
481 // the data and counts sections:
482 // start(__llvm_prf_cnts) - start(__llvm_prf_data)
483 // As we advance to the next record, we maintain the correct CountersDelta
484 // with respect to the next record.
485 CountersDelta -= sizeof(*Data);
486 BitmapDelta -= sizeof(*Data);
487 UniformCountersDelta -= sizeof(*Data);
488 }
489 Data++;
490 ValueDataStart += CurValueDataSize;
491 }
492
493 const char *getNextHeaderPos() const {
494 assert(atEnd());
495 return (const char *)ValueDataStart;
496 }
497
498 StringRef getName(uint64_t NameRef) const {
499 return Symtab->getFuncOrVarName(swap(NameRef));
500 }
501
502 int getCounterTypeSize() const {
503 return hasSingleByteCoverage() ? sizeof(uint8_t) : sizeof(uint64_t);
504 }
505};
506
509
510namespace IndexedInstrProf {
511
512enum class HashT : uint32_t;
513
514} // end namespace IndexedInstrProf
515
516/// Trait for lookups into the on-disk hash table for the binary instrprof
517/// format.
519 std::vector<NamedInstrProfRecord> DataBuffer;
521 unsigned FormatVersion;
522 // Endianness of the input value profile data.
523 // It should be LE by default, but can be changed
524 // for testing purpose.
525 llvm::endianness ValueProfDataEndianness = llvm::endianness::little;
526
527public:
528 InstrProfLookupTrait(IndexedInstrProf::HashT HashType, unsigned FormatVersion)
529 : HashType(HashType), FormatVersion(FormatVersion) {}
530
532
537
538 static bool EqualKey(StringRef A, StringRef B) { return A == B; }
541
542 LLVM_ABI hash_value_type ComputeHash(StringRef K);
543
544 static std::pair<offset_type, offset_type>
545 ReadKeyDataLength(const unsigned char *&D) {
546 using namespace support;
547
548 offset_type KeyLen =
550 offset_type DataLen =
552 return std::make_pair(KeyLen, DataLen);
553 }
554
555 StringRef ReadKey(const unsigned char *D, offset_type N) {
556 return StringRef((const char *)D, N);
557 }
558
559 LLVM_ABI bool readValueProfilingData(const unsigned char *&D,
560 const unsigned char *const End);
561 LLVM_ABI data_type ReadData(StringRef K, const unsigned char *D,
562 offset_type N);
563
564 // Used for testing purpose only.
566 ValueProfDataEndianness = Endianness;
567 }
568};
569
571 virtual ~InstrProfReaderIndexBase() = default;
572
573 // Read all the profile records with the same key pointed to the current
574 // iterator.
576
577 // Read all the profile records with the key equal to FuncName
578 virtual Error getRecords(StringRef FuncName,
580 virtual void advanceToNextKey() = 0;
581 virtual bool atEnd() const = 0;
582 virtual void setValueProfDataEndianness(llvm::endianness Endianness) = 0;
583 virtual uint64_t getVersion() const = 0;
584 virtual bool isIRLevelProfile() const = 0;
585 virtual bool hasCSIRLevelProfile() const = 0;
586 virtual bool instrEntryBBEnabled() const = 0;
587 virtual bool instrLoopEntriesEnabled() const = 0;
588 virtual bool hasSingleByteCoverage() const = 0;
589 virtual bool functionEntryOnly() const = 0;
590 virtual bool hasMemoryProfile() const = 0;
591 virtual bool hasTemporalProfile() const = 0;
592 virtual InstrProfKind getProfileKind() const = 0;
594};
595
598
601
602template <typename HashTableImpl>
604
605template <typename HashTableImpl>
607private:
608 std::unique_ptr<HashTableImpl> HashTable;
609 typename HashTableImpl::data_iterator RecordIterator;
610 uint64_t FormatVersion;
611
612 friend class InstrProfReaderItaniumRemapper<HashTableImpl>;
613
614public:
615 InstrProfReaderIndex(const unsigned char *Buckets,
616 const unsigned char *const Payload,
617 const unsigned char *const Base,
619 ~InstrProfReaderIndex() override = default;
620
622 Error getRecords(StringRef FuncName,
624 void advanceToNextKey() override { RecordIterator++; }
625
626 bool atEnd() const override {
627 return RecordIterator == HashTable->data_end();
628 }
629
631 HashTable->getInfoObj().setValueProfDataEndianness(Endianness);
632 }
633
634 uint64_t getVersion() const override { return GET_VERSION(FormatVersion); }
635
636 bool isIRLevelProfile() const override {
637 return (FormatVersion & VARIANT_MASK_IR_PROF) != 0;
638 }
639
640 bool hasCSIRLevelProfile() const override {
641 return (FormatVersion & VARIANT_MASK_CSIR_PROF) != 0;
642 }
643
644 bool instrEntryBBEnabled() const override {
645 return (FormatVersion & VARIANT_MASK_INSTR_ENTRY) != 0;
646 }
647
648 bool instrLoopEntriesEnabled() const override {
649 return (FormatVersion & VARIANT_MASK_INSTR_LOOP_ENTRIES) != 0;
650 }
651
652 bool hasSingleByteCoverage() const override {
653 return (FormatVersion & VARIANT_MASK_BYTE_COVERAGE) != 0;
654 }
655
656 bool functionEntryOnly() const override {
657 return (FormatVersion & VARIANT_MASK_FUNCTION_ENTRY_ONLY) != 0;
658 }
659
660 bool hasMemoryProfile() const override {
661 return (FormatVersion & VARIANT_MASK_MEMPROF) != 0;
662 }
663
664 bool hasTemporalProfile() const override {
665 return (FormatVersion & VARIANT_MASK_TEMPORAL_PROF) != 0;
666 }
667
668 InstrProfKind getProfileKind() const override;
669
671 // FIXME: the create method calls 'finalizeSymtab' and sorts a bunch of
672 // arrays/maps. Since there are other data sources other than 'HashTable' to
673 // populate a symtab, it might make sense to have something like this
674 // 1. Let each data source populate Symtab and init the arrays/maps without
675 // calling 'finalizeSymtab'
676 // 2. Call 'finalizeSymtab' once to get all arrays/maps sorted if needed.
677 return Symtab.create(HashTable->keys());
678 }
679};
680
681/// Name matcher supporting fuzzy matching of symbol names to names in profiles.
683public:
684 virtual ~InstrProfReaderRemapper() = default;
686 virtual Error getRecords(StringRef FuncName,
688};
689
691private:
692 /// The MemProf version.
695 /// MemProf summary (if available, version >= 4).
696 std::unique_ptr<memprof::MemProfSummary> MemProfSum;
697 /// MemProf profile schema (if available).
699 /// MemProf record profile data on-disk indexed via llvm::md5(FunctionName).
700 std::unique_ptr<MemProfRecordHashTable> MemProfRecordTable;
701 /// The starting address of the frame array.
702 const unsigned char *FrameBase = nullptr;
703 /// The starting address of the call stack array.
704 const unsigned char *CallStackBase = nullptr;
705 // The number of elements in the radix tree array.
706 unsigned RadixTreeSize = 0;
707 /// The data access profiles, deserialized from binary data.
708 std::unique_ptr<memprof::DataAccessProfData> DataAccessProfileData;
709
710 Error deserializeRadixTreeBased(const unsigned char *Start,
711 const unsigned char *Ptr,
713
714public:
716
717 LLVM_ABI Error deserialize(const unsigned char *Start,
718 uint64_t MemProfOffset);
719
721 getMemProfRecord(const uint64_t FuncNameHash) const;
722
725
726 // Returns non-owned pointer to data access profile data.
728 return DataAccessProfileData.get();
729 }
730
731 // Return the entire MemProf profile.
733
734 memprof::MemProfSummary *getSummary() const { return MemProfSum.get(); }
735};
736
737/// Reader for the indexed binary instrprof format.
739private:
740 /// The profile data file contents.
741 std::unique_ptr<MemoryBuffer> DataBuffer;
742 /// The profile remapping file contents.
743 std::unique_ptr<MemoryBuffer> RemappingBuffer;
744 /// The index into the profile data.
745 std::unique_ptr<InstrProfReaderIndexBase> Index;
746 /// The profile remapping file contents.
747 std::unique_ptr<InstrProfReaderRemapper> Remapper;
748 /// Profile summary data.
749 std::unique_ptr<ProfileSummary> Summary;
750 /// Context sensitive profile summary data.
751 std::unique_ptr<ProfileSummary> CS_Summary;
752 IndexedMemProfReader MemProfReader;
753 /// The compressed vtable names, to be used for symtab construction.
754 /// A compiler that reads indexed profiles could construct symtab from module
755 /// IR so it doesn't need the decompressed names.
756 StringRef VTableName;
757 /// A memory buffer holding binary ids.
758 ArrayRef<uint8_t> BinaryIdsBuffer;
759
760 // Index to the current record in the record array.
761 unsigned RecordIndex = 0;
762
763 // Read the profile summary. Return a pointer pointing to one byte past the
764 // end of the summary data if it exists or the input \c Cur.
765 // \c UseCS indicates whether to use the context-sensitive profile summary.
766 const unsigned char *readSummary(IndexedInstrProf::ProfVersion Version,
767 const unsigned char *Cur, bool UseCS);
768
769public:
771 std::unique_ptr<MemoryBuffer> DataBuffer,
772 std::unique_ptr<MemoryBuffer> RemappingBuffer = nullptr)
773 : DataBuffer(std::move(DataBuffer)),
774 RemappingBuffer(std::move(RemappingBuffer)) {}
777
778 /// Return the profile version.
779 uint64_t getVersion() const override { return Index->getVersion(); }
780 bool isIRLevelProfile() const override { return Index->isIRLevelProfile(); }
781 bool hasCSIRLevelProfile() const override {
782 return Index->hasCSIRLevelProfile();
783 }
784
785 bool instrEntryBBEnabled() const override {
786 return Index->instrEntryBBEnabled();
787 }
788
789 bool instrLoopEntriesEnabled() const override {
790 return Index->instrLoopEntriesEnabled();
791 }
792
793 bool hasSingleByteCoverage() const override {
794 return Index->hasSingleByteCoverage();
795 }
796
797 bool functionEntryOnly() const override { return Index->functionEntryOnly(); }
798
799 bool hasMemoryProfile() const override { return Index->hasMemoryProfile(); }
800
801 bool hasTemporalProfile() const override {
802 return Index->hasTemporalProfile();
803 }
804
805 /// Returns a BitsetEnum describing the attributes of the indexed instr
806 /// profile.
807 InstrProfKind getProfileKind() const override {
808 return Index->getProfileKind();
809 }
810
811 /// Return true if the given buffer is in an indexed instrprof format.
812 static bool hasFormat(const MemoryBuffer &DataBuffer);
813
814 /// Read the file header.
815 Error readHeader() override;
816 /// Read a single record.
817 Error readNextRecord(NamedInstrProfRecord &Record) override;
818
819 /// Return the NamedInstrProfRecord associated with FuncName and FuncHash.
820 /// When return a hash_mismatch error and MismatchedFuncSum is not nullptr,
821 /// the sum of all counters in the mismatched function will be set to
822 /// MismatchedFuncSum. If there are multiple instances of mismatched
823 /// functions, MismatchedFuncSum returns the maximum. If \c FuncName is not
824 /// found, try to lookup \c DeprecatedFuncName to handle profiles built by
825 /// older compilers.
827 getInstrProfRecord(StringRef FuncName, uint64_t FuncHash,
828 StringRef DeprecatedFuncName = "",
829 uint64_t *MismatchedFuncSum = nullptr);
830
831 /// Return the memprof record for the function identified by
832 /// llvm::md5(Name).
834 return MemProfReader.getMemProfRecord(FuncNameHash);
835 }
836
839 return MemProfReader.getMemProfCallerCalleePairs();
840 }
841
843 return MemProfReader.getAllMemProfData();
844 }
845
846 /// Fill Counts with the profile data for the given function name.
847 Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
848 std::vector<uint64_t> &Counts);
849
850 /// Fill Bitmap with the profile data for the given function name.
851 Error getFunctionBitmap(StringRef FuncName, uint64_t FuncHash,
852 BitVector &Bitmap);
853
854 /// Return the maximum of all known function counts.
855 /// \c UseCS indicates whether to use the context-sensitive count.
857 if (UseCS) {
858 assert(CS_Summary && "No context sensitive profile summary");
859 return CS_Summary->getMaxFunctionCount();
860 } else {
861 assert(Summary && "No profile summary");
862 return Summary->getMaxFunctionCount();
863 }
864 }
865
866 /// Factory method to create an indexed reader.
868 create(const Twine &Path, vfs::FileSystem &FS,
869 const Twine &RemappingPath = "");
870
872 create(std::unique_ptr<MemoryBuffer> Buffer,
873 std::unique_ptr<MemoryBuffer> RemappingBuffer = nullptr);
874
875 // Used for testing purpose only.
877 Index->setValueProfDataEndianness(Endianness);
878 }
879
880 // See description in the base class. This interface is designed
881 // to be used by llvm-profdata (for dumping). Avoid using this when
882 // the client is the compiler.
883 InstrProfSymtab &getSymtab() override;
884
885 /// Return the profile summary.
886 /// \c UseCS indicates whether to use the context-sensitive summary.
888 if (UseCS) {
889 assert(CS_Summary && "No context sensitive summary");
890 return *CS_Summary;
891 } else {
892 assert(Summary && "No profile summary");
893 return *Summary;
894 }
895 }
896
897 /// Return the MemProf summary. Will be null if unavailable (version < 4).
899 return MemProfReader.getSummary();
900 }
901
902 /// Returns non-owned pointer to the data access profile data.
903 /// Will be null if unavailable (version < 4).
905 return MemProfReader.getDataAccessProfileData();
906 }
907
908 Error readBinaryIds(std::vector<llvm::object::BuildID> &BinaryIds) override;
909 Error printBinaryIds(raw_ostream &OS) override;
910};
911
912} // end namespace llvm
913
914#endif // LLVM_PROFILEDATA_INSTRPROFREADER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t 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:211
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:320
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:879
#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:907