da68242b4617ca86dbc128c650d197a2badae9f4
[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 "llvm/ADT/STLExtras.h"
17 #include <cassert>
18
19 using namespace llvm;
20
21 static ErrorOr<std::unique_ptr<MemoryBuffer>>
22 setupMemoryBuffer(std::string Path) {
23   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
24       MemoryBuffer::getFileOrSTDIN(Path);
25   if (std::error_code EC = BufferOrErr.getError())
26     return EC;
27   return std::move(BufferOrErr.get());
28 }
29
30 static std::error_code initializeReader(InstrProfReader &Reader) {
31   return Reader.readHeader();
32 }
33
34 ErrorOr<std::unique_ptr<InstrProfReader>>
35 InstrProfReader::create(std::string Path) {
36   // Set up the buffer to read.
37   auto BufferOrError = setupMemoryBuffer(Path);
38   if (std::error_code EC = BufferOrError.getError())
39     return EC;
40   return InstrProfReader::create(std::move(BufferOrError.get()));
41 }
42
43 ErrorOr<std::unique_ptr<InstrProfReader>>
44 InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
45   // Sanity check the buffer.
46   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
47     return instrprof_error::too_large;
48
49   std::unique_ptr<InstrProfReader> Result;
50   // Create the reader.
51   if (IndexedInstrProfReader::hasFormat(*Buffer))
52     Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
53   else if (RawInstrProfReader64::hasFormat(*Buffer))
54     Result.reset(new RawInstrProfReader64(std::move(Buffer)));
55   else if (RawInstrProfReader32::hasFormat(*Buffer))
56     Result.reset(new RawInstrProfReader32(std::move(Buffer)));
57   else if (TextInstrProfReader::hasFormat(*Buffer))
58     Result.reset(new TextInstrProfReader(std::move(Buffer)));
59   else
60     return instrprof_error::unrecognized_format;
61
62   // Initialize the reader and return the result.
63   if (std::error_code EC = initializeReader(*Result))
64     return EC;
65
66   return std::move(Result);
67 }
68
69 ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
70 IndexedInstrProfReader::create(std::string Path) {
71   // Set up the buffer to read.
72   auto BufferOrError = setupMemoryBuffer(Path);
73   if (std::error_code EC = BufferOrError.getError())
74     return EC;
75   return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
76 }
77
78
79 ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
80 IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
81   // Sanity check the buffer.
82   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
83     return instrprof_error::too_large;
84
85   // Create the reader.
86   if (!IndexedInstrProfReader::hasFormat(*Buffer))
87     return instrprof_error::bad_magic;
88   auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
89
90   // Initialize the reader and return the result.
91   if (std::error_code EC = initializeReader(*Result))
92     return EC;
93
94   return std::move(Result);
95 }
96
97 void InstrProfIterator::Increment() {
98   if (Reader->readNextRecord(Record))
99     *this = InstrProfIterator();
100 }
101
102 bool TextInstrProfReader::hasFormat(const MemoryBuffer &Buffer) {
103   // Verify that this really looks like plain ASCII text by checking a
104   // 'reasonable' number of characters (up to profile magic size).
105   size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));
106   StringRef buffer = Buffer.getBufferStart();
107   return count == 0 ||
108          std::all_of(buffer.begin(), buffer.begin() + count,
109                      [](char c) { return ::isprint(c) || ::isspace(c); });
110 }
111
112 std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
113   // Skip empty lines and comments.
114   while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
115     ++Line;
116   // If we hit EOF while looking for a name, we're done.
117   if (Line.is_at_end())
118     return error(instrprof_error::eof);
119
120   // Read the function name.
121   Record.Name = *Line++;
122
123   // Read the function hash.
124   if (Line.is_at_end())
125     return error(instrprof_error::truncated);
126   if ((Line++)->getAsInteger(0, Record.Hash))
127     return error(instrprof_error::malformed);
128
129   // Read the number of counters.
130   uint64_t NumCounters;
131   if (Line.is_at_end())
132     return error(instrprof_error::truncated);
133   if ((Line++)->getAsInteger(10, NumCounters))
134     return error(instrprof_error::malformed);
135   if (NumCounters == 0)
136     return error(instrprof_error::malformed);
137
138   // Read each counter and fill our internal storage with the values.
139   Record.Counts.clear();
140   Record.Counts.reserve(NumCounters);
141   for (uint64_t I = 0; I < NumCounters; ++I) {
142     if (Line.is_at_end())
143       return error(instrprof_error::truncated);
144     uint64_t Count;
145     if ((Line++)->getAsInteger(10, Count))
146       return error(instrprof_error::malformed);
147     Record.Counts.push_back(Count);
148   }
149
150   return success();
151 }
152
153 template <class IntPtrT>
154 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
155   if (DataBuffer.getBufferSize() < sizeof(uint64_t))
156     return false;
157   uint64_t Magic =
158     *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
159   return RawInstrProf::getMagic<IntPtrT>() == Magic ||
160          sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
161 }
162
163 template <class IntPtrT>
164 std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
165   if (!hasFormat(*DataBuffer))
166     return error(instrprof_error::bad_magic);
167   if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
168     return error(instrprof_error::bad_header);
169   auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
170       DataBuffer->getBufferStart());
171   ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
172   return readHeader(*Header);
173 }
174
175 template <class IntPtrT>
176 std::error_code
177 RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
178   const char *End = DataBuffer->getBufferEnd();
179   // Skip zero padding between profiles.
180   while (CurrentPos != End && *CurrentPos == 0)
181     ++CurrentPos;
182   // If there's nothing left, we're done.
183   if (CurrentPos == End)
184     return instrprof_error::eof;
185   // If there isn't enough space for another header, this is probably just
186   // garbage at the end of the file.
187   if (CurrentPos + sizeof(RawInstrProf::Header) > End)
188     return instrprof_error::malformed;
189   // The writer ensures each profile is padded to start at an aligned address.
190   if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
191     return instrprof_error::malformed;
192   // The magic should have the same byte order as in the previous header.
193   uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
194   if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
195     return instrprof_error::bad_magic;
196
197   // There's another profile to read, so we need to process the header.
198   auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
199   return readHeader(*Header);
200 }
201
202 template <class IntPtrT>
203 std::error_code RawInstrProfReader<IntPtrT>::readHeader(
204     const RawInstrProf::Header &Header) {
205   if (swap(Header.Version) != RawInstrProf::Version)
206     return error(instrprof_error::unsupported_version);
207
208   CountersDelta = swap(Header.CountersDelta);
209   NamesDelta = swap(Header.NamesDelta);
210   auto DataSize = swap(Header.DataSize);
211   auto CountersSize = swap(Header.CountersSize);
212   auto NamesSize = swap(Header.NamesSize);
213   auto ValueDataSize = swap(Header.ValueDataSize);
214   ValueKindLast = swap(Header.ValueKindLast);
215
216   auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
217   auto PaddingSize = getNumPaddingBytes(NamesSize);
218
219   ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
220   ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
221   ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
222   ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
223   size_t ProfileSize = ValueDataOffset + ValueDataSize;
224
225   auto *Start = reinterpret_cast<const char *>(&Header);
226   if (Start + ProfileSize > DataBuffer->getBufferEnd())
227     return error(instrprof_error::bad_header);
228
229   Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
230       Start + DataOffset);
231   DataEnd = Data + DataSize;
232   CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
233   NamesStart = Start + NamesOffset;
234   ValueDataStart = reinterpret_cast<const uint8_t*>(Start + ValueDataOffset);
235   ProfileEnd = Start + ProfileSize;
236
237   FunctionPtrToNameMap.clear();
238   for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
239     const IntPtrT FPtr = swap(I->FunctionPointer);
240     if (!FPtr)
241       continue;
242     StringRef FunctionName(getName(I->NamePtr), swap(I->NameSize));
243     const char* NameEntryPtr = StringTable.insertString(FunctionName);
244     FunctionPtrToNameMap.push_back(std::pair<const IntPtrT, const char*>
245                                    (FPtr, NameEntryPtr));
246   }
247   std::sort(FunctionPtrToNameMap.begin(), FunctionPtrToNameMap.end(), less_first());
248   FunctionPtrToNameMap.erase(std::unique(FunctionPtrToNameMap.begin(),
249                                          FunctionPtrToNameMap.end()),
250                                          FunctionPtrToNameMap.end());
251   return success();
252 }
253
254 template <class IntPtrT>
255 std::error_code RawInstrProfReader<IntPtrT>::readName(InstrProfRecord &Record) {
256   Record.Name = StringRef(getName(Data->NamePtr), swap(Data->NameSize));
257   if (Record.Name.data() < NamesStart ||
258       Record.Name.data() + Record.Name.size() >
259           reinterpret_cast<const char *>(ValueDataStart))
260     return error(instrprof_error::malformed);
261   return success();
262 }
263
264 template <class IntPtrT>
265 std::error_code RawInstrProfReader<IntPtrT>::readFuncHash(
266     InstrProfRecord &Record) {
267   Record.Hash = swap(Data->FuncHash);
268   return success();
269 }
270
271 template <class IntPtrT>
272 std::error_code RawInstrProfReader<IntPtrT>::readRawCounts(
273     InstrProfRecord &Record) {
274   uint32_t NumCounters = swap(Data->NumCounters);
275   IntPtrT CounterPtr = Data->CounterPtr;
276   if (NumCounters == 0)
277     return error(instrprof_error::malformed);
278
279   auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
280   auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
281
282   // Check bounds.
283   if (RawCounts.data() < CountersStart ||
284       RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
285     return error(instrprof_error::malformed);
286
287   if (ShouldSwapBytes) {
288     Record.Counts.clear();
289     Record.Counts.reserve(RawCounts.size());
290     for (uint64_t Count : RawCounts)
291       Record.Counts.push_back(swap(Count));
292   } else
293     Record.Counts = RawCounts;
294
295   return success();
296 }
297
298 template <class IntPtrT>
299 std::error_code
300 RawInstrProfReader<IntPtrT>::readValueProfilingData(InstrProfRecord &Record) {
301
302   Record.clearValueData();
303   CurValueDataSize = 0;
304   // Need to match the logic in value profile dumper code in compiler-rt:
305   uint32_t NumValueKinds = 0;
306   for (uint32_t I = 0; I < IPVK_Last + 1; I++)
307     NumValueKinds += (Data->NumValueSites[I] != 0);
308
309   if (!NumValueKinds)
310     return success();
311
312   ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
313       ValueProfData::getValueProfData(ValueDataStart,
314                                       (const unsigned char *)ProfileEnd,
315                                       getDataEndianness());
316
317   if (VDataPtrOrErr.getError())
318     return VDataPtrOrErr.getError();
319
320   VDataPtrOrErr.get()->deserializeTo(Record, &FunctionPtrToNameMap);
321   CurValueDataSize = VDataPtrOrErr.get()->getSize();
322   return success();
323 }
324
325 template <class IntPtrT>
326 std::error_code
327 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
328   if (atEnd())
329     if (std::error_code EC = readNextHeader(ProfileEnd))
330       return EC;
331
332   // Read name ad set it in Record.
333   if (std::error_code EC = readName(Record))
334     return EC;
335
336   // Read FuncHash and set it in Record.
337   if (std::error_code EC = readFuncHash(Record))
338     return EC;
339
340   // Read raw counts and set Record.
341   if (std::error_code EC = readRawCounts(Record))
342     return EC;
343
344   // Read value data and set Record.
345   if (std::error_code EC = readValueProfilingData(Record))
346     return EC;
347
348   // Iterate.
349   advanceData();
350   return success();
351 }
352
353 namespace llvm {
354 template class RawInstrProfReader<uint32_t>;
355 template class RawInstrProfReader<uint64_t>;
356 }
357
358 InstrProfLookupTrait::hash_value_type
359 InstrProfLookupTrait::ComputeHash(StringRef K) {
360   return IndexedInstrProf::ComputeHash(HashType, K);
361 }
362
363 typedef InstrProfLookupTrait::data_type data_type;
364 typedef InstrProfLookupTrait::offset_type offset_type;
365
366 bool InstrProfLookupTrait::readValueProfilingData(
367     const unsigned char *&D, const unsigned char *const End) {
368   ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
369       ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
370
371   if (VDataPtrOrErr.getError())
372     return false;
373
374   VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), &HashKeys);
375   D += VDataPtrOrErr.get()->TotalSize;
376
377   return true;
378 }
379
380 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
381                                          offset_type N) {
382   // Check if the data is corrupt. If so, don't try to read it.
383   if (N % sizeof(uint64_t))
384     return data_type();
385
386   DataBuffer.clear();
387   std::vector<uint64_t> CounterBuffer;
388
389   using namespace support;
390   const unsigned char *End = D + N;
391   while (D < End) {
392     // Read hash.
393     if (D + sizeof(uint64_t) >= End)
394       return data_type();
395     uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
396
397     // Initialize number of counters for FormatVersion == 1.
398     uint64_t CountsSize = N / sizeof(uint64_t) - 1;
399     // If format version is different then read the number of counters.
400     if (FormatVersion != 1) {
401       if (D + sizeof(uint64_t) > End)
402         return data_type();
403       CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
404     }
405     // Read counter values.
406     if (D + CountsSize * sizeof(uint64_t) > End)
407       return data_type();
408
409     CounterBuffer.clear();
410     CounterBuffer.reserve(CountsSize);
411     for (uint64_t J = 0; J < CountsSize; ++J)
412       CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
413
414     DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
415
416     // Read value profiling data.
417     if (FormatVersion > 2 && !readValueProfilingData(D, End)) {
418       DataBuffer.clear();
419       return data_type();
420     }
421   }
422   return DataBuffer;
423 }
424
425 template <typename HashTableImpl>
426 std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
427     StringRef FuncName, ArrayRef<InstrProfRecord> &Data) {
428   auto Iter = HashTable->find(FuncName);
429   if (Iter == HashTable->end())
430     return instrprof_error::unknown_function;
431
432   Data = (*Iter);
433   if (Data.empty())
434     return instrprof_error::malformed;
435
436   return instrprof_error::success;
437 }
438
439 template <typename HashTableImpl>
440 std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
441     ArrayRef<InstrProfRecord> &Data) {
442   if (atEnd())
443     return instrprof_error::eof;
444
445   Data = *RecordIterator;
446
447   if (Data.empty())
448     return instrprof_error::malformed;
449
450   return instrprof_error::success;
451 }
452
453 template <typename HashTableImpl>
454 InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
455     const unsigned char *Buckets, const unsigned char *const Payload,
456     const unsigned char *const Base, IndexedInstrProf::HashT HashType,
457     uint64_t Version) {
458   FormatVersion = Version;
459   HashTable.reset(HashTableImpl::Create(
460       Buckets, Payload, Base,
461       typename HashTableImpl::InfoType(HashType, Version)));
462   // Form the map of hash values to const char* keys in profiling data.
463   std::vector<std::pair<uint64_t, const char *>> HashKeys;
464   for (auto Key : HashTable->keys()) {
465     const char *KeyTableRef = StringTable.insertString(Key);
466     HashKeys.push_back(std::make_pair(ComputeHash(HashType, Key), KeyTableRef));
467   }
468   std::sort(HashKeys.begin(), HashKeys.end(), less_first());
469   HashKeys.erase(std::unique(HashKeys.begin(), HashKeys.end()), HashKeys.end());
470   // Set the hash key map for the InstrLookupTrait
471   HashTable->getInfoObj().setHashKeys(std::move(HashKeys));
472   RecordIterator = HashTable->data_begin();
473 }
474
475 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
476   if (DataBuffer.getBufferSize() < 8)
477     return false;
478   using namespace support;
479   uint64_t Magic =
480       endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
481   // Verify that it's magical.
482   return Magic == IndexedInstrProf::Magic;
483 }
484
485 std::error_code IndexedInstrProfReader::readHeader() {
486   const unsigned char *Start =
487       (const unsigned char *)DataBuffer->getBufferStart();
488   const unsigned char *Cur = Start;
489   if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
490     return error(instrprof_error::truncated);
491
492   using namespace support;
493
494   auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
495   Cur += sizeof(IndexedInstrProf::Header);
496
497   // Check the magic number.
498   uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
499   if (Magic != IndexedInstrProf::Magic)
500     return error(instrprof_error::bad_magic);
501
502   // Read the version.
503   uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
504   if (FormatVersion > IndexedInstrProf::Version)
505     return error(instrprof_error::unsupported_version);
506
507   // Read the maximal function count.
508   MaxFunctionCount =
509       endian::byte_swap<uint64_t, little>(Header->MaxFunctionCount);
510
511   // Read the hash type and start offset.
512   IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
513       endian::byte_swap<uint64_t, little>(Header->HashType));
514   if (HashType > IndexedInstrProf::HashT::Last)
515     return error(instrprof_error::unsupported_hash_type);
516
517   uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
518
519   // The rest of the file is an on disk hash table.
520   InstrProfReaderIndexBase *IndexPtr = nullptr;
521   IndexPtr = new InstrProfReaderIndex<OnDiskHashTableImplV3>(
522       Start + HashOffset, Cur, Start, HashType, FormatVersion);
523   Index.reset(IndexPtr);
524   return success();
525 }
526
527 ErrorOr<InstrProfRecord>
528 IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
529                                            uint64_t FuncHash) {
530   ArrayRef<InstrProfRecord> Data;
531   std::error_code EC = Index->getRecords(FuncName, Data);
532   if (EC != instrprof_error::success)
533     return EC;
534   // Found it. Look for counters with the right hash.
535   for (unsigned I = 0, E = Data.size(); I < E; ++I) {
536     // Check for a match and fill the vector if there is one.
537     if (Data[I].Hash == FuncHash) {
538       return std::move(Data[I]);
539     }
540   }
541   return error(instrprof_error::hash_mismatch);
542 }
543
544 std::error_code
545 IndexedInstrProfReader::getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
546                                           std::vector<uint64_t> &Counts) {
547   ErrorOr<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
548   if (std::error_code EC = Record.getError())
549     return EC;
550
551   Counts = Record.get().Counts;
552   return success();
553 }
554
555 std::error_code IndexedInstrProfReader::readNextRecord(
556     InstrProfRecord &Record) {
557   static unsigned RecordIndex = 0;
558
559   ArrayRef<InstrProfRecord> Data;
560
561   std::error_code EC = Index->getRecords(Data);
562   if (EC != instrprof_error::success)
563     return error(EC);
564
565   Record = Data[RecordIndex++];
566   if (RecordIndex >= Data.size()) {
567     Index->advanceToNextKey();
568     RecordIndex = 0;
569   }
570   return success();
571 }