Re-apply "InstrProf: Add unit tests for the profile reader and writer"
[oota-llvm.git] / lib / ProfileData / InstrProfReader.cpp
1 //=-- InstrProfReader.cpp - Instrumented profiling reader -------------------=//
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 clang's
11 // instrumentation based PGO and coverage.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ProfileData/InstrProfReader.h"
16 #include "InstrProfIndexed.h"
17 #include "llvm/ProfileData/InstrProf.h"
18 #include <cassert>
19
20 using namespace llvm;
21
22 static ErrorOr<std::unique_ptr<MemoryBuffer>>
23 setupMemoryBuffer(std::string Path) {
24   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
25       MemoryBuffer::getFileOrSTDIN(Path);
26   if (std::error_code EC = BufferOrErr.getError())
27     return EC;
28   return std::move(BufferOrErr.get());
29 }
30
31 static std::error_code initializeReader(InstrProfReader &Reader) {
32   return Reader.readHeader();
33 }
34
35 ErrorOr<std::unique_ptr<InstrProfReader>>
36 InstrProfReader::create(std::string Path) {
37   // Set up the buffer to read.
38   auto BufferOrError = setupMemoryBuffer(Path);
39   if (std::error_code EC = BufferOrError.getError())
40     return EC;
41   return InstrProfReader::create(std::move(BufferOrError.get()));
42 }
43
44 ErrorOr<std::unique_ptr<InstrProfReader>>
45 InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
46   // Sanity check the buffer.
47   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
48     return instrprof_error::too_large;
49
50   std::unique_ptr<InstrProfReader> Result;
51   // Create the reader.
52   if (IndexedInstrProfReader::hasFormat(*Buffer))
53     Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
54   else if (RawInstrProfReader64::hasFormat(*Buffer))
55     Result.reset(new RawInstrProfReader64(std::move(Buffer)));
56   else if (RawInstrProfReader32::hasFormat(*Buffer))
57     Result.reset(new RawInstrProfReader32(std::move(Buffer)));
58   else
59     Result.reset(new TextInstrProfReader(std::move(Buffer)));
60
61   // Initialize the reader and return the result.
62   if (std::error_code EC = initializeReader(*Result))
63     return EC;
64
65   return std::move(Result);
66 }
67
68 ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
69 IndexedInstrProfReader::create(std::string Path) {
70   // Set up the buffer to read.
71   auto BufferOrError = setupMemoryBuffer(Path);
72   if (std::error_code EC = BufferOrError.getError())
73     return EC;
74   return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
75 }
76
77
78 ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
79 IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
80   // Sanity check the buffer.
81   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
82     return instrprof_error::too_large;
83
84   // Create the reader.
85   if (!IndexedInstrProfReader::hasFormat(*Buffer))
86     return instrprof_error::bad_magic;
87   auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
88
89   // Initialize the reader and return the result.
90   if (std::error_code EC = initializeReader(*Result))
91     return EC;
92
93   return std::move(Result);
94 }
95
96 void InstrProfIterator::Increment() {
97   if (Reader->readNextRecord(Record))
98     *this = InstrProfIterator();
99 }
100
101 std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
102   // Skip empty lines and comments.
103   while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
104     ++Line;
105   // If we hit EOF while looking for a name, we're done.
106   if (Line.is_at_end())
107     return error(instrprof_error::eof);
108
109   // Read the function name.
110   Record.Name = *Line++;
111
112   // Read the function hash.
113   if (Line.is_at_end())
114     return error(instrprof_error::truncated);
115   if ((Line++)->getAsInteger(10, Record.Hash))
116     return error(instrprof_error::malformed);
117
118   // Read the number of counters.
119   uint64_t NumCounters;
120   if (Line.is_at_end())
121     return error(instrprof_error::truncated);
122   if ((Line++)->getAsInteger(10, NumCounters))
123     return error(instrprof_error::malformed);
124   if (NumCounters == 0)
125     return error(instrprof_error::malformed);
126
127   // Read each counter and fill our internal storage with the values.
128   Counts.clear();
129   Counts.reserve(NumCounters);
130   for (uint64_t I = 0; I < NumCounters; ++I) {
131     if (Line.is_at_end())
132       return error(instrprof_error::truncated);
133     uint64_t Count;
134     if ((Line++)->getAsInteger(10, Count))
135       return error(instrprof_error::malformed);
136     Counts.push_back(Count);
137   }
138   // Give the record a reference to our internal counter storage.
139   Record.Counts = Counts;
140
141   return success();
142 }
143
144 template <class IntPtrT>
145 static uint64_t getRawMagic();
146
147 template <>
148 uint64_t getRawMagic<uint64_t>() {
149   return
150     uint64_t(255) << 56 |
151     uint64_t('l') << 48 |
152     uint64_t('p') << 40 |
153     uint64_t('r') << 32 |
154     uint64_t('o') << 24 |
155     uint64_t('f') << 16 |
156     uint64_t('r') <<  8 |
157     uint64_t(129);
158 }
159
160 template <>
161 uint64_t getRawMagic<uint32_t>() {
162   return
163     uint64_t(255) << 56 |
164     uint64_t('l') << 48 |
165     uint64_t('p') << 40 |
166     uint64_t('r') << 32 |
167     uint64_t('o') << 24 |
168     uint64_t('f') << 16 |
169     uint64_t('R') <<  8 |
170     uint64_t(129);
171 }
172
173 template <class IntPtrT>
174 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
175   if (DataBuffer.getBufferSize() < sizeof(uint64_t))
176     return false;
177   uint64_t Magic =
178     *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
179   return getRawMagic<IntPtrT>() == Magic ||
180     sys::getSwappedBytes(getRawMagic<IntPtrT>()) == Magic;
181 }
182
183 template <class IntPtrT>
184 std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
185   if (!hasFormat(*DataBuffer))
186     return error(instrprof_error::bad_magic);
187   if (DataBuffer->getBufferSize() < sizeof(RawHeader))
188     return error(instrprof_error::bad_header);
189   auto *Header =
190     reinterpret_cast<const RawHeader *>(DataBuffer->getBufferStart());
191   ShouldSwapBytes = Header->Magic != getRawMagic<IntPtrT>();
192   return readHeader(*Header);
193 }
194
195 template <class IntPtrT>
196 std::error_code
197 RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
198   const char *End = DataBuffer->getBufferEnd();
199   // Skip zero padding between profiles.
200   while (CurrentPos != End && *CurrentPos == 0)
201     ++CurrentPos;
202   // If there's nothing left, we're done.
203   if (CurrentPos == End)
204     return instrprof_error::eof;
205   // If there isn't enough space for another header, this is probably just
206   // garbage at the end of the file.
207   if (CurrentPos + sizeof(RawHeader) > End)
208     return instrprof_error::malformed;
209   // The writer ensures each profile is padded to start at an aligned address.
210   if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
211     return instrprof_error::malformed;
212   // The magic should have the same byte order as in the previous header.
213   uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
214   if (Magic != swap(getRawMagic<IntPtrT>()))
215     return instrprof_error::bad_magic;
216
217   // There's another profile to read, so we need to process the header.
218   auto *Header = reinterpret_cast<const RawHeader *>(CurrentPos);
219   return readHeader(*Header);
220 }
221
222 static uint64_t getRawVersion() {
223   return 1;
224 }
225
226 template <class IntPtrT>
227 std::error_code
228 RawInstrProfReader<IntPtrT>::readHeader(const RawHeader &Header) {
229   if (swap(Header.Version) != getRawVersion())
230     return error(instrprof_error::unsupported_version);
231
232   CountersDelta = swap(Header.CountersDelta);
233   NamesDelta = swap(Header.NamesDelta);
234   auto DataSize = swap(Header.DataSize);
235   auto CountersSize = swap(Header.CountersSize);
236   auto NamesSize = swap(Header.NamesSize);
237
238   ptrdiff_t DataOffset = sizeof(RawHeader);
239   ptrdiff_t CountersOffset = DataOffset + sizeof(ProfileData) * DataSize;
240   ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
241   size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize;
242
243   auto *Start = reinterpret_cast<const char *>(&Header);
244   if (Start + ProfileSize > DataBuffer->getBufferEnd())
245     return error(instrprof_error::bad_header);
246
247   Data = reinterpret_cast<const ProfileData *>(Start + DataOffset);
248   DataEnd = Data + DataSize;
249   CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
250   NamesStart = Start + NamesOffset;
251   ProfileEnd = Start + ProfileSize;
252
253   return success();
254 }
255
256 template <class IntPtrT>
257 std::error_code
258 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
259   if (Data == DataEnd)
260     if (std::error_code EC = readNextHeader(ProfileEnd))
261       return EC;
262
263   // Get the raw data.
264   StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize));
265   uint32_t NumCounters = swap(Data->NumCounters);
266   if (NumCounters == 0)
267     return error(instrprof_error::malformed);
268   auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr), NumCounters);
269
270   // Check bounds.
271   auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
272   if (RawName.data() < NamesStart ||
273       RawName.data() + RawName.size() > DataBuffer->getBufferEnd() ||
274       RawCounts.data() < CountersStart ||
275       RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
276     return error(instrprof_error::malformed);
277
278   // Store the data in Record, byte-swapping as necessary.
279   Record.Hash = swap(Data->FuncHash);
280   Record.Name = RawName;
281   if (ShouldSwapBytes) {
282     Counts.clear();
283     Counts.reserve(RawCounts.size());
284     for (uint64_t Count : RawCounts)
285       Counts.push_back(swap(Count));
286     Record.Counts = Counts;
287   } else
288     Record.Counts = RawCounts;
289
290   // Iterate.
291   ++Data;
292   return success();
293 }
294
295 namespace llvm {
296 template class RawInstrProfReader<uint32_t>;
297 template class RawInstrProfReader<uint64_t>;
298 }
299
300 InstrProfLookupTrait::hash_value_type
301 InstrProfLookupTrait::ComputeHash(StringRef K) {
302   return IndexedInstrProf::ComputeHash(HashType, K);
303 }
304
305 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
306   if (DataBuffer.getBufferSize() < 8)
307     return false;
308   using namespace support;
309   uint64_t Magic =
310       endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
311   return Magic == IndexedInstrProf::Magic;
312 }
313
314 std::error_code IndexedInstrProfReader::readHeader() {
315   const unsigned char *Start =
316       (const unsigned char *)DataBuffer->getBufferStart();
317   const unsigned char *Cur = Start;
318   if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
319     return error(instrprof_error::truncated);
320
321   using namespace support;
322
323   // Check the magic number.
324   uint64_t Magic = endian::readNext<uint64_t, little, unaligned>(Cur);
325   if (Magic != IndexedInstrProf::Magic)
326     return error(instrprof_error::bad_magic);
327
328   // Read the version.
329   FormatVersion = endian::readNext<uint64_t, little, unaligned>(Cur);
330   if (FormatVersion > IndexedInstrProf::Version)
331     return error(instrprof_error::unsupported_version);
332
333   // Read the maximal function count.
334   MaxFunctionCount = endian::readNext<uint64_t, little, unaligned>(Cur);
335
336   // Read the hash type and start offset.
337   IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
338       endian::readNext<uint64_t, little, unaligned>(Cur));
339   if (HashType > IndexedInstrProf::HashT::Last)
340     return error(instrprof_error::unsupported_hash_type);
341   uint64_t HashOffset = endian::readNext<uint64_t, little, unaligned>(Cur);
342
343   // The rest of the file is an on disk hash table.
344   Index.reset(InstrProfReaderIndex::Create(Start + HashOffset, Cur, Start,
345                                            InstrProfLookupTrait(HashType)));
346   // Set up our iterator for readNextRecord.
347   RecordIterator = Index->data_begin();
348
349   return success();
350 }
351
352 std::error_code IndexedInstrProfReader::getFunctionCounts(
353     StringRef FuncName, uint64_t FuncHash, std::vector<uint64_t> &Counts) {
354   auto Iter = Index->find(FuncName);
355   if (Iter == Index->end())
356     return error(instrprof_error::unknown_function);
357
358   // Found it. Look for counters with the right hash.
359   ArrayRef<uint64_t> Data = (*Iter).Data;
360   uint64_t NumCounts;
361   for (uint64_t I = 0, E = Data.size(); I != E; I += NumCounts) {
362     // The function hash comes first.
363     uint64_t FoundHash = Data[I++];
364     // In v1, we have at least one count. Later, we have the number of counts.
365     if (I == E)
366       return error(instrprof_error::malformed);
367     NumCounts = FormatVersion == 1 ? E - I : Data[I++];
368     // If we have more counts than data, this is bogus.
369     if (I + NumCounts > E)
370       return error(instrprof_error::malformed);
371     // Check for a match and fill the vector if there is one.
372     if (FoundHash == FuncHash) {
373       Counts = Data.slice(I, NumCounts);
374       return success();
375     }
376   }
377   return error(instrprof_error::hash_mismatch);
378 }
379
380 std::error_code
381 IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) {
382   // Are we out of records?
383   if (RecordIterator == Index->data_end())
384     return error(instrprof_error::eof);
385
386   // Record the current function name.
387   Record.Name = (*RecordIterator).Name;
388
389   ArrayRef<uint64_t> Data = (*RecordIterator).Data;
390   // Valid data starts with a hash and either a count or the number of counts.
391   if (CurrentOffset + 1 > Data.size())
392     return error(instrprof_error::malformed);
393   // First we have a function hash.
394   Record.Hash = Data[CurrentOffset++];
395   // In version 1 we knew the number of counters implicitly, but in newer
396   // versions we store the number of counters next.
397   uint64_t NumCounts =
398       FormatVersion == 1 ? Data.size() - CurrentOffset : Data[CurrentOffset++];
399   if (CurrentOffset + NumCounts > Data.size())
400     return error(instrprof_error::malformed);
401   // And finally the counts themselves.
402   Record.Counts = Data.slice(CurrentOffset, NumCounts);
403
404   // If we've exhausted this function's data, increment the record.
405   CurrentOffset += NumCounts;
406   if (CurrentOffset == Data.size()) {
407     ++RecordIterator;
408     CurrentOffset = 0;
409   }
410
411   return success();
412 }