1 //=-- InstrProfReader.h - Instrumented profiling readers ----------*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for reading profiling data for instrumentation
11 // based PGO and coverage.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_PROFILEDATA_INSTRPROFREADER_H
16 #define LLVM_PROFILEDATA_INSTRPROFREADER_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ProfileData/InstrProf.h"
21 #include "llvm/Support/EndianStream.h"
22 #include "llvm/Support/ErrorOr.h"
23 #include "llvm/Support/LineIterator.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/OnDiskHashTable.h"
26 #include "llvm/Support/raw_ostream.h"
31 class InstrProfReader;
33 /// A file format agnostic iterator over profiling data.
34 class InstrProfIterator : public std::iterator<std::input_iterator_tag,
36 InstrProfReader *Reader;
37 InstrProfRecord Record;
41 InstrProfIterator() : Reader(nullptr) {}
42 InstrProfIterator(InstrProfReader *Reader) : Reader(Reader) { Increment(); }
44 InstrProfIterator &operator++() { Increment(); return *this; }
45 bool operator==(const InstrProfIterator &RHS) { return Reader == RHS.Reader; }
46 bool operator!=(const InstrProfIterator &RHS) { return Reader != RHS.Reader; }
47 InstrProfRecord &operator*() { return Record; }
48 InstrProfRecord *operator->() { return &Record; }
51 /// Base class and interface for reading profiling data of any known instrprof
52 /// format. Provides an iterator over InstrProfRecords.
53 class InstrProfReader {
54 std::error_code LastError;
57 InstrProfReader() : LastError(instrprof_error::success) {}
58 virtual ~InstrProfReader() {}
60 /// Read the header. Required before reading first record.
61 virtual std::error_code readHeader() = 0;
62 /// Read a single record.
63 virtual std::error_code readNextRecord(InstrProfRecord &Record) = 0;
64 /// Iterator over profile data.
65 InstrProfIterator begin() { return InstrProfIterator(this); }
66 InstrProfIterator end() { return InstrProfIterator(); }
69 /// Set the current std::error_code and return same.
70 std::error_code error(std::error_code EC) {
75 /// Clear the current error code and return a successful one.
76 std::error_code success() { return error(instrprof_error::success); }
79 /// Return true if the reader has finished reading the profile data.
80 bool isEOF() { return LastError == instrprof_error::eof; }
81 /// Return true if the reader encountered an error reading profiling data.
82 bool hasError() { return LastError && !isEOF(); }
83 /// Get the current error code.
84 std::error_code getError() { return LastError; }
86 /// Factory method to create an appropriately typed reader for the given
88 static ErrorOr<std::unique_ptr<InstrProfReader>> create(std::string Path);
90 static ErrorOr<std::unique_ptr<InstrProfReader>>
91 create(std::unique_ptr<MemoryBuffer> Buffer);
94 /// Reader for the simple text based instrprof format.
96 /// This format is a simple text format that's suitable for test data. Records
97 /// are separated by one or more blank lines, and record fields are separated by
100 /// Each record consists of a function name, a function hash, a number of
101 /// counters, and then each counter value, in that order.
102 class TextInstrProfReader : public InstrProfReader {
104 /// The profile data file contents.
105 std::unique_ptr<MemoryBuffer> DataBuffer;
106 /// Iterator over the profile data.
109 // String table for holding a unique copy of all the strings in the profile.
110 InstrProfStringTable StringTable;
112 TextInstrProfReader(const TextInstrProfReader &) = delete;
113 TextInstrProfReader &operator=(const TextInstrProfReader &) = delete;
114 std::error_code readValueProfileData(InstrProfRecord &Record);
117 TextInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer_)
118 : DataBuffer(std::move(DataBuffer_)), Line(*DataBuffer, true, '#') {}
120 /// Return true if the given buffer is in text instrprof format.
121 static bool hasFormat(const MemoryBuffer &Buffer);
124 std::error_code readHeader() override { return success(); }
125 /// Read a single record.
126 std::error_code readNextRecord(InstrProfRecord &Record) override;
129 /// Reader for the raw instrprof binary format from runtime.
131 /// This format is a raw memory dump of the instrumentation-baed profiling data
132 /// from the runtime. It has no index.
134 /// Templated on the unsigned type whose size matches pointers on the platform
135 /// that wrote the profile.
136 template <class IntPtrT>
137 class RawInstrProfReader : public InstrProfReader {
139 /// The profile data file contents.
140 std::unique_ptr<MemoryBuffer> DataBuffer;
141 bool ShouldSwapBytes;
142 uint64_t CountersDelta;
144 const RawInstrProf::ProfileData<IntPtrT> *Data;
145 const RawInstrProf::ProfileData<IntPtrT> *DataEnd;
146 const uint64_t *CountersStart;
147 const char *NamesStart;
148 const uint8_t *ValueDataStart;
149 const char *ProfileEnd;
150 uint32_t ValueKindLast;
151 uint32_t CurValueDataSize;
153 // String table for holding a unique copy of all the strings in the profile.
154 InstrProfStringTable StringTable;
155 InstrProfRecord::ValueMapType FunctionPtrToNameMap;
157 RawInstrProfReader(const RawInstrProfReader &) = delete;
158 RawInstrProfReader &operator=(const RawInstrProfReader &) = delete;
160 RawInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
161 : DataBuffer(std::move(DataBuffer)) { }
163 static bool hasFormat(const MemoryBuffer &DataBuffer);
164 std::error_code readHeader() override;
165 std::error_code readNextRecord(InstrProfRecord &Record) override;
168 std::error_code readNextHeader(const char *CurrentPos);
169 std::error_code readHeader(const RawInstrProf::Header &Header);
170 template <class IntT> IntT swap(IntT Int) const {
171 return ShouldSwapBytes ? sys::getSwappedBytes(Int) : Int;
173 support::endianness getDataEndianness() const {
174 support::endianness HostEndian = getHostEndianness();
175 if (!ShouldSwapBytes)
177 if (HostEndian == support::little)
180 return support::little;
183 inline uint8_t getNumPaddingBytes(uint64_t SizeInBytes) {
184 return 7 & (sizeof(uint64_t) - SizeInBytes % sizeof(uint64_t));
186 std::error_code readName(InstrProfRecord &Record);
187 std::error_code readFuncHash(InstrProfRecord &Record);
188 std::error_code readRawCounts(InstrProfRecord &Record);
189 std::error_code readValueProfilingData(InstrProfRecord &Record);
190 bool atEnd() const { return Data == DataEnd; }
193 ValueDataStart += CurValueDataSize;
196 const uint64_t *getCounter(IntPtrT CounterPtr) const {
197 ptrdiff_t Offset = (swap(CounterPtr) - CountersDelta) / sizeof(uint64_t);
198 return CountersStart + Offset;
200 const char *getName(IntPtrT NamePtr) const {
201 ptrdiff_t Offset = (swap(NamePtr) - NamesDelta) / sizeof(char);
202 return NamesStart + Offset;
206 typedef RawInstrProfReader<uint32_t> RawInstrProfReader32;
207 typedef RawInstrProfReader<uint64_t> RawInstrProfReader64;
209 namespace IndexedInstrProf {
210 enum class HashT : uint32_t;
213 /// Trait for lookups into the on-disk hash table for the binary instrprof
215 class InstrProfLookupTrait {
216 std::vector<InstrProfRecord> DataBuffer;
217 IndexedInstrProf::HashT HashType;
218 unsigned FormatVersion;
219 // Endianness of the input value profile data.
220 // It should be LE by default, but can be changed
221 // for testing purpose.
222 support::endianness ValueProfDataEndianness;
223 std::vector<std::pair<uint64_t, const char *>> HashKeys;
226 InstrProfLookupTrait(IndexedInstrProf::HashT HashType, unsigned FormatVersion)
227 : HashType(HashType), FormatVersion(FormatVersion),
228 ValueProfDataEndianness(support::little) {}
230 typedef ArrayRef<InstrProfRecord> data_type;
232 typedef StringRef internal_key_type;
233 typedef StringRef external_key_type;
234 typedef uint64_t hash_value_type;
235 typedef uint64_t offset_type;
237 static bool EqualKey(StringRef A, StringRef B) { return A == B; }
238 static StringRef GetInternalKey(StringRef K) { return K; }
239 static StringRef GetExternalKey(StringRef K) { return K; }
241 hash_value_type ComputeHash(StringRef K);
243 void setHashKeys(std::vector<std::pair<uint64_t, const char *>> HashKeys) {
244 this->HashKeys = std::move(HashKeys);
246 static std::pair<offset_type, offset_type>
247 ReadKeyDataLength(const unsigned char *&D) {
248 using namespace support;
249 offset_type KeyLen = endian::readNext<offset_type, little, unaligned>(D);
250 offset_type DataLen = endian::readNext<offset_type, little, unaligned>(D);
251 return std::make_pair(KeyLen, DataLen);
254 StringRef ReadKey(const unsigned char *D, offset_type N) {
255 return StringRef((const char *)D, N);
258 bool readValueProfilingData(const unsigned char *&D,
259 const unsigned char *const End);
260 data_type ReadData(StringRef K, const unsigned char *D, offset_type N);
262 // Used for testing purpose only.
263 void setValueProfDataEndianness(support::endianness Endianness) {
264 ValueProfDataEndianness = Endianness;
268 struct InstrProfReaderIndexBase {
269 // Read all the profile records with the same key pointed to the current
271 virtual std::error_code getRecords(ArrayRef<InstrProfRecord> &Data) = 0;
272 // Read all the profile records with the key equal to FuncName
273 virtual std::error_code getRecords(StringRef FuncName,
274 ArrayRef<InstrProfRecord> &Data) = 0;
275 virtual void advanceToNextKey() = 0;
276 virtual bool atEnd() const = 0;
277 virtual void setValueProfDataEndianness(support::endianness Endianness) = 0;
278 virtual ~InstrProfReaderIndexBase() {}
279 virtual uint64_t getVersion() const = 0;
282 typedef OnDiskIterableChainedHashTable<InstrProfLookupTrait>
283 OnDiskHashTableImplV3;
285 template <typename HashTableImpl>
286 class InstrProfReaderIndex : public InstrProfReaderIndexBase {
289 std::unique_ptr<HashTableImpl> HashTable;
290 typename HashTableImpl::data_iterator RecordIterator;
291 uint64_t FormatVersion;
293 // String table for holding a unique copy of all the strings in the profile.
294 InstrProfStringTable StringTable;
297 InstrProfReaderIndex(const unsigned char *Buckets,
298 const unsigned char *const Payload,
299 const unsigned char *const Base,
300 IndexedInstrProf::HashT HashType, uint64_t Version);
302 std::error_code getRecords(ArrayRef<InstrProfRecord> &Data) override;
303 std::error_code getRecords(StringRef FuncName,
304 ArrayRef<InstrProfRecord> &Data) override;
305 void advanceToNextKey() override { RecordIterator++; }
306 bool atEnd() const override {
307 return RecordIterator == HashTable->data_end();
309 void setValueProfDataEndianness(support::endianness Endianness) override {
310 HashTable->getInfoObj().setValueProfDataEndianness(Endianness);
312 ~InstrProfReaderIndex() override {}
313 uint64_t getVersion() const override { return FormatVersion; }
316 /// Reader for the indexed binary instrprof format.
317 class IndexedInstrProfReader : public InstrProfReader {
319 /// The profile data file contents.
320 std::unique_ptr<MemoryBuffer> DataBuffer;
321 /// The index into the profile data.
322 std::unique_ptr<InstrProfReaderIndexBase> Index;
323 /// The maximal execution count among all functions.
324 uint64_t MaxFunctionCount;
326 IndexedInstrProfReader(const IndexedInstrProfReader &) = delete;
327 IndexedInstrProfReader &operator=(const IndexedInstrProfReader &) = delete;
330 uint64_t getVersion() const { return Index->getVersion(); }
331 IndexedInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
332 : DataBuffer(std::move(DataBuffer)), Index(nullptr) {}
334 /// Return true if the given buffer is in an indexed instrprof format.
335 static bool hasFormat(const MemoryBuffer &DataBuffer);
337 /// Read the file header.
338 std::error_code readHeader() override;
339 /// Read a single record.
340 std::error_code readNextRecord(InstrProfRecord &Record) override;
342 /// Return the pointer to InstrProfRecord associated with FuncName
344 ErrorOr<InstrProfRecord> getInstrProfRecord(StringRef FuncName,
347 /// Fill Counts with the profile data for the given function name.
348 std::error_code getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
349 std::vector<uint64_t> &Counts);
351 /// Return the maximum of all known function counts.
352 uint64_t getMaximumFunctionCount() { return MaxFunctionCount; }
354 /// Factory method to create an indexed reader.
355 static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
356 create(std::string Path);
358 static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
359 create(std::unique_ptr<MemoryBuffer> Buffer);
361 // Used for testing purpose only.
362 void setValueProfDataEndianness(support::endianness Endianness) {
363 Index->setValueProfDataEndianness(Endianness);
367 } // end namespace llvm