Revert "InstrProf: Add unit tests for the profile reader and writer"
[oota-llvm.git] / include / llvm / ProfileData / InstrProfReader.h
1 //=-- InstrProfReader.h - Instrumented profiling readers ----------*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for reading profiling data for instrumentation
11 // based PGO and coverage.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_PROFILEDATA_INSTRPROFREADER_H
16 #define LLVM_PROFILEDATA_INSTRPROFREADER_H
17
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 <iterator>
27
28 namespace llvm {
29
30 class InstrProfReader;
31
32 /// Profiling information for a single function.
33 struct InstrProfRecord {
34   InstrProfRecord() {}
35   InstrProfRecord(StringRef Name, uint64_t Hash, ArrayRef<uint64_t> Counts)
36       : Name(Name), Hash(Hash), Counts(Counts) {}
37   StringRef Name;
38   uint64_t Hash;
39   ArrayRef<uint64_t> Counts;
40 };
41
42 /// A file format agnostic iterator over profiling data.
43 class InstrProfIterator : public std::iterator<std::input_iterator_tag,
44                                                InstrProfRecord> {
45   InstrProfReader *Reader;
46   InstrProfRecord Record;
47
48   void Increment();
49 public:
50   InstrProfIterator() : Reader(nullptr) {}
51   InstrProfIterator(InstrProfReader *Reader) : Reader(Reader) { Increment(); }
52
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; }
58 };
59
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;
64
65 public:
66   InstrProfReader() : LastError(instrprof_error::success) {}
67   virtual ~InstrProfReader() {}
68
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(); }
76
77 protected:
78   /// Set the current std::error_code and return same.
79   std::error_code error(std::error_code EC) {
80     LastError = EC;
81     return EC;
82   }
83
84   /// Clear the current error code and return a successful one.
85   std::error_code success() { return error(instrprof_error::success); }
86
87 public:
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; }
94
95   /// Factory method to create an appropriately typed reader for the given
96   /// instrprof file.
97   static ErrorOr<std::unique_ptr<InstrProfReader>> create(std::string Path);
98 };
99
100 /// Reader for the simple text based instrprof format.
101 ///
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
104 /// new lines.
105 ///
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 {
109 private:
110   /// The profile data file contents.
111   std::unique_ptr<MemoryBuffer> DataBuffer;
112   /// Iterator over the profile data.
113   line_iterator Line;
114   /// The current set of counter values.
115   std::vector<uint64_t> Counts;
116
117   TextInstrProfReader(const TextInstrProfReader &) = delete;
118   TextInstrProfReader &operator=(const TextInstrProfReader &) = delete;
119 public:
120   TextInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer_)
121       : DataBuffer(std::move(DataBuffer_)), Line(*DataBuffer, true, '#') {}
122
123   /// Read the header.
124   std::error_code readHeader() override { return success(); }
125   /// Read a single record.
126   std::error_code readNextRecord(InstrProfRecord &Record) override;
127 };
128
129 /// Reader for the raw instrprof binary format from runtime.
130 ///
131 /// This format is a raw memory dump of the instrumentation-baed profiling data
132 /// from the runtime.  It has no index.
133 ///
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 {
138 private:
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;
143   struct ProfileData {
144     const uint32_t NameSize;
145     const uint32_t NumCounters;
146     const uint64_t FuncHash;
147     const IntPtrT NamePtr;
148     const IntPtrT CounterPtr;
149   };
150   struct RawHeader {
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;
158   };
159
160   bool ShouldSwapBytes;
161   uint64_t CountersDelta;
162   uint64_t NamesDelta;
163   const ProfileData *Data;
164   const ProfileData *DataEnd;
165   const uint64_t *CountersStart;
166   const char *NamesStart;
167   const char *ProfileEnd;
168
169   RawInstrProfReader(const RawInstrProfReader &) = delete;
170   RawInstrProfReader &operator=(const RawInstrProfReader &) = delete;
171 public:
172   RawInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
173       : DataBuffer(std::move(DataBuffer)) { }
174
175   static bool hasFormat(const MemoryBuffer &DataBuffer);
176   std::error_code readHeader() override;
177   std::error_code readNextRecord(InstrProfRecord &Record) override;
178
179 private:
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;
185   }
186   const uint64_t *getCounter(IntPtrT CounterPtr) const {
187     ptrdiff_t Offset = (swap(CounterPtr) - CountersDelta) / sizeof(uint64_t);
188     return CountersStart + Offset;
189   }
190   const char *getName(IntPtrT NamePtr) const {
191     ptrdiff_t Offset = (swap(NamePtr) - NamesDelta) / sizeof(char);
192     return NamesStart + Offset;
193   }
194 };
195
196 typedef RawInstrProfReader<uint32_t> RawInstrProfReader32;
197 typedef RawInstrProfReader<uint64_t> RawInstrProfReader64;
198
199 namespace IndexedInstrProf {
200 enum class HashT : uint32_t;
201 }
202
203 /// Trait for lookups into the on-disk hash table for the binary instrprof
204 /// format.
205 class InstrProfLookupTrait {
206   std::vector<uint64_t> DataBuffer;
207   IndexedInstrProf::HashT HashType;
208 public:
209   InstrProfLookupTrait(IndexedInstrProf::HashT HashType) : HashType(HashType) {}
210
211   struct data_type {
212     data_type(StringRef Name, ArrayRef<uint64_t> Data)
213         : Name(Name), Data(Data) {}
214     StringRef Name;
215     ArrayRef<uint64_t> Data;
216   };
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;
221
222   static bool EqualKey(StringRef A, StringRef B) { return A == B; }
223   static StringRef GetInternalKey(StringRef K) { return K; }
224
225   hash_value_type ComputeHash(StringRef K);
226
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);
233   }
234
235   StringRef ReadKey(const unsigned char *D, offset_type N) {
236     return StringRef((const char *)D, N);
237   }
238
239   data_type ReadData(StringRef K, const unsigned char *D, offset_type N) {
240     DataBuffer.clear();
241     if (N % sizeof(uint64_t))
242       // The data is corrupt, don't try to read it.
243       return data_type("", DataBuffer);
244
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);
253   }
254 };
255 typedef OnDiskIterableChainedHashTable<InstrProfLookupTrait>
256     InstrProfReaderIndex;
257
258 /// Reader for the indexed binary instrprof format.
259 class IndexedInstrProfReader : public InstrProfReader {
260 private:
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;
273
274   IndexedInstrProfReader(const IndexedInstrProfReader &) = delete;
275   IndexedInstrProfReader &operator=(const IndexedInstrProfReader &) = delete;
276 public:
277   IndexedInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
278       : DataBuffer(std::move(DataBuffer)), Index(nullptr), CurrentOffset(0) {}
279
280   /// Return true if the given buffer is in an indexed instrprof format.
281   static bool hasFormat(const MemoryBuffer &DataBuffer);
282
283   /// Read the file header.
284   std::error_code readHeader() override;
285   /// Read a single record.
286   std::error_code readNextRecord(InstrProfRecord &Record) override;
287
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; }
293
294   /// Factory method to create an indexed reader.
295   static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
296   create(std::string Path);
297 };
298
299 } // end namespace llvm
300
301 #endif