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"
30 class InstrProfReader;
32 /// A file format agnostic iterator over profiling data.
33 class InstrProfIterator : public std::iterator<std::input_iterator_tag,
35 InstrProfReader *Reader;
36 InstrProfRecord Record;
40 InstrProfIterator() : Reader(nullptr) {}
41 InstrProfIterator(InstrProfReader *Reader) : Reader(Reader) { Increment(); }
43 InstrProfIterator &operator++() { Increment(); return *this; }
44 bool operator==(const InstrProfIterator &RHS) { return Reader == RHS.Reader; }
45 bool operator!=(const InstrProfIterator &RHS) { return Reader != RHS.Reader; }
46 InstrProfRecord &operator*() { return Record; }
47 InstrProfRecord *operator->() { return &Record; }
50 /// Base class and interface for reading profiling data of any known instrprof
51 /// format. Provides an iterator over InstrProfRecords.
52 class InstrProfReader {
53 std::error_code LastError;
56 InstrProfReader() : LastError(instrprof_error::success) {}
57 virtual ~InstrProfReader() {}
59 /// Read the header. Required before reading first record.
60 virtual std::error_code readHeader() = 0;
61 /// Read a single record.
62 virtual std::error_code readNextRecord(InstrProfRecord &Record) = 0;
63 /// Iterator over profile data.
64 InstrProfIterator begin() { return InstrProfIterator(this); }
65 InstrProfIterator end() { return InstrProfIterator(); }
68 /// Set the current std::error_code and return same.
69 std::error_code error(std::error_code EC) {
74 /// Clear the current error code and return a successful one.
75 std::error_code success() { return error(instrprof_error::success); }
78 /// Return true if the reader has finished reading the profile data.
79 bool isEOF() { return LastError == instrprof_error::eof; }
80 /// Return true if the reader encountered an error reading profiling data.
81 bool hasError() { return LastError && !isEOF(); }
82 /// Get the current error code.
83 std::error_code getError() { return LastError; }
85 /// Factory method to create an appropriately typed reader for the given
87 static ErrorOr<std::unique_ptr<InstrProfReader>> create(std::string Path);
89 static ErrorOr<std::unique_ptr<InstrProfReader>>
90 create(std::unique_ptr<MemoryBuffer> Buffer);
93 /// Reader for the simple text based instrprof format.
95 /// This format is a simple text format that's suitable for test data. Records
96 /// are separated by one or more blank lines, and record fields are separated by
99 /// Each record consists of a function name, a function hash, a number of
100 /// counters, and then each counter value, in that order.
101 class TextInstrProfReader : public InstrProfReader {
103 /// The profile data file contents.
104 std::unique_ptr<MemoryBuffer> DataBuffer;
105 /// Iterator over the profile data.
108 TextInstrProfReader(const TextInstrProfReader &) = delete;
109 TextInstrProfReader &operator=(const TextInstrProfReader &) = delete;
111 TextInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer_)
112 : DataBuffer(std::move(DataBuffer_)), Line(*DataBuffer, true, '#') {}
115 std::error_code readHeader() override { return success(); }
116 /// Read a single record.
117 std::error_code readNextRecord(InstrProfRecord &Record) override;
120 /// Reader for the raw instrprof binary format from runtime.
122 /// This format is a raw memory dump of the instrumentation-baed profiling data
123 /// from the runtime. It has no index.
125 /// Templated on the unsigned type whose size matches pointers on the platform
126 /// that wrote the profile.
127 template <class IntPtrT>
128 class RawInstrProfReader : public InstrProfReader {
130 /// The profile data file contents.
131 std::unique_ptr<MemoryBuffer> DataBuffer;
133 bool ShouldSwapBytes;
134 uint64_t CountersDelta;
136 const RawInstrProf::ProfileData<IntPtrT> *Data;
137 const RawInstrProf::ProfileData<IntPtrT> *DataEnd;
138 const uint64_t *CountersStart;
139 const char *NamesStart;
140 const char *ProfileEnd;
142 RawInstrProfReader(const RawInstrProfReader &) = delete;
143 RawInstrProfReader &operator=(const RawInstrProfReader &) = delete;
145 RawInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
146 : DataBuffer(std::move(DataBuffer)) { }
148 static bool hasFormat(const MemoryBuffer &DataBuffer);
149 std::error_code readHeader() override;
150 std::error_code readNextRecord(InstrProfRecord &Record) override;
153 std::error_code readNextHeader(const char *CurrentPos);
154 std::error_code readHeader(const RawInstrProf::Header &Header);
155 template <class IntT>
156 IntT swap(IntT Int) const {
157 return ShouldSwapBytes ? sys::getSwappedBytes(Int) : Int;
160 std::error_code readName(InstrProfRecord &Record);
161 std::error_code readFuncHash(InstrProfRecord &Record);
162 std::error_code readRawCounts(InstrProfRecord &Record);
163 bool atEnd() const { return Data == DataEnd; }
164 void advanceData() { Data++; }
166 const uint64_t *getCounter(IntPtrT CounterPtr) const {
167 ptrdiff_t Offset = (swap(CounterPtr) - CountersDelta) / sizeof(uint64_t);
168 return CountersStart + Offset;
170 const char *getName(IntPtrT NamePtr) const {
171 ptrdiff_t Offset = (swap(NamePtr) - NamesDelta) / sizeof(char);
172 return NamesStart + Offset;
176 typedef RawInstrProfReader<uint32_t> RawInstrProfReader32;
177 typedef RawInstrProfReader<uint64_t> RawInstrProfReader64;
179 namespace IndexedInstrProf {
180 enum class HashT : uint32_t;
183 /// Trait for lookups into the on-disk hash table for the binary instrprof
185 class InstrProfLookupTrait {
186 std::vector<InstrProfRecord> DataBuffer;
187 IndexedInstrProf::HashT HashType;
188 unsigned FormatVersion;
189 // Endianness of the input value profile data.
190 // It should be LE by default, but can be changed
191 // for testing purpose.
192 support::endianness ValueProfDataEndianness;
193 std::vector<std::pair<uint64_t, const char *>> HashKeys;
196 InstrProfLookupTrait(IndexedInstrProf::HashT HashType, unsigned FormatVersion)
197 : HashType(HashType), FormatVersion(FormatVersion),
198 ValueProfDataEndianness(support::little) {}
200 typedef ArrayRef<InstrProfRecord> data_type;
202 typedef StringRef internal_key_type;
203 typedef StringRef external_key_type;
204 typedef uint64_t hash_value_type;
205 typedef uint64_t offset_type;
207 static bool EqualKey(StringRef A, StringRef B) { return A == B; }
208 static StringRef GetInternalKey(StringRef K) { return K; }
209 static StringRef GetExternalKey(StringRef K) { return K; }
211 hash_value_type ComputeHash(StringRef K);
213 void setHashKeys(std::vector<std::pair<uint64_t, const char *>> HashKeys) {
214 this->HashKeys = std::move(HashKeys);
216 static std::pair<offset_type, offset_type>
217 ReadKeyDataLength(const unsigned char *&D) {
218 using namespace support;
219 offset_type KeyLen = endian::readNext<offset_type, little, unaligned>(D);
220 offset_type DataLen = endian::readNext<offset_type, little, unaligned>(D);
221 return std::make_pair(KeyLen, DataLen);
224 StringRef ReadKey(const unsigned char *D, offset_type N) {
225 return StringRef((const char *)D, N);
228 bool ReadValueProfilingData(const unsigned char *&D,
229 const unsigned char *const End);
230 data_type ReadData(StringRef K, const unsigned char *D, offset_type N);
232 // Used for testing purpose only.
233 void setValueProfDataEndianness(support::endianness Endianness) {
234 ValueProfDataEndianness = Endianness;
238 class InstrProfReaderIndex {
240 typedef OnDiskIterableChainedHashTable<InstrProfLookupTrait> IndexType;
242 std::unique_ptr<IndexType> Index;
243 IndexType::data_iterator RecordIterator;
244 uint64_t FormatVersion;
246 // String table for holding a unique copy of all the strings in the profile.
247 InstrProfStringTable StringTable;
250 InstrProfReaderIndex() : Index(nullptr) {}
251 void Init(const unsigned char *Buckets, const unsigned char *const Payload,
252 const unsigned char *const Base, IndexedInstrProf::HashT HashType,
255 // Read all the pofile records with the same key pointed to the current
257 std::error_code getRecords(ArrayRef<InstrProfRecord> &Data);
258 // Read all the profile records with the key equal to FuncName
259 std::error_code getRecords(StringRef FuncName,
260 ArrayRef<InstrProfRecord> &Data);
262 void advanceToNextKey() { RecordIterator++; }
263 bool atEnd() const { return RecordIterator == Index->data_end(); }
264 // Used for testing purpose only.
265 void setValueProfDataEndianness(support::endianness Endianness) {
266 Index->getInfoObj().setValueProfDataEndianness(Endianness);
270 /// Reader for the indexed binary instrprof format.
271 class IndexedInstrProfReader : public InstrProfReader {
273 /// The profile data file contents.
274 std::unique_ptr<MemoryBuffer> DataBuffer;
275 /// The index into the profile data.
276 InstrProfReaderIndex Index;
277 /// The maximal execution count among all functions.
278 uint64_t MaxFunctionCount;
280 IndexedInstrProfReader(const IndexedInstrProfReader &) = delete;
281 IndexedInstrProfReader &operator=(const IndexedInstrProfReader &) = delete;
284 IndexedInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
285 : DataBuffer(std::move(DataBuffer)), Index() {}
287 /// Return true if the given buffer is in an indexed instrprof format.
288 static bool hasFormat(const MemoryBuffer &DataBuffer);
290 /// Read the file header.
291 std::error_code readHeader() override;
292 /// Read a single record.
293 std::error_code readNextRecord(InstrProfRecord &Record) override;
295 /// Return the pointer to InstrProfRecord associated with FuncName
297 ErrorOr<InstrProfRecord> getInstrProfRecord(StringRef FuncName,
300 /// Fill Counts with the profile data for the given function name.
301 std::error_code getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
302 std::vector<uint64_t> &Counts);
303 /// Return the maximum of all known function counts.
304 uint64_t getMaximumFunctionCount() { return MaxFunctionCount; }
306 /// Factory method to create an indexed reader.
307 static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
308 create(std::string Path);
310 static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
311 create(std::unique_ptr<MemoryBuffer> Buffer);
313 // Used for testing purpose only.
314 void setValueProfDataEndianness(support::endianness Endianness) {
315 Index.setValueProfDataEndianness(Endianness);
319 } // end namespace llvm