blob: e333473f6f8d228b9face989d6f0888949852b9d [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"
16#include "llvm/ProfileData/InstrProf.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000017
Justin Bognerb7aa2632014-04-18 21:48:40 +000018#include "InstrProfIndexed.h"
19
Justin Bognerf8d79192014-03-21 17:24:48 +000020#include <cassert>
21
22using namespace llvm;
23
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000024static std::error_code
25setupMemoryBuffer(std::string Path, std::unique_ptr<MemoryBuffer> &Buffer) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +000026 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
27 MemoryBuffer::getFileOrSTDIN(Path);
28 if (std::error_code EC = BufferOrErr.getError())
Justin Bognerf8d79192014-03-21 17:24:48 +000029 return EC;
Rafael Espindolaadf21f22014-07-06 17:43:13 +000030 Buffer = std::move(BufferOrErr.get());
Justin Bognerf8d79192014-03-21 17:24:48 +000031
32 // Sanity check the file.
33 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
34 return instrprof_error::too_large;
Justin Bognerb7aa2632014-04-18 21:48:40 +000035 return instrprof_error::success;
36}
37
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000038static std::error_code initializeReader(InstrProfReader &Reader) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000039 return Reader.readHeader();
40}
41
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000042std::error_code
43InstrProfReader::create(std::string Path,
44 std::unique_ptr<InstrProfReader> &Result) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000045 // Set up the buffer to read.
46 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000047 if (std::error_code EC = setupMemoryBuffer(Path, Buffer))
Justin Bognerb7aa2632014-04-18 21:48:40 +000048 return EC;
Justin Bognerf8d79192014-03-21 17:24:48 +000049
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.
61 return initializeReader(*Result);
62}
63
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000064std::error_code IndexedInstrProfReader::create(
Justin Bognerb7aa2632014-04-18 21:48:40 +000065 std::string Path, std::unique_ptr<IndexedInstrProfReader> &Result) {
66 // Set up the buffer to read.
67 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000068 if (std::error_code EC = setupMemoryBuffer(Path, Buffer))
Justin Bognerb7aa2632014-04-18 21:48:40 +000069 return EC;
70
71 // Create the reader.
72 if (!IndexedInstrProfReader::hasFormat(*Buffer))
73 return instrprof_error::bad_magic;
74 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
75
76 // Initialize the reader and return the result.
77 return initializeReader(*Result);
Justin Bognerf8d79192014-03-21 17:24:48 +000078}
79
80void InstrProfIterator::Increment() {
81 if (Reader->readNextRecord(Record))
82 *this = InstrProfIterator();
83}
84
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000085std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
Justin Bognercf36a362014-07-29 22:29:23 +000086 // Skip empty lines and comments.
87 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
Justin Bognerf8d79192014-03-21 17:24:48 +000088 ++Line;
89 // If we hit EOF while looking for a name, we're done.
90 if (Line.is_at_end())
91 return error(instrprof_error::eof);
92
93 // Read the function name.
94 Record.Name = *Line++;
95
96 // Read the function hash.
97 if (Line.is_at_end())
98 return error(instrprof_error::truncated);
99 if ((Line++)->getAsInteger(10, Record.Hash))
100 return error(instrprof_error::malformed);
101
102 // Read the number of counters.
103 uint64_t NumCounters;
104 if (Line.is_at_end())
105 return error(instrprof_error::truncated);
106 if ((Line++)->getAsInteger(10, NumCounters))
107 return error(instrprof_error::malformed);
Justin Bognerb59d7c72014-04-25 02:45:33 +0000108 if (NumCounters == 0)
109 return error(instrprof_error::malformed);
Justin Bognerf8d79192014-03-21 17:24:48 +0000110
111 // Read each counter and fill our internal storage with the values.
112 Counts.clear();
113 Counts.reserve(NumCounters);
114 for (uint64_t I = 0; I < NumCounters; ++I) {
115 if (Line.is_at_end())
116 return error(instrprof_error::truncated);
117 uint64_t Count;
118 if ((Line++)->getAsInteger(10, Count))
119 return error(instrprof_error::malformed);
120 Counts.push_back(Count);
121 }
122 // Give the record a reference to our internal counter storage.
123 Record.Counts = Counts;
124
125 return success();
126}
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000127
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000128template <class IntPtrT>
129static uint64_t getRawMagic();
130
131template <>
132uint64_t getRawMagic<uint64_t>() {
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000133 return
Duncan P. N. Exon Smith745a2bf2014-03-21 20:42:37 +0000134 uint64_t(255) << 56 |
135 uint64_t('l') << 48 |
136 uint64_t('p') << 40 |
137 uint64_t('r') << 32 |
138 uint64_t('o') << 24 |
139 uint64_t('f') << 16 |
140 uint64_t('r') << 8 |
141 uint64_t(129);
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000142}
143
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000144template <>
145uint64_t getRawMagic<uint32_t>() {
146 return
147 uint64_t(255) << 56 |
148 uint64_t('l') << 48 |
149 uint64_t('p') << 40 |
150 uint64_t('r') << 32 |
151 uint64_t('o') << 24 |
152 uint64_t('f') << 16 |
153 uint64_t('R') << 8 |
154 uint64_t(129);
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000155}
156
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000157template <class IntPtrT>
158bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000159 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000160 return false;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000161 uint64_t Magic =
162 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
163 return getRawMagic<IntPtrT>() == Magic ||
Artyom Skrobovef5e8672014-06-14 11:36:01 +0000164 sys::getSwappedBytes(getRawMagic<IntPtrT>()) == Magic;
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000165}
166
167template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000168std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000169 if (!hasFormat(*DataBuffer))
170 return error(instrprof_error::bad_magic);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000171 if (DataBuffer->getBufferSize() < sizeof(RawHeader))
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000172 return error(instrprof_error::bad_header);
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000173 auto *Header =
174 reinterpret_cast<const RawHeader *>(DataBuffer->getBufferStart());
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000175 ShouldSwapBytes = Header->Magic != getRawMagic<IntPtrT>();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000176 return readHeader(*Header);
177}
178
Justin Bognera119f322014-05-16 00:38:00 +0000179template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000180std::error_code
181RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
Justin Bognera119f322014-05-16 00:38:00 +0000182 const char *End = DataBuffer->getBufferEnd();
183 // Skip zero padding between profiles.
184 while (CurrentPos != End && *CurrentPos == 0)
185 ++CurrentPos;
186 // If there's nothing left, we're done.
187 if (CurrentPos == End)
188 return instrprof_error::eof;
189 // If there isn't enough space for another header, this is probably just
190 // garbage at the end of the file.
191 if (CurrentPos + sizeof(RawHeader) > End)
192 return instrprof_error::malformed;
Justin Bogner54b11282014-09-12 21:22:55 +0000193 // The writer ensures each profile is padded to start at an aligned address.
194 if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
195 return instrprof_error::malformed;
Justin Bognera119f322014-05-16 00:38:00 +0000196 // The magic should have the same byte order as in the previous header.
197 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
198 if (Magic != swap(getRawMagic<IntPtrT>()))
199 return instrprof_error::bad_magic;
200
201 // There's another profile to read, so we need to process the header.
202 auto *Header = reinterpret_cast<const RawHeader *>(CurrentPos);
203 return readHeader(*Header);
204}
205
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000206static uint64_t getRawVersion() {
207 return 1;
208}
209
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000210template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000211std::error_code
212RawInstrProfReader<IntPtrT>::readHeader(const RawHeader &Header) {
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000213 if (swap(Header.Version) != getRawVersion())
214 return error(instrprof_error::unsupported_version);
215
216 CountersDelta = swap(Header.CountersDelta);
217 NamesDelta = swap(Header.NamesDelta);
218 auto DataSize = swap(Header.DataSize);
219 auto CountersSize = swap(Header.CountersSize);
220 auto NamesSize = swap(Header.NamesSize);
221
222 ptrdiff_t DataOffset = sizeof(RawHeader);
223 ptrdiff_t CountersOffset = DataOffset + sizeof(ProfileData) * DataSize;
224 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
Justin Bognera119f322014-05-16 00:38:00 +0000225 size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000226
Justin Bognera119f322014-05-16 00:38:00 +0000227 auto *Start = reinterpret_cast<const char *>(&Header);
228 if (Start + ProfileSize > DataBuffer->getBufferEnd())
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000229 return error(instrprof_error::bad_header);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000230
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000231 Data = reinterpret_cast<const ProfileData *>(Start + DataOffset);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000232 DataEnd = Data + DataSize;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000233 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
234 NamesStart = Start + NamesOffset;
Justin Bognera119f322014-05-16 00:38:00 +0000235 ProfileEnd = Start + ProfileSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000236
237 return success();
238}
239
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000240template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000241std::error_code
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000242RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000243 if (Data == DataEnd)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000244 if (std::error_code EC = readNextHeader(ProfileEnd))
Justin Bognera119f322014-05-16 00:38:00 +0000245 return EC;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000246
247 // Get the raw data.
248 StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize));
Justin Bognerb59d7c72014-04-25 02:45:33 +0000249 uint32_t NumCounters = swap(Data->NumCounters);
250 if (NumCounters == 0)
251 return error(instrprof_error::malformed);
252 auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr), NumCounters);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000253
254 // Check bounds.
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000255 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000256 if (RawName.data() < NamesStart ||
257 RawName.data() + RawName.size() > DataBuffer->getBufferEnd() ||
258 RawCounts.data() < CountersStart ||
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000259 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000260 return error(instrprof_error::malformed);
261
262 // Store the data in Record, byte-swapping as necessary.
263 Record.Hash = swap(Data->FuncHash);
264 Record.Name = RawName;
265 if (ShouldSwapBytes) {
266 Counts.clear();
267 Counts.reserve(RawCounts.size());
268 for (uint64_t Count : RawCounts)
269 Counts.push_back(swap(Count));
270 Record.Counts = Counts;
271 } else
272 Record.Counts = RawCounts;
273
274 // Iterate.
275 ++Data;
276 return success();
277}
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000278
279namespace llvm {
280template class RawInstrProfReader<uint32_t>;
281template class RawInstrProfReader<uint64_t>;
282}
Justin Bognerb7aa2632014-04-18 21:48:40 +0000283
Justin Bognerb5d368e2014-04-18 22:00:22 +0000284InstrProfLookupTrait::hash_value_type
285InstrProfLookupTrait::ComputeHash(StringRef K) {
286 return IndexedInstrProf::ComputeHash(HashType, K);
287}
288
Justin Bognerb7aa2632014-04-18 21:48:40 +0000289bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
290 if (DataBuffer.getBufferSize() < 8)
291 return false;
292 using namespace support;
293 uint64_t Magic =
294 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
295 return Magic == IndexedInstrProf::Magic;
296}
297
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000298std::error_code IndexedInstrProfReader::readHeader() {
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000299 const unsigned char *Start =
300 (const unsigned char *)DataBuffer->getBufferStart();
Justin Bognerb7aa2632014-04-18 21:48:40 +0000301 const unsigned char *Cur = Start;
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000302 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000303 return error(instrprof_error::truncated);
304
305 using namespace support;
306
307 // Check the magic number.
308 uint64_t Magic = endian::readNext<uint64_t, little, unaligned>(Cur);
309 if (Magic != IndexedInstrProf::Magic)
310 return error(instrprof_error::bad_magic);
311
312 // Read the version.
Justin Bogner821d7472014-08-01 22:50:07 +0000313 FormatVersion = endian::readNext<uint64_t, little, unaligned>(Cur);
314 if (FormatVersion > IndexedInstrProf::Version)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000315 return error(instrprof_error::unsupported_version);
316
317 // Read the maximal function count.
318 MaxFunctionCount = endian::readNext<uint64_t, little, unaligned>(Cur);
319
320 // Read the hash type and start offset.
321 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
322 endian::readNext<uint64_t, little, unaligned>(Cur));
323 if (HashType > IndexedInstrProf::HashT::Last)
324 return error(instrprof_error::unsupported_hash_type);
325 uint64_t HashOffset = endian::readNext<uint64_t, little, unaligned>(Cur);
326
327 // The rest of the file is an on disk hash table.
328 Index.reset(InstrProfReaderIndex::Create(Start + HashOffset, Cur, Start,
329 InstrProfLookupTrait(HashType)));
330 // Set up our iterator for readNextRecord.
331 RecordIterator = Index->data_begin();
332
333 return success();
334}
335
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000336std::error_code IndexedInstrProfReader::getFunctionCounts(
Justin Bogner821d7472014-08-01 22:50:07 +0000337 StringRef FuncName, uint64_t FuncHash, std::vector<uint64_t> &Counts) {
338 auto Iter = Index->find(FuncName);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000339 if (Iter == Index->end())
340 return error(instrprof_error::unknown_function);
341
Justin Bogner821d7472014-08-01 22:50:07 +0000342 // Found it. Look for counters with the right hash.
343 ArrayRef<uint64_t> Data = (*Iter).Data;
344 uint64_t NumCounts;
345 for (uint64_t I = 0, E = Data.size(); I != E; I += NumCounts) {
346 // The function hash comes first.
347 uint64_t FoundHash = Data[I++];
348 // In v1, we have at least one count. Later, we have the number of counts.
349 if (I == E)
350 return error(instrprof_error::malformed);
351 NumCounts = FormatVersion == 1 ? E - I : Data[I++];
352 // If we have more counts than data, this is bogus.
353 if (I + NumCounts > E)
354 return error(instrprof_error::malformed);
355 // Check for a match and fill the vector if there is one.
356 if (FoundHash == FuncHash) {
357 Counts = Data.slice(I, NumCounts);
358 return success();
359 }
360 }
361 return error(instrprof_error::hash_mismatch);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000362}
363
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000364std::error_code
365IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) {
Justin Bognerb7aa2632014-04-18 21:48:40 +0000366 // Are we out of records?
367 if (RecordIterator == Index->data_end())
368 return error(instrprof_error::eof);
369
Justin Bogner821d7472014-08-01 22:50:07 +0000370 // Record the current function name.
371 Record.Name = (*RecordIterator).Name;
372
373 ArrayRef<uint64_t> Data = (*RecordIterator).Data;
374 // Valid data starts with a hash and either a count or the number of counts.
375 if (CurrentOffset + 1 > Data.size())
Justin Bognerb7aa2632014-04-18 21:48:40 +0000376 return error(instrprof_error::malformed);
Justin Bogner821d7472014-08-01 22:50:07 +0000377 // First we have a function hash.
378 Record.Hash = Data[CurrentOffset++];
379 // In version 1 we knew the number of counters implicitly, but in newer
380 // versions we store the number of counters next.
381 uint64_t NumCounts =
382 FormatVersion == 1 ? Data.size() - CurrentOffset : Data[CurrentOffset++];
383 if (CurrentOffset + NumCounts > Data.size())
384 return error(instrprof_error::malformed);
385 // And finally the counts themselves.
386 Record.Counts = Data.slice(CurrentOffset, NumCounts);
387
388 // If we've exhausted this function's data, increment the record.
389 CurrentOffset += NumCounts;
390 if (CurrentOffset == Data.size()) {
391 ++RecordIterator;
392 CurrentOffset = 0;
393 }
394
Justin Bognerb7aa2632014-04-18 21:48:40 +0000395 return success();
396}