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 /// Profiling information for a single function.
33 struct InstrProfRecord {
35 InstrProfRecord(StringRef Name, uint64_t Hash, ArrayRef<uint64_t> Counts)
36 : Name(Name), Hash(Hash), Counts(Counts) {}
39 ArrayRef<uint64_t> Counts;
42 /// A file format agnostic iterator over profiling data.
43 class InstrProfIterator : public std::iterator<std::input_iterator_tag,
45 InstrProfReader *Reader;
46 InstrProfRecord Record;
50 InstrProfIterator() : Reader(nullptr) {}
51 InstrProfIterator(InstrProfReader *Reader) : Reader(Reader) { Increment(); }
53 InstrProfIterator &operator++() { Increment(); return *this; }
54 bool operator==(const InstrProfIterator &RHS) { return Reader == RHS.Reader; }
55 bool operator!=(const InstrProfIterator &RHS) { return Reader != RHS.Reader; }
56 InstrProfRecord &operator*() { return Record; }
57 InstrProfRecord *operator->() { return &Record; }
60 /// Base class and interface for reading profiling data of any known instrprof
61 /// format. Provides an iterator over InstrProfRecords.
62 class InstrProfReader {
63 std::error_code LastError;
66 InstrProfReader() : LastError(instrprof_error::success) {}
67 virtual ~InstrProfReader() {}
69 /// Read the header. Required before reading first record.
70 virtual std::error_code readHeader() = 0;
71 /// Read a single record.
72 virtual std::error_code readNextRecord(InstrProfRecord &Record) = 0;
73 /// Iterator over profile data.
74 InstrProfIterator begin() { return InstrProfIterator(this); }
75 InstrProfIterator end() { return InstrProfIterator(); }
78 /// Set the current std::error_code and return same.
79 std::error_code error(std::error_code EC) {
84 /// Clear the current error code and return a successful one.
85 std::error_code success() { return error(instrprof_error::success); }
88 /// Return true if the reader has finished reading the profile data.
89 bool isEOF() { return LastError == instrprof_error::eof; }
90 /// Return true if the reader encountered an error reading profiling data.
91 bool hasError() { return LastError && !isEOF(); }
92 /// Get the current error code.
93 std::error_code getError() { return LastError; }
95 /// Factory method to create an appropriately typed reader for the given
97 static ErrorOr<std::unique_ptr<InstrProfReader>> create(std::string Path);
100 /// Reader for the simple text based instrprof format.
102 /// This format is a simple text format that's suitable for test data. Records
103 /// are separated by one or more blank lines, and record fields are separated by
106 /// Each record consists of a function name, a function hash, a number of
107 /// counters, and then each counter value, in that order.
108 class TextInstrProfReader : public InstrProfReader {
110 /// The profile data file contents.
111 std::unique_ptr<MemoryBuffer> DataBuffer;
112 /// Iterator over the profile data.
114 /// The current set of counter values.
115 std::vector<uint64_t> Counts;
117 TextInstrProfReader(const TextInstrProfReader &) = delete;
118 TextInstrProfReader &operator=(const TextInstrProfReader &) = delete;
120 TextInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer_)
121 : DataBuffer(std::move(DataBuffer_)), Line(*DataBuffer, true, '#') {}
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 /// The current set of counter values.
142 std::vector<uint64_t> Counts;
144 const uint32_t NameSize;
145 const uint32_t NumCounters;
146 const uint64_t FuncHash;
147 const IntPtrT NamePtr;
148 const IntPtrT CounterPtr;
151 const uint64_t Magic;
152 const uint64_t Version;
153 const uint64_t DataSize;
154 const uint64_t CountersSize;
155 const uint64_t NamesSize;
156 const uint64_t CountersDelta;
157 const uint64_t NamesDelta;
160 bool ShouldSwapBytes;
161 uint64_t CountersDelta;
163 const ProfileData *Data;
164 const ProfileData *DataEnd;
165 const uint64_t *CountersStart;
166 const char *NamesStart;
167 const char *ProfileEnd;
169 RawInstrProfReader(const RawInstrProfReader &) = delete;
170 RawInstrProfReader &operator=(const RawInstrProfReader &) = delete;
172 RawInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
173 : DataBuffer(std::move(DataBuffer)) { }
175 static bool hasFormat(const MemoryBuffer &DataBuffer);
176 std::error_code readHeader() override;
177 std::error_code readNextRecord(InstrProfRecord &Record) override;
180 std::error_code readNextHeader(const char *CurrentPos);
181 std::error_code readHeader(const RawHeader &Header);
182 template <class IntT>
183 IntT swap(IntT Int) const {
184 return ShouldSwapBytes ? sys::getSwappedBytes(Int) : Int;
186 const uint64_t *getCounter(IntPtrT CounterPtr) const {
187 ptrdiff_t Offset = (swap(CounterPtr) - CountersDelta) / sizeof(uint64_t);
188 return CountersStart + Offset;
190 const char *getName(IntPtrT NamePtr) const {
191 ptrdiff_t Offset = (swap(NamePtr) - NamesDelta) / sizeof(char);
192 return NamesStart + Offset;
196 typedef RawInstrProfReader<uint32_t> RawInstrProfReader32;
197 typedef RawInstrProfReader<uint64_t> RawInstrProfReader64;
199 namespace IndexedInstrProf {
200 enum class HashT : uint32_t;
203 /// Trait for lookups into the on-disk hash table for the binary instrprof
205 class InstrProfLookupTrait {
206 std::vector<uint64_t> DataBuffer;
207 IndexedInstrProf::HashT HashType;
209 InstrProfLookupTrait(IndexedInstrProf::HashT HashType) : HashType(HashType) {}
212 data_type(StringRef Name, ArrayRef<uint64_t> Data)
213 : Name(Name), Data(Data) {}
215 ArrayRef<uint64_t> Data;
217 typedef StringRef internal_key_type;
218 typedef StringRef external_key_type;
219 typedef uint64_t hash_value_type;
220 typedef uint64_t offset_type;
222 static bool EqualKey(StringRef A, StringRef B) { return A == B; }
223 static StringRef GetInternalKey(StringRef K) { return K; }
225 hash_value_type ComputeHash(StringRef K);
227 static std::pair<offset_type, offset_type>
228 ReadKeyDataLength(const unsigned char *&D) {
229 using namespace support;
230 offset_type KeyLen = endian::readNext<offset_type, little, unaligned>(D);
231 offset_type DataLen = endian::readNext<offset_type, little, unaligned>(D);
232 return std::make_pair(KeyLen, DataLen);
235 StringRef ReadKey(const unsigned char *D, offset_type N) {
236 return StringRef((const char *)D, N);
239 data_type ReadData(StringRef K, const unsigned char *D, offset_type N) {
241 if (N % sizeof(uint64_t))
242 // The data is corrupt, don't try to read it.
243 return data_type("", DataBuffer);
245 using namespace support;
246 // We just treat the data as opaque here. It's simpler to handle in
247 // IndexedInstrProfReader.
248 unsigned NumEntries = N / sizeof(uint64_t);
249 DataBuffer.reserve(NumEntries);
250 for (unsigned I = 0; I < NumEntries; ++I)
251 DataBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
252 return data_type(K, DataBuffer);
255 typedef OnDiskIterableChainedHashTable<InstrProfLookupTrait>
256 InstrProfReaderIndex;
258 /// Reader for the indexed binary instrprof format.
259 class IndexedInstrProfReader : public InstrProfReader {
261 /// The profile data file contents.
262 std::unique_ptr<MemoryBuffer> DataBuffer;
263 /// The index into the profile data.
264 std::unique_ptr<InstrProfReaderIndex> Index;
265 /// Iterator over the profile data.
266 InstrProfReaderIndex::data_iterator RecordIterator;
267 /// Offset into our current data set.
268 size_t CurrentOffset;
269 /// The file format version of the profile data.
270 uint64_t FormatVersion;
271 /// The maximal execution count among all functions.
272 uint64_t MaxFunctionCount;
274 IndexedInstrProfReader(const IndexedInstrProfReader &) = delete;
275 IndexedInstrProfReader &operator=(const IndexedInstrProfReader &) = delete;
277 IndexedInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
278 : DataBuffer(std::move(DataBuffer)), Index(nullptr), CurrentOffset(0) {}
280 /// Return true if the given buffer is in an indexed instrprof format.
281 static bool hasFormat(const MemoryBuffer &DataBuffer);
283 /// Read the file header.
284 std::error_code readHeader() override;
285 /// Read a single record.
286 std::error_code readNextRecord(InstrProfRecord &Record) override;
288 /// Fill Counts with the profile data for the given function name.
289 std::error_code getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
290 std::vector<uint64_t> &Counts);
291 /// Return the maximum of all known function counts.
292 uint64_t getMaximumFunctionCount() { return MaxFunctionCount; }
294 /// Factory method to create an indexed reader.
295 static std::error_code
296 create(std::string Path, std::unique_ptr<IndexedInstrProfReader> &Result);
299 } // end namespace llvm