blob: d13f27c3113e1951082f8a2b21b2308c8f9d70a9 [file] [log] [blame]
Justin Bognerf8d79192014-03-21 17:24:48 +00001//=-- 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"
Justin Bognerb7aa2632014-04-18 21:48:40 +000016#include "InstrProfIndexed.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000017#include "llvm/ProfileData/InstrProf.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000018#include <cassert>
19
20using namespace llvm;
21
Diego Novillofcd55602014-11-03 00:51:45 +000022static ErrorOr<std::unique_ptr<MemoryBuffer>>
23setupMemoryBuffer(std::string Path) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +000024 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
25 MemoryBuffer::getFileOrSTDIN(Path);
26 if (std::error_code EC = BufferOrErr.getError())
Justin Bognerf8d79192014-03-21 17:24:48 +000027 return EC;
Diego Novillofcd55602014-11-03 00:51:45 +000028 auto Buffer = std::move(BufferOrErr.get());
Justin Bognerf8d79192014-03-21 17:24:48 +000029
30 // Sanity check the file.
31 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
32 return instrprof_error::too_large;
Diego Novillofcd55602014-11-03 00:51:45 +000033 return std::move(Buffer);
Justin Bognerb7aa2632014-04-18 21:48:40 +000034}
35
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000036static std::error_code initializeReader(InstrProfReader &Reader) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000037 return Reader.readHeader();
38}
39
Diego Novillofcd55602014-11-03 00:51:45 +000040ErrorOr<std::unique_ptr<InstrProfReader>>
41InstrProfReader::create(std::string Path) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000042 // Set up the buffer to read.
Diego Novillofcd55602014-11-03 00:51:45 +000043 auto BufferOrError = setupMemoryBuffer(Path);
44 if (std::error_code EC = BufferOrError.getError())
Justin Bognerb7aa2632014-04-18 21:48:40 +000045 return EC;
Justin Bognerf8d79192014-03-21 17:24:48 +000046
Diego Novillofcd55602014-11-03 00:51:45 +000047 auto Buffer = std::move(BufferOrError.get());
48 std::unique_ptr<InstrProfReader> Result;
49
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +000050 // Create the reader.
Justin Bognerb7aa2632014-04-18 21:48:40 +000051 if (IndexedInstrProfReader::hasFormat(*Buffer))
52 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
53 else if (RawInstrProfReader64::hasFormat(*Buffer))
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +000054 Result.reset(new RawInstrProfReader64(std::move(Buffer)));
55 else if (RawInstrProfReader32::hasFormat(*Buffer))
56 Result.reset(new RawInstrProfReader32(std::move(Buffer)));
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +000057 else
Duncan P. N. Exon Smith4c5b7cb2014-03-21 20:42:34 +000058 Result.reset(new TextInstrProfReader(std::move(Buffer)));
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +000059
Justin Bognerb7aa2632014-04-18 21:48:40 +000060 // Initialize the reader and return the result.
Diego Novillofcd55602014-11-03 00:51:45 +000061 if (std::error_code EC = initializeReader(*Result))
62 return EC;
63
64 return std::move(Result);
Justin Bognerb7aa2632014-04-18 21:48:40 +000065}
66
Justin Bognerab89ed72015-02-16 21:28:58 +000067ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
68IndexedInstrProfReader::create(std::string Path) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000069 // Set up the buffer to read.
Diego Novillofcd55602014-11-03 00:51:45 +000070 auto BufferOrError = setupMemoryBuffer(Path);
71 if (std::error_code EC = BufferOrError.getError())
Justin Bognerb7aa2632014-04-18 21:48:40 +000072 return EC;
73
Diego Novillofcd55602014-11-03 00:51:45 +000074 auto Buffer = std::move(BufferOrError.get());
Justin Bognerab89ed72015-02-16 21:28:58 +000075 std::unique_ptr<IndexedInstrProfReader> Result;
76
Justin Bognerb7aa2632014-04-18 21:48:40 +000077 // Create the reader.
78 if (!IndexedInstrProfReader::hasFormat(*Buffer))
79 return instrprof_error::bad_magic;
80 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
81
82 // Initialize the reader and return the result.
Justin Bognerab89ed72015-02-16 21:28:58 +000083 if (std::error_code EC = initializeReader(*Result))
84 return EC;
85
86 return std::move(Result);
Justin Bognerf8d79192014-03-21 17:24:48 +000087}
88
89void InstrProfIterator::Increment() {
90 if (Reader->readNextRecord(Record))
91 *this = InstrProfIterator();
92}
93
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000094std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
Justin Bognercf36a362014-07-29 22:29:23 +000095 // Skip empty lines and comments.
96 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
Justin Bognerf8d79192014-03-21 17:24:48 +000097 ++Line;
98 // If we hit EOF while looking for a name, we're done.
99 if (Line.is_at_end())
100 return error(instrprof_error::eof);
101
102 // Read the function name.
103 Record.Name = *Line++;
104
105 // Read the function hash.
106 if (Line.is_at_end())
107 return error(instrprof_error::truncated);
108 if ((Line++)->getAsInteger(10, Record.Hash))
109 return error(instrprof_error::malformed);
110
111 // Read the number of counters.
112 uint64_t NumCounters;
113 if (Line.is_at_end())
114 return error(instrprof_error::truncated);
115 if ((Line++)->getAsInteger(10, NumCounters))
116 return error(instrprof_error::malformed);
Justin Bognerb59d7c72014-04-25 02:45:33 +0000117 if (NumCounters == 0)
118 return error(instrprof_error::malformed);
Justin Bognerf8d79192014-03-21 17:24:48 +0000119
120 // Read each counter and fill our internal storage with the values.
121 Counts.clear();
122 Counts.reserve(NumCounters);
123 for (uint64_t I = 0; I < NumCounters; ++I) {
124 if (Line.is_at_end())
125 return error(instrprof_error::truncated);
126 uint64_t Count;
127 if ((Line++)->getAsInteger(10, Count))
128 return error(instrprof_error::malformed);
129 Counts.push_back(Count);
130 }
131 // Give the record a reference to our internal counter storage.
132 Record.Counts = Counts;
133
134 return success();
135}
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000136
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000137template <class IntPtrT>
138static uint64_t getRawMagic();
139
140template <>
141uint64_t getRawMagic<uint64_t>() {
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000142 return
Duncan P. N. Exon Smith745a2bf2014-03-21 20:42:37 +0000143 uint64_t(255) << 56 |
144 uint64_t('l') << 48 |
145 uint64_t('p') << 40 |
146 uint64_t('r') << 32 |
147 uint64_t('o') << 24 |
148 uint64_t('f') << 16 |
149 uint64_t('r') << 8 |
150 uint64_t(129);
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000151}
152
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000153template <>
154uint64_t getRawMagic<uint32_t>() {
155 return
156 uint64_t(255) << 56 |
157 uint64_t('l') << 48 |
158 uint64_t('p') << 40 |
159 uint64_t('r') << 32 |
160 uint64_t('o') << 24 |
161 uint64_t('f') << 16 |
162 uint64_t('R') << 8 |
163 uint64_t(129);
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000164}
165
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000166template <class IntPtrT>
167bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000168 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000169 return false;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000170 uint64_t Magic =
171 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
172 return getRawMagic<IntPtrT>() == Magic ||
Artyom Skrobovef5e8672014-06-14 11:36:01 +0000173 sys::getSwappedBytes(getRawMagic<IntPtrT>()) == Magic;
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000174}
175
176template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000177std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000178 if (!hasFormat(*DataBuffer))
179 return error(instrprof_error::bad_magic);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000180 if (DataBuffer->getBufferSize() < sizeof(RawHeader))
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000181 return error(instrprof_error::bad_header);
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000182 auto *Header =
183 reinterpret_cast<const RawHeader *>(DataBuffer->getBufferStart());
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000184 ShouldSwapBytes = Header->Magic != getRawMagic<IntPtrT>();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000185 return readHeader(*Header);
186}
187
Justin Bognera119f322014-05-16 00:38:00 +0000188template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000189std::error_code
190RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
Justin Bognera119f322014-05-16 00:38:00 +0000191 const char *End = DataBuffer->getBufferEnd();
192 // Skip zero padding between profiles.
193 while (CurrentPos != End && *CurrentPos == 0)
194 ++CurrentPos;
195 // If there's nothing left, we're done.
196 if (CurrentPos == End)
197 return instrprof_error::eof;
198 // If there isn't enough space for another header, this is probably just
199 // garbage at the end of the file.
200 if (CurrentPos + sizeof(RawHeader) > End)
201 return instrprof_error::malformed;
Justin Bogner54b11282014-09-12 21:22:55 +0000202 // The writer ensures each profile is padded to start at an aligned address.
203 if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
204 return instrprof_error::malformed;
Justin Bognera119f322014-05-16 00:38:00 +0000205 // The magic should have the same byte order as in the previous header.
206 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
207 if (Magic != swap(getRawMagic<IntPtrT>()))
208 return instrprof_error::bad_magic;
209
210 // There's another profile to read, so we need to process the header.
211 auto *Header = reinterpret_cast<const RawHeader *>(CurrentPos);
212 return readHeader(*Header);
213}
214
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000215static uint64_t getRawVersion() {
216 return 1;
217}
218
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000219template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000220std::error_code
221RawInstrProfReader<IntPtrT>::readHeader(const RawHeader &Header) {
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000222 if (swap(Header.Version) != getRawVersion())
223 return error(instrprof_error::unsupported_version);
224
225 CountersDelta = swap(Header.CountersDelta);
226 NamesDelta = swap(Header.NamesDelta);
227 auto DataSize = swap(Header.DataSize);
228 auto CountersSize = swap(Header.CountersSize);
229 auto NamesSize = swap(Header.NamesSize);
230
231 ptrdiff_t DataOffset = sizeof(RawHeader);
232 ptrdiff_t CountersOffset = DataOffset + sizeof(ProfileData) * DataSize;
233 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
Justin Bognera119f322014-05-16 00:38:00 +0000234 size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000235
Justin Bognera119f322014-05-16 00:38:00 +0000236 auto *Start = reinterpret_cast<const char *>(&Header);
237 if (Start + ProfileSize > DataBuffer->getBufferEnd())
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000238 return error(instrprof_error::bad_header);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000239
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000240 Data = reinterpret_cast<const ProfileData *>(Start + DataOffset);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000241 DataEnd = Data + DataSize;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000242 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
243 NamesStart = Start + NamesOffset;
Justin Bognera119f322014-05-16 00:38:00 +0000244 ProfileEnd = Start + ProfileSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000245
246 return success();
247}
248
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000249template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000250std::error_code
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000251RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000252 if (Data == DataEnd)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000253 if (std::error_code EC = readNextHeader(ProfileEnd))
Justin Bognera119f322014-05-16 00:38:00 +0000254 return EC;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000255
256 // Get the raw data.
257 StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize));
Justin Bognerb59d7c72014-04-25 02:45:33 +0000258 uint32_t NumCounters = swap(Data->NumCounters);
259 if (NumCounters == 0)
260 return error(instrprof_error::malformed);
261 auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr), NumCounters);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000262
263 // Check bounds.
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000264 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000265 if (RawName.data() < NamesStart ||
266 RawName.data() + RawName.size() > DataBuffer->getBufferEnd() ||
267 RawCounts.data() < CountersStart ||
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000268 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000269 return error(instrprof_error::malformed);
270
271 // Store the data in Record, byte-swapping as necessary.
272 Record.Hash = swap(Data->FuncHash);
273 Record.Name = RawName;
274 if (ShouldSwapBytes) {
275 Counts.clear();
276 Counts.reserve(RawCounts.size());
277 for (uint64_t Count : RawCounts)
278 Counts.push_back(swap(Count));
279 Record.Counts = Counts;
280 } else
281 Record.Counts = RawCounts;
282
283 // Iterate.
284 ++Data;
285 return success();
286}
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000287
288namespace llvm {
289template class RawInstrProfReader<uint32_t>;
290template class RawInstrProfReader<uint64_t>;
291}
Justin Bognerb7aa2632014-04-18 21:48:40 +0000292
Justin Bognerb5d368e2014-04-18 22:00:22 +0000293InstrProfLookupTrait::hash_value_type
294InstrProfLookupTrait::ComputeHash(StringRef K) {
295 return IndexedInstrProf::ComputeHash(HashType, K);
296}
297
Justin Bognerb7aa2632014-04-18 21:48:40 +0000298bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
299 if (DataBuffer.getBufferSize() < 8)
300 return false;
301 using namespace support;
302 uint64_t Magic =
303 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
304 return Magic == IndexedInstrProf::Magic;
305}
306
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000307std::error_code IndexedInstrProfReader::readHeader() {
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000308 const unsigned char *Start =
309 (const unsigned char *)DataBuffer->getBufferStart();
Justin Bognerb7aa2632014-04-18 21:48:40 +0000310 const unsigned char *Cur = Start;
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000311 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000312 return error(instrprof_error::truncated);
313
314 using namespace support;
315
316 // Check the magic number.
317 uint64_t Magic = endian::readNext<uint64_t, little, unaligned>(Cur);
318 if (Magic != IndexedInstrProf::Magic)
319 return error(instrprof_error::bad_magic);
320
321 // Read the version.
Justin Bogner821d7472014-08-01 22:50:07 +0000322 FormatVersion = endian::readNext<uint64_t, little, unaligned>(Cur);
323 if (FormatVersion > IndexedInstrProf::Version)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000324 return error(instrprof_error::unsupported_version);
325
326 // Read the maximal function count.
327 MaxFunctionCount = endian::readNext<uint64_t, little, unaligned>(Cur);
328
329 // Read the hash type and start offset.
330 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
331 endian::readNext<uint64_t, little, unaligned>(Cur));
332 if (HashType > IndexedInstrProf::HashT::Last)
333 return error(instrprof_error::unsupported_hash_type);
334 uint64_t HashOffset = endian::readNext<uint64_t, little, unaligned>(Cur);
335
336 // The rest of the file is an on disk hash table.
337 Index.reset(InstrProfReaderIndex::Create(Start + HashOffset, Cur, Start,
338 InstrProfLookupTrait(HashType)));
339 // Set up our iterator for readNextRecord.
340 RecordIterator = Index->data_begin();
341
342 return success();
343}
344
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000345std::error_code IndexedInstrProfReader::getFunctionCounts(
Justin Bogner821d7472014-08-01 22:50:07 +0000346 StringRef FuncName, uint64_t FuncHash, std::vector<uint64_t> &Counts) {
347 auto Iter = Index->find(FuncName);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000348 if (Iter == Index->end())
349 return error(instrprof_error::unknown_function);
350
Justin Bogner821d7472014-08-01 22:50:07 +0000351 // Found it. Look for counters with the right hash.
352 ArrayRef<uint64_t> Data = (*Iter).Data;
353 uint64_t NumCounts;
354 for (uint64_t I = 0, E = Data.size(); I != E; I += NumCounts) {
355 // The function hash comes first.
356 uint64_t FoundHash = Data[I++];
357 // In v1, we have at least one count. Later, we have the number of counts.
358 if (I == E)
359 return error(instrprof_error::malformed);
360 NumCounts = FormatVersion == 1 ? E - I : Data[I++];
361 // If we have more counts than data, this is bogus.
362 if (I + NumCounts > E)
363 return error(instrprof_error::malformed);
364 // Check for a match and fill the vector if there is one.
365 if (FoundHash == FuncHash) {
366 Counts = Data.slice(I, NumCounts);
367 return success();
368 }
369 }
370 return error(instrprof_error::hash_mismatch);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000371}
372
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000373std::error_code
374IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) {
Justin Bognerb7aa2632014-04-18 21:48:40 +0000375 // Are we out of records?
376 if (RecordIterator == Index->data_end())
377 return error(instrprof_error::eof);
378
Justin Bogner821d7472014-08-01 22:50:07 +0000379 // Record the current function name.
380 Record.Name = (*RecordIterator).Name;
381
382 ArrayRef<uint64_t> Data = (*RecordIterator).Data;
383 // Valid data starts with a hash and either a count or the number of counts.
384 if (CurrentOffset + 1 > Data.size())
Justin Bognerb7aa2632014-04-18 21:48:40 +0000385 return error(instrprof_error::malformed);
Justin Bogner821d7472014-08-01 22:50:07 +0000386 // First we have a function hash.
387 Record.Hash = Data[CurrentOffset++];
388 // In version 1 we knew the number of counters implicitly, but in newer
389 // versions we store the number of counters next.
390 uint64_t NumCounts =
391 FormatVersion == 1 ? Data.size() - CurrentOffset : Data[CurrentOffset++];
392 if (CurrentOffset + NumCounts > Data.size())
393 return error(instrprof_error::malformed);
394 // And finally the counts themselves.
395 Record.Counts = Data.slice(CurrentOffset, NumCounts);
396
397 // If we've exhausted this function's data, increment the record.
398 CurrentOffset += NumCounts;
399 if (CurrentOffset == Data.size()) {
400 ++RecordIterator;
401 CurrentOffset = 0;
402 }
403
Justin Bognerb7aa2632014-04-18 21:48:40 +0000404 return success();
405}