blob: 31ed1309b462fef349e864fd8dce4a170fb0f2c5 [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
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000067std::error_code IndexedInstrProfReader::create(
Justin Bognerb7aa2632014-04-18 21:48:40 +000068 std::string Path, std::unique_ptr<IndexedInstrProfReader> &Result) {
69 // 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 Bognerb7aa2632014-04-18 21:48:40 +000075 // Create the reader.
76 if (!IndexedInstrProfReader::hasFormat(*Buffer))
77 return instrprof_error::bad_magic;
78 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
79
80 // Initialize the reader and return the result.
81 return initializeReader(*Result);
Justin Bognerf8d79192014-03-21 17:24:48 +000082}
83
84void InstrProfIterator::Increment() {
85 if (Reader->readNextRecord(Record))
86 *this = InstrProfIterator();
87}
88
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000089std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
Justin Bognercf36a362014-07-29 22:29:23 +000090 // Skip empty lines and comments.
91 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
Justin Bognerf8d79192014-03-21 17:24:48 +000092 ++Line;
93 // If we hit EOF while looking for a name, we're done.
94 if (Line.is_at_end())
95 return error(instrprof_error::eof);
96
97 // Read the function name.
98 Record.Name = *Line++;
99
100 // Read the function hash.
101 if (Line.is_at_end())
102 return error(instrprof_error::truncated);
103 if ((Line++)->getAsInteger(10, Record.Hash))
104 return error(instrprof_error::malformed);
105
106 // Read the number of counters.
107 uint64_t NumCounters;
108 if (Line.is_at_end())
109 return error(instrprof_error::truncated);
110 if ((Line++)->getAsInteger(10, NumCounters))
111 return error(instrprof_error::malformed);
Justin Bognerb59d7c72014-04-25 02:45:33 +0000112 if (NumCounters == 0)
113 return error(instrprof_error::malformed);
Justin Bognerf8d79192014-03-21 17:24:48 +0000114
115 // Read each counter and fill our internal storage with the values.
116 Counts.clear();
117 Counts.reserve(NumCounters);
118 for (uint64_t I = 0; I < NumCounters; ++I) {
119 if (Line.is_at_end())
120 return error(instrprof_error::truncated);
121 uint64_t Count;
122 if ((Line++)->getAsInteger(10, Count))
123 return error(instrprof_error::malformed);
124 Counts.push_back(Count);
125 }
126 // Give the record a reference to our internal counter storage.
127 Record.Counts = Counts;
128
129 return success();
130}
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000131
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000132template <class IntPtrT>
133static uint64_t getRawMagic();
134
135template <>
136uint64_t getRawMagic<uint64_t>() {
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000137 return
Duncan P. N. Exon Smith745a2bf2014-03-21 20:42:37 +0000138 uint64_t(255) << 56 |
139 uint64_t('l') << 48 |
140 uint64_t('p') << 40 |
141 uint64_t('r') << 32 |
142 uint64_t('o') << 24 |
143 uint64_t('f') << 16 |
144 uint64_t('r') << 8 |
145 uint64_t(129);
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000146}
147
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000148template <>
149uint64_t getRawMagic<uint32_t>() {
150 return
151 uint64_t(255) << 56 |
152 uint64_t('l') << 48 |
153 uint64_t('p') << 40 |
154 uint64_t('r') << 32 |
155 uint64_t('o') << 24 |
156 uint64_t('f') << 16 |
157 uint64_t('R') << 8 |
158 uint64_t(129);
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000159}
160
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000161template <class IntPtrT>
162bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000163 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000164 return false;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000165 uint64_t Magic =
166 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
167 return getRawMagic<IntPtrT>() == Magic ||
Artyom Skrobovef5e8672014-06-14 11:36:01 +0000168 sys::getSwappedBytes(getRawMagic<IntPtrT>()) == Magic;
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000169}
170
171template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000172std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000173 if (!hasFormat(*DataBuffer))
174 return error(instrprof_error::bad_magic);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000175 if (DataBuffer->getBufferSize() < sizeof(RawHeader))
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000176 return error(instrprof_error::bad_header);
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000177 auto *Header =
178 reinterpret_cast<const RawHeader *>(DataBuffer->getBufferStart());
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000179 ShouldSwapBytes = Header->Magic != getRawMagic<IntPtrT>();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000180 return readHeader(*Header);
181}
182
Justin Bognera119f322014-05-16 00:38:00 +0000183template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000184std::error_code
185RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
Justin Bognera119f322014-05-16 00:38:00 +0000186 const char *End = DataBuffer->getBufferEnd();
187 // Skip zero padding between profiles.
188 while (CurrentPos != End && *CurrentPos == 0)
189 ++CurrentPos;
190 // If there's nothing left, we're done.
191 if (CurrentPos == End)
192 return instrprof_error::eof;
193 // If there isn't enough space for another header, this is probably just
194 // garbage at the end of the file.
195 if (CurrentPos + sizeof(RawHeader) > End)
196 return instrprof_error::malformed;
Justin Bogner54b11282014-09-12 21:22:55 +0000197 // The writer ensures each profile is padded to start at an aligned address.
198 if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
199 return instrprof_error::malformed;
Justin Bognera119f322014-05-16 00:38:00 +0000200 // The magic should have the same byte order as in the previous header.
201 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
202 if (Magic != swap(getRawMagic<IntPtrT>()))
203 return instrprof_error::bad_magic;
204
205 // There's another profile to read, so we need to process the header.
206 auto *Header = reinterpret_cast<const RawHeader *>(CurrentPos);
207 return readHeader(*Header);
208}
209
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000210static uint64_t getRawVersion() {
211 return 1;
212}
213
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000214template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000215std::error_code
216RawInstrProfReader<IntPtrT>::readHeader(const RawHeader &Header) {
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000217 if (swap(Header.Version) != getRawVersion())
218 return error(instrprof_error::unsupported_version);
219
220 CountersDelta = swap(Header.CountersDelta);
221 NamesDelta = swap(Header.NamesDelta);
222 auto DataSize = swap(Header.DataSize);
223 auto CountersSize = swap(Header.CountersSize);
224 auto NamesSize = swap(Header.NamesSize);
225
226 ptrdiff_t DataOffset = sizeof(RawHeader);
227 ptrdiff_t CountersOffset = DataOffset + sizeof(ProfileData) * DataSize;
228 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
Justin Bognera119f322014-05-16 00:38:00 +0000229 size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000230
Justin Bognera119f322014-05-16 00:38:00 +0000231 auto *Start = reinterpret_cast<const char *>(&Header);
232 if (Start + ProfileSize > DataBuffer->getBufferEnd())
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000233 return error(instrprof_error::bad_header);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000234
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000235 Data = reinterpret_cast<const ProfileData *>(Start + DataOffset);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000236 DataEnd = Data + DataSize;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000237 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
238 NamesStart = Start + NamesOffset;
Justin Bognera119f322014-05-16 00:38:00 +0000239 ProfileEnd = Start + ProfileSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000240
241 return success();
242}
243
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000244template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000245std::error_code
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000246RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000247 if (Data == DataEnd)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000248 if (std::error_code EC = readNextHeader(ProfileEnd))
Justin Bognera119f322014-05-16 00:38:00 +0000249 return EC;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000250
251 // Get the raw data.
252 StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize));
Justin Bognerb59d7c72014-04-25 02:45:33 +0000253 uint32_t NumCounters = swap(Data->NumCounters);
254 if (NumCounters == 0)
255 return error(instrprof_error::malformed);
256 auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr), NumCounters);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000257
258 // Check bounds.
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000259 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000260 if (RawName.data() < NamesStart ||
261 RawName.data() + RawName.size() > DataBuffer->getBufferEnd() ||
262 RawCounts.data() < CountersStart ||
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000263 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000264 return error(instrprof_error::malformed);
265
266 // Store the data in Record, byte-swapping as necessary.
267 Record.Hash = swap(Data->FuncHash);
268 Record.Name = RawName;
269 if (ShouldSwapBytes) {
270 Counts.clear();
271 Counts.reserve(RawCounts.size());
272 for (uint64_t Count : RawCounts)
273 Counts.push_back(swap(Count));
274 Record.Counts = Counts;
275 } else
276 Record.Counts = RawCounts;
277
278 // Iterate.
279 ++Data;
280 return success();
281}
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000282
283namespace llvm {
284template class RawInstrProfReader<uint32_t>;
285template class RawInstrProfReader<uint64_t>;
286}
Justin Bognerb7aa2632014-04-18 21:48:40 +0000287
Justin Bognerb5d368e2014-04-18 22:00:22 +0000288InstrProfLookupTrait::hash_value_type
289InstrProfLookupTrait::ComputeHash(StringRef K) {
290 return IndexedInstrProf::ComputeHash(HashType, K);
291}
292
Justin Bognerb7aa2632014-04-18 21:48:40 +0000293bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
294 if (DataBuffer.getBufferSize() < 8)
295 return false;
296 using namespace support;
297 uint64_t Magic =
298 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
299 return Magic == IndexedInstrProf::Magic;
300}
301
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000302std::error_code IndexedInstrProfReader::readHeader() {
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000303 const unsigned char *Start =
304 (const unsigned char *)DataBuffer->getBufferStart();
Justin Bognerb7aa2632014-04-18 21:48:40 +0000305 const unsigned char *Cur = Start;
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000306 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000307 return error(instrprof_error::truncated);
308
309 using namespace support;
310
311 // Check the magic number.
312 uint64_t Magic = endian::readNext<uint64_t, little, unaligned>(Cur);
313 if (Magic != IndexedInstrProf::Magic)
314 return error(instrprof_error::bad_magic);
315
316 // Read the version.
Justin Bogner821d7472014-08-01 22:50:07 +0000317 FormatVersion = endian::readNext<uint64_t, little, unaligned>(Cur);
318 if (FormatVersion > IndexedInstrProf::Version)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000319 return error(instrprof_error::unsupported_version);
320
321 // Read the maximal function count.
322 MaxFunctionCount = endian::readNext<uint64_t, little, unaligned>(Cur);
323
324 // Read the hash type and start offset.
325 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
326 endian::readNext<uint64_t, little, unaligned>(Cur));
327 if (HashType > IndexedInstrProf::HashT::Last)
328 return error(instrprof_error::unsupported_hash_type);
329 uint64_t HashOffset = endian::readNext<uint64_t, little, unaligned>(Cur);
330
331 // The rest of the file is an on disk hash table.
332 Index.reset(InstrProfReaderIndex::Create(Start + HashOffset, Cur, Start,
333 InstrProfLookupTrait(HashType)));
334 // Set up our iterator for readNextRecord.
335 RecordIterator = Index->data_begin();
336
337 return success();
338}
339
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000340std::error_code IndexedInstrProfReader::getFunctionCounts(
Justin Bogner821d7472014-08-01 22:50:07 +0000341 StringRef FuncName, uint64_t FuncHash, std::vector<uint64_t> &Counts) {
342 auto Iter = Index->find(FuncName);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000343 if (Iter == Index->end())
344 return error(instrprof_error::unknown_function);
345
Justin Bogner821d7472014-08-01 22:50:07 +0000346 // Found it. Look for counters with the right hash.
347 ArrayRef<uint64_t> Data = (*Iter).Data;
348 uint64_t NumCounts;
349 for (uint64_t I = 0, E = Data.size(); I != E; I += NumCounts) {
350 // The function hash comes first.
351 uint64_t FoundHash = Data[I++];
352 // In v1, we have at least one count. Later, we have the number of counts.
353 if (I == E)
354 return error(instrprof_error::malformed);
355 NumCounts = FormatVersion == 1 ? E - I : Data[I++];
356 // If we have more counts than data, this is bogus.
357 if (I + NumCounts > E)
358 return error(instrprof_error::malformed);
359 // Check for a match and fill the vector if there is one.
360 if (FoundHash == FuncHash) {
361 Counts = Data.slice(I, NumCounts);
362 return success();
363 }
364 }
365 return error(instrprof_error::hash_mismatch);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000366}
367
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000368std::error_code
369IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) {
Justin Bognerb7aa2632014-04-18 21:48:40 +0000370 // Are we out of records?
371 if (RecordIterator == Index->data_end())
372 return error(instrprof_error::eof);
373
Justin Bogner821d7472014-08-01 22:50:07 +0000374 // Record the current function name.
375 Record.Name = (*RecordIterator).Name;
376
377 ArrayRef<uint64_t> Data = (*RecordIterator).Data;
378 // Valid data starts with a hash and either a count or the number of counts.
379 if (CurrentOffset + 1 > Data.size())
Justin Bognerb7aa2632014-04-18 21:48:40 +0000380 return error(instrprof_error::malformed);
Justin Bogner821d7472014-08-01 22:50:07 +0000381 // First we have a function hash.
382 Record.Hash = Data[CurrentOffset++];
383 // In version 1 we knew the number of counters implicitly, but in newer
384 // versions we store the number of counters next.
385 uint64_t NumCounts =
386 FormatVersion == 1 ? Data.size() - CurrentOffset : Data[CurrentOffset++];
387 if (CurrentOffset + NumCounts > Data.size())
388 return error(instrprof_error::malformed);
389 // And finally the counts themselves.
390 Record.Counts = Data.slice(CurrentOffset, NumCounts);
391
392 // If we've exhausted this function's data, increment the record.
393 CurrentOffset += NumCounts;
394 if (CurrentOffset == Data.size()) {
395 ++RecordIterator;
396 CurrentOffset = 0;
397 }
398
Justin Bognerb7aa2632014-04-18 21:48:40 +0000399 return success();
400}