394893d3701c2b9a1b7d8c4de51b5ac65d8a34d2
[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   ValueDataDelta = swap(Header.ValueDataDelta);
211   auto DataSize = swap(Header.DataSize);
212   auto CountersSize = swap(Header.CountersSize);
213   auto NamesSize = swap(Header.NamesSize);
214   auto ValueDataSize = swap(Header.ValueDataSize);
215   ValueKindLast = swap(Header.ValueKindLast);
216
217   auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
218   auto PaddingSize = getNumPaddingBytes(NamesSize);
219
220   ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
221   ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
222   ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
223   ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
224   size_t ProfileSize = ValueDataOffset + ValueDataSize;
225
226   auto *Start = reinterpret_cast<const char *>(&Header);
227   if (Start + ProfileSize > DataBuffer->getBufferEnd())
228     return error(instrprof_error::bad_header);
229
230   Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
231       Start + DataOffset);
232   DataEnd = Data + DataSize;
233   CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
234   NamesStart = Start + NamesOffset;
235   ValueDataStart = reinterpret_cast<const uint8_t*>(Start + ValueDataOffset);
236   ProfileEnd = Start + ProfileSize;
237
238   FunctionPtrToNameMap.clear();
239   for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
240     const IntPtrT FPtr = swap(I->FunctionPointer);
241     if (!FPtr)
242       continue;
243     StringRef FunctionName(getName(I->NamePtr), swap(I->NameSize));
244     const char* NameEntryPtr = StringTable.insertString(FunctionName);
245     FunctionPtrToNameMap.push_back(std::pair<const IntPtrT, const char*>
246                                    (FPtr, NameEntryPtr));
247   }
248   std::sort(FunctionPtrToNameMap.begin(), FunctionPtrToNameMap.end(), less_first());
249   FunctionPtrToNameMap.erase(std::unique(FunctionPtrToNameMap.begin(),
250                                          FunctionPtrToNameMap.end()),
251                                          FunctionPtrToNameMap.end());
252   return success();
253 }
254
255 template <class IntPtrT>
256 std::error_code RawInstrProfReader<IntPtrT>::readName(InstrProfRecord &Record) {
257   Record.Name = StringRef(getName(Data->NamePtr), swap(Data->NameSize));
258   if (Record.Name.data() < NamesStart ||
259       Record.Name.data() + Record.Name.size() >
260           reinterpret_cast<const char *>(ValueDataStart))
261     return error(instrprof_error::malformed);
262   return success();
263 }
264
265 template <class IntPtrT>
266 std::error_code RawInstrProfReader<IntPtrT>::readFuncHash(
267     InstrProfRecord &Record) {
268   Record.Hash = swap(Data->FuncHash);
269   return success();
270 }
271
272 template <class IntPtrT>
273 std::error_code RawInstrProfReader<IntPtrT>::readRawCounts(
274     InstrProfRecord &Record) {
275   uint32_t NumCounters = swap(Data->NumCounters);
276   IntPtrT CounterPtr = Data->CounterPtr;
277   if (NumCounters == 0)
278     return error(instrprof_error::malformed);
279
280   auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
281   auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
282
283   // Check bounds.
284   if (RawCounts.data() < CountersStart ||
285       RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
286     return error(instrprof_error::malformed);
287
288   if (ShouldSwapBytes) {
289     Record.Counts.clear();
290     Record.Counts.reserve(RawCounts.size());
291     for (uint64_t Count : RawCounts)
292       Record.Counts.push_back(swap(Count));
293   } else
294     Record.Counts = RawCounts;
295
296   return success();
297 }
298
299 template <class IntPtrT>
300 std::error_code
301 RawInstrProfReader<IntPtrT>::readValueProfilingData(InstrProfRecord &Record) {
302
303   Record.clearValueData();
304   if (!Data->Values || (ValueDataDelta == 0))
305     return success();
306
307   ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
308       ValueProfData::getValueProfData(getValueDataCounts(Data->Values),
309                                       (const unsigned char *)ProfileEnd,
310                                       getDataEndianness());
311
312   if (VDataPtrOrErr.getError())
313     return VDataPtrOrErr.getError();
314
315   VDataPtrOrErr.get()->deserializeTo(Record, &FunctionPtrToNameMap);
316   return success();
317 }
318
319 template <class IntPtrT>
320 std::error_code
321 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
322   if (atEnd())
323     if (std::error_code EC = readNextHeader(ProfileEnd))
324       return EC;
325
326   // Read name ad set it in Record.
327   if (std::error_code EC = readName(Record))
328     return EC;
329
330   // Read FuncHash and set it in Record.
331   if (std::error_code EC = readFuncHash(Record))
332     return EC;
333
334   // Read raw counts and set Record.
335   if (std::error_code EC = readRawCounts(Record))
336     return EC;
337
338   // Read value data and set Record.
339   if (std::error_code EC = readValueProfilingData(Record))
340     return EC;
341
342   // Iterate.
343   advanceData();
344   return success();
345 }
346
347 namespace llvm {
348 template class RawInstrProfReader<uint32_t>;
349 template class RawInstrProfReader<uint64_t>;
350 }
351
352 InstrProfLookupTrait::hash_value_type
353 InstrProfLookupTrait::ComputeHash(StringRef K) {
354   return IndexedInstrProf::ComputeHash(HashType, K);
355 }
356
357 typedef InstrProfLookupTrait::data_type data_type;
358 typedef InstrProfLookupTrait::offset_type offset_type;
359
360 bool InstrProfLookupTrait::readValueProfilingData(
361     const unsigned char *&D, const unsigned char *const End) {
362   ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
363       ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
364
365   if (VDataPtrOrErr.getError())
366     return false;
367
368   VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), &HashKeys);
369   D += VDataPtrOrErr.get()->TotalSize;
370
371   return true;
372 }
373
374 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
375                                          offset_type N) {
376   // Check if the data is corrupt. If so, don't try to read it.
377   if (N % sizeof(uint64_t))
378     return data_type();
379
380   DataBuffer.clear();
381   std::vector<uint64_t> CounterBuffer;
382
383   using namespace support;
384   const unsigned char *End = D + N;
385   while (D < End) {
386     // Read hash.
387     if (D + sizeof(uint64_t) >= End)
388       return data_type();
389     uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
390
391     // Initialize number of counters for FormatVersion == 1.
392     uint64_t CountsSize = N / sizeof(uint64_t) - 1;
393     // If format version is different then read the number of counters.
394     if (FormatVersion != 1) {
395       if (D + sizeof(uint64_t) > End)
396         return data_type();
397       CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
398     }
399     // Read counter values.
400     if (D + CountsSize * sizeof(uint64_t) > End)
401       return data_type();
402
403     CounterBuffer.clear();
404     CounterBuffer.reserve(CountsSize);
405     for (uint64_t J = 0; J < CountsSize; ++J)
406       CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
407
408     DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
409
410     // Read value profiling data.
411     if (FormatVersion > 2 && !readValueProfilingData(D, End)) {
412       DataBuffer.clear();
413       return data_type();
414     }
415   }
416   return DataBuffer;
417 }
418
419 template <typename HashTableImpl>
420 std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
421     StringRef FuncName, ArrayRef<InstrProfRecord> &Data) {
422   auto Iter = HashTable->find(FuncName);
423   if (Iter == HashTable->end())
424     return instrprof_error::unknown_function;
425
426   Data = (*Iter);
427   if (Data.empty())
428     return instrprof_error::malformed;
429
430   return instrprof_error::success;
431 }
432
433 template <typename HashTableImpl>
434 std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
435     ArrayRef<InstrProfRecord> &Data) {
436   if (atEnd())
437     return instrprof_error::eof;
438
439   Data = *RecordIterator;
440
441   if (Data.empty())
442     return instrprof_error::malformed;
443
444   return instrprof_error::success;
445 }
446
447 template <typename HashTableImpl>
448 InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
449     const unsigned char *Buckets, const unsigned char *const Payload,
450     const unsigned char *const Base, IndexedInstrProf::HashT HashType,
451     uint64_t Version) {
452   FormatVersion = Version;
453   HashTable.reset(HashTableImpl::Create(
454       Buckets, Payload, Base,
455       typename HashTableImpl::InfoType(HashType, Version)));
456   // Form the map of hash values to const char* keys in profiling data.
457   std::vector<std::pair<uint64_t, const char *>> HashKeys;
458   for (auto Key : HashTable->keys()) {
459     const char *KeyTableRef = StringTable.insertString(Key);
460     HashKeys.push_back(std::make_pair(ComputeHash(HashType, Key), KeyTableRef));
461   }
462   std::sort(HashKeys.begin(), HashKeys.end(), less_first());
463   HashKeys.erase(std::unique(HashKeys.begin(), HashKeys.end()), HashKeys.end());
464   // Set the hash key map for the InstrLookupTrait
465   HashTable->getInfoObj().setHashKeys(std::move(HashKeys));
466   RecordIterator = HashTable->data_begin();
467 }
468
469 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
470   if (DataBuffer.getBufferSize() < 8)
471     return false;
472   using namespace support;
473   uint64_t Magic =
474       endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
475   // Verify that it's magical.
476   return Magic == IndexedInstrProf::Magic;
477 }
478
479 std::error_code IndexedInstrProfReader::readHeader() {
480   const unsigned char *Start =
481       (const unsigned char *)DataBuffer->getBufferStart();
482   const unsigned char *Cur = Start;
483   if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
484     return error(instrprof_error::truncated);
485
486   using namespace support;
487
488   auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
489   Cur += sizeof(IndexedInstrProf::Header);
490
491   // Check the magic number.
492   uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
493   if (Magic != IndexedInstrProf::Magic)
494     return error(instrprof_error::bad_magic);
495
496   // Read the version.
497   uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
498   if (FormatVersion > IndexedInstrProf::Version)
499     return error(instrprof_error::unsupported_version);
500
501   // Read the maximal function count.
502   MaxFunctionCount =
503       endian::byte_swap<uint64_t, little>(Header->MaxFunctionCount);
504
505   // Read the hash type and start offset.
506   IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
507       endian::byte_swap<uint64_t, little>(Header->HashType));
508   if (HashType > IndexedInstrProf::HashT::Last)
509     return error(instrprof_error::unsupported_hash_type);
510
511   uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
512
513   // The rest of the file is an on disk hash table.
514   InstrProfReaderIndexBase *IndexPtr = nullptr;
515   IndexPtr = new InstrProfReaderIndex<OnDiskHashTableImplV3>(
516       Start + HashOffset, Cur, Start, HashType, FormatVersion);
517   Index.reset(IndexPtr);
518   return success();
519 }
520
521 ErrorOr<InstrProfRecord>
522 IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
523                                            uint64_t FuncHash) {
524   ArrayRef<InstrProfRecord> Data;
525   std::error_code EC = Index->getRecords(FuncName, Data);
526   if (EC != instrprof_error::success)
527     return EC;
528   // Found it. Look for counters with the right hash.
529   for (unsigned I = 0, E = Data.size(); I < E; ++I) {
530     // Check for a match and fill the vector if there is one.
531     if (Data[I].Hash == FuncHash) {
532       return std::move(Data[I]);
533     }
534   }
535   return error(instrprof_error::hash_mismatch);
536 }
537
538 std::error_code
539 IndexedInstrProfReader::getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
540                                           std::vector<uint64_t> &Counts) {
541   ErrorOr<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
542   if (std::error_code EC = Record.getError())
543     return EC;
544
545   Counts = Record.get().Counts;
546   return success();
547 }
548
549 std::error_code IndexedInstrProfReader::readNextRecord(
550     InstrProfRecord &Record) {
551   static unsigned RecordIndex = 0;
552
553   ArrayRef<InstrProfRecord> Data;
554
555   std::error_code EC = Index->getRecords(Data);
556   if (EC != instrprof_error::success)
557     return error(EC);
558
559   Record = Data[RecordIndex++];
560   if (RecordIndex >= Data.size()) {
561     Index->advanceToNextKey();
562     RecordIndex = 0;
563   }
564   return success();
565 }