blob: 8a0354dc98cf6fb2910dc44cb6f1892839745085 [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"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000016#include "llvm/ADT/STLExtras.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000017#include <cassert>
18
19using namespace llvm;
20
Diego Novillofcd55602014-11-03 00:51:45 +000021static ErrorOr<std::unique_ptr<MemoryBuffer>>
22setupMemoryBuffer(std::string Path) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +000023 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
24 MemoryBuffer::getFileOrSTDIN(Path);
25 if (std::error_code EC = BufferOrErr.getError())
Justin Bognerf8d79192014-03-21 17:24:48 +000026 return EC;
Justin Bogner2b6c5372015-02-18 01:58:17 +000027 return std::move(BufferOrErr.get());
Justin Bognerb7aa2632014-04-18 21:48:40 +000028}
29
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000030static std::error_code initializeReader(InstrProfReader &Reader) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000031 return Reader.readHeader();
32}
33
Diego Novillofcd55602014-11-03 00:51:45 +000034ErrorOr<std::unique_ptr<InstrProfReader>>
35InstrProfReader::create(std::string Path) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000036 // Set up the buffer to read.
Diego Novillofcd55602014-11-03 00:51:45 +000037 auto BufferOrError = setupMemoryBuffer(Path);
38 if (std::error_code EC = BufferOrError.getError())
Justin Bognerb7aa2632014-04-18 21:48:40 +000039 return EC;
Justin Bogner2b6c5372015-02-18 01:58:17 +000040 return InstrProfReader::create(std::move(BufferOrError.get()));
41}
Justin Bognerf8d79192014-03-21 17:24:48 +000042
Justin Bogner2b6c5372015-02-18 01:58:17 +000043ErrorOr<std::unique_ptr<InstrProfReader>>
44InstrProfReader::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
Diego Novillofcd55602014-11-03 00:51:45 +000049 std::unique_ptr<InstrProfReader> Result;
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)));
Nathan Slingerland4f823662015-11-13 03:47:58 +000057 else if (TextInstrProfReader::hasFormat(*Buffer))
Nathan Slingerland911ced62015-11-12 18:39:26 +000058 Result.reset(new TextInstrProfReader(std::move(Buffer)));
Nathan Slingerland4f823662015-11-13 03:47:58 +000059 else
60 return instrprof_error::unrecognized_format;
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +000061
Justin Bognerb7aa2632014-04-18 21:48:40 +000062 // Initialize the reader and return the result.
Diego Novillofcd55602014-11-03 00:51:45 +000063 if (std::error_code EC = initializeReader(*Result))
64 return EC;
65
66 return std::move(Result);
Justin Bognerb7aa2632014-04-18 21:48:40 +000067}
68
Justin Bognerab89ed72015-02-16 21:28:58 +000069ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
70IndexedInstrProfReader::create(std::string Path) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000071 // Set up the buffer to read.
Diego Novillofcd55602014-11-03 00:51:45 +000072 auto BufferOrError = setupMemoryBuffer(Path);
73 if (std::error_code EC = BufferOrError.getError())
Justin Bognerb7aa2632014-04-18 21:48:40 +000074 return EC;
Justin Bogner2b6c5372015-02-18 01:58:17 +000075 return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
76}
Justin Bognerb7aa2632014-04-18 21:48:40 +000077
Justin Bogner2b6c5372015-02-18 01:58:17 +000078
79ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
80IndexedInstrProfReader::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;
Justin Bognerab89ed72015-02-16 21:28:58 +000084
Justin Bognerb7aa2632014-04-18 21:48:40 +000085 // Create the reader.
86 if (!IndexedInstrProfReader::hasFormat(*Buffer))
87 return instrprof_error::bad_magic;
Justin Bogner2b6c5372015-02-18 01:58:17 +000088 auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
Justin Bognerb7aa2632014-04-18 21:48:40 +000089
90 // Initialize the reader and return the result.
Justin Bognerab89ed72015-02-16 21:28:58 +000091 if (std::error_code EC = initializeReader(*Result))
92 return EC;
93
94 return std::move(Result);
Justin Bognerf8d79192014-03-21 17:24:48 +000095}
96
97void InstrProfIterator::Increment() {
98 if (Reader->readNextRecord(Record))
99 *this = InstrProfIterator();
100}
101
Nathan Slingerland4f823662015-11-13 03:47:58 +0000102bool 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 || std::all_of(buffer.begin(), buffer.begin() + count,
108 [](char c) { return ::isprint(c) || ::isspace(c); });
109}
110
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000111std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
Justin Bognercf36a362014-07-29 22:29:23 +0000112 // Skip empty lines and comments.
113 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
Justin Bognerf8d79192014-03-21 17:24:48 +0000114 ++Line;
115 // If we hit EOF while looking for a name, we're done.
116 if (Line.is_at_end())
117 return error(instrprof_error::eof);
118
119 // Read the function name.
120 Record.Name = *Line++;
121
122 // Read the function hash.
123 if (Line.is_at_end())
124 return error(instrprof_error::truncated);
Justin Bognerf95ca072015-03-09 18:54:49 +0000125 if ((Line++)->getAsInteger(0, Record.Hash))
Justin Bognerf8d79192014-03-21 17:24:48 +0000126 return error(instrprof_error::malformed);
127
128 // Read the number of counters.
129 uint64_t NumCounters;
130 if (Line.is_at_end())
131 return error(instrprof_error::truncated);
132 if ((Line++)->getAsInteger(10, NumCounters))
133 return error(instrprof_error::malformed);
Justin Bognerb59d7c72014-04-25 02:45:33 +0000134 if (NumCounters == 0)
135 return error(instrprof_error::malformed);
Justin Bognerf8d79192014-03-21 17:24:48 +0000136
137 // Read each counter and fill our internal storage with the values.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000138 Record.Counts.clear();
139 Record.Counts.reserve(NumCounters);
Justin Bognerf8d79192014-03-21 17:24:48 +0000140 for (uint64_t I = 0; I < NumCounters; ++I) {
141 if (Line.is_at_end())
142 return error(instrprof_error::truncated);
143 uint64_t Count;
144 if ((Line++)->getAsInteger(10, Count))
145 return error(instrprof_error::malformed);
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000146 Record.Counts.push_back(Count);
Justin Bognerf8d79192014-03-21 17:24:48 +0000147 }
Justin Bognerf8d79192014-03-21 17:24:48 +0000148
149 return success();
150}
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000151
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000152template <class IntPtrT>
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000153bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000154 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000155 return false;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000156 uint64_t Magic =
157 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000158 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
159 sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000160}
161
162template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000163std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000164 if (!hasFormat(*DataBuffer))
165 return error(instrprof_error::bad_magic);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000166 if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000167 return error(instrprof_error::bad_header);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000168 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
169 DataBuffer->getBufferStart());
170 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000171 return readHeader(*Header);
172}
173
Justin Bognera119f322014-05-16 00:38:00 +0000174template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000175std::error_code
176RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
Justin Bognera119f322014-05-16 00:38:00 +0000177 const char *End = DataBuffer->getBufferEnd();
178 // Skip zero padding between profiles.
179 while (CurrentPos != End && *CurrentPos == 0)
180 ++CurrentPos;
181 // If there's nothing left, we're done.
182 if (CurrentPos == End)
183 return instrprof_error::eof;
184 // If there isn't enough space for another header, this is probably just
185 // garbage at the end of the file.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000186 if (CurrentPos + sizeof(RawInstrProf::Header) > End)
Justin Bognera119f322014-05-16 00:38:00 +0000187 return instrprof_error::malformed;
Justin Bogner54b11282014-09-12 21:22:55 +0000188 // The writer ensures each profile is padded to start at an aligned address.
189 if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
190 return instrprof_error::malformed;
Justin Bognera119f322014-05-16 00:38:00 +0000191 // The magic should have the same byte order as in the previous header.
192 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000193 if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
Justin Bognera119f322014-05-16 00:38:00 +0000194 return instrprof_error::bad_magic;
195
196 // There's another profile to read, so we need to process the header.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000197 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
Justin Bognera119f322014-05-16 00:38:00 +0000198 return readHeader(*Header);
199}
200
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000201template <class IntPtrT>
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000202std::error_code RawInstrProfReader<IntPtrT>::readHeader(
203 const RawInstrProf::Header &Header) {
204 if (swap(Header.Version) != RawInstrProf::Version)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000205 return error(instrprof_error::unsupported_version);
206
207 CountersDelta = swap(Header.CountersDelta);
208 NamesDelta = swap(Header.NamesDelta);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000209 ValueDataDelta = swap(Header.ValueDataDelta);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000210 auto DataSize = swap(Header.DataSize);
211 auto CountersSize = swap(Header.CountersSize);
212 auto NamesSize = swap(Header.NamesSize);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000213 auto ValueDataSize = swap(Header.ValueDataSize);
214 ValueKindLast = swap(Header.ValueKindLast);
215
216 auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
217 auto PaddingSize = getNumPaddingBytes(NamesSize);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000218
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000219 ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000220 ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000221 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000222 ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
223 size_t ProfileSize = ValueDataOffset + ValueDataSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000224
Justin Bognera119f322014-05-16 00:38:00 +0000225 auto *Start = reinterpret_cast<const char *>(&Header);
226 if (Start + ProfileSize > DataBuffer->getBufferEnd())
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000227 return error(instrprof_error::bad_header);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000228
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000229 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
230 Start + DataOffset);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000231 DataEnd = Data + DataSize;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000232 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
233 NamesStart = Start + NamesOffset;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000234 ValueDataStart = reinterpret_cast<const uint8_t*>(Start + ValueDataOffset);
Justin Bognera119f322014-05-16 00:38:00 +0000235 ProfileEnd = Start + ProfileSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000236
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000237 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());
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000251 return success();
252}
253
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000254template <class IntPtrT>
Xinliang David Licf4a1282015-10-28 19:34:04 +0000255std::error_code RawInstrProfReader<IntPtrT>::readName(InstrProfRecord &Record) {
256 Record.Name = StringRef(getName(Data->NamePtr), swap(Data->NameSize));
257 if (Record.Name.data() < NamesStart ||
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000258 Record.Name.data() + Record.Name.size() > (char*)ValueDataStart)
Xinliang David Licf4a1282015-10-28 19:34:04 +0000259 return error(instrprof_error::malformed);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000260 return success();
261}
262
263template <class IntPtrT>
264std::error_code RawInstrProfReader<IntPtrT>::readFuncHash(
265 InstrProfRecord &Record) {
266 Record.Hash = swap(Data->FuncHash);
267 return success();
268}
269
270template <class IntPtrT>
271std::error_code RawInstrProfReader<IntPtrT>::readRawCounts(
272 InstrProfRecord &Record) {
Justin Bognerb59d7c72014-04-25 02:45:33 +0000273 uint32_t NumCounters = swap(Data->NumCounters);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000274 IntPtrT CounterPtr = Data->CounterPtr;
Justin Bognerb59d7c72014-04-25 02:45:33 +0000275 if (NumCounters == 0)
276 return error(instrprof_error::malformed);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000277
278 auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
279 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000280
281 // Check bounds.
Xinliang David Licf4a1282015-10-28 19:34:04 +0000282 if (RawCounts.data() < CountersStart ||
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000283 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000284 return error(instrprof_error::malformed);
285
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000286 if (ShouldSwapBytes) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000287 Record.Counts.clear();
288 Record.Counts.reserve(RawCounts.size());
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000289 for (uint64_t Count : RawCounts)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000290 Record.Counts.push_back(swap(Count));
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000291 } else
292 Record.Counts = RawCounts;
293
Xinliang David Licf4a1282015-10-28 19:34:04 +0000294 return success();
295}
296
297template <class IntPtrT>
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000298std::error_code RawInstrProfReader<IntPtrT>::readValueData(
299 InstrProfRecord &Record) {
300
301 Record.clearValueData();
302 if (!Data->Values || (ValueDataDelta == 0))
303 return success();
304
305 // Read value data.
306 uint64_t NumVSites = 0;
307 for (uint32_t Kind = IPVK_First; Kind <= ValueKindLast; ++Kind)
308 NumVSites += swap(Data->NumValueSites[Kind]);
309 NumVSites += getNumPaddingBytes(NumVSites);
310
311 auto VDataCounts = makeArrayRef(getValueDataCounts(Data->Values), NumVSites);
312 // Check bounds.
313 if (VDataCounts.data() < ValueDataStart ||
314 VDataCounts.data() + VDataCounts.size() > (const uint8_t *)ProfileEnd)
315 return error(instrprof_error::malformed);
316
317 const InstrProfValueData *VDataPtr =
318 getValueData(swap(Data->Values) + NumVSites);
319 for (uint32_t Kind = IPVK_First; Kind <= ValueKindLast; ++Kind) {
320 NumVSites = swap(Data->NumValueSites[Kind]);
321 Record.reserveSites(Kind, NumVSites);
322 for (uint32_t VSite = 0; VSite < NumVSites; ++VSite) {
323
324 uint32_t VDataCount = VDataCounts[VSite];
325 if ((const char *)(VDataPtr + VDataCount) > ProfileEnd)
326 return error(instrprof_error::malformed);
327
328 std::vector<InstrProfValueData> CurrentValues;
329 CurrentValues.reserve(VDataCount);
330 for (uint32_t VIndex = 0; VIndex < VDataCount; ++VIndex) {
331 uint64_t TargetValue = swap(VDataPtr->Value);
332 uint64_t Count = swap(VDataPtr->Count);
333 CurrentValues.push_back({TargetValue, Count});
334 ++VDataPtr;
335 }
336 Record.addValueData(Kind, VSite, CurrentValues.data(),
337 VDataCount, &FunctionPtrToNameMap);
338 }
339 }
340 return success();
341}
342
343template <class IntPtrT>
344std::error_code RawInstrProfReader<IntPtrT>::readNextRecord(
345 InstrProfRecord &Record) {
Xinliang David Licf4a1282015-10-28 19:34:04 +0000346 if (atEnd())
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000347 if (std::error_code EC = readNextHeader(ProfileEnd))
348 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000349
350 // Read name ad set it in Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000351 if (std::error_code EC = readName(Record))
352 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000353
354 // Read FuncHash and set it in Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000355 if (std::error_code EC = readFuncHash(Record))
356 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000357
358 // Read raw counts and set Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000359 if (std::error_code EC = readRawCounts(Record))
360 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000361
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000362 // Read value data and set Record.
363 if (std::error_code EC = readValueData(Record)) return EC;
364
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000365 // Iterate.
Xinliang David Licf4a1282015-10-28 19:34:04 +0000366 advanceData();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000367 return success();
368}
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000369
370namespace llvm {
371template class RawInstrProfReader<uint32_t>;
372template class RawInstrProfReader<uint64_t>;
373}
Justin Bognerb7aa2632014-04-18 21:48:40 +0000374
Justin Bognerb5d368e2014-04-18 22:00:22 +0000375InstrProfLookupTrait::hash_value_type
376InstrProfLookupTrait::ComputeHash(StringRef K) {
377 return IndexedInstrProf::ComputeHash(HashType, K);
378}
379
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000380typedef InstrProfLookupTrait::data_type data_type;
381typedef InstrProfLookupTrait::offset_type offset_type;
382
Justin Bogner9e9a0572015-09-29 22:13:58 +0000383bool InstrProfLookupTrait::ReadValueProfilingData(
384 const unsigned char *&D, const unsigned char *const End) {
Xinliang David Li99556872015-11-17 23:00:40 +0000385 ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
386 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
Justin Bogner9e9a0572015-09-29 22:13:58 +0000387
Xinliang David Liee415892015-11-10 00:24:45 +0000388 if (VDataPtrOrErr.getError())
Justin Bogner9e9a0572015-09-29 22:13:58 +0000389 return false;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000390
Xinliang David Liee415892015-11-10 00:24:45 +0000391 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), &HashKeys);
392 D += VDataPtrOrErr.get()->TotalSize;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000393
Justin Bogner9e9a0572015-09-29 22:13:58 +0000394 return true;
395}
396
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000397data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
398 offset_type N) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000399 // Check if the data is corrupt. If so, don't try to read it.
400 if (N % sizeof(uint64_t))
401 return data_type();
402
403 DataBuffer.clear();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000404 std::vector<uint64_t> CounterBuffer;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000405
406 using namespace support;
407 const unsigned char *End = D + N;
408 while (D < End) {
Xinliang David Lic7583872015-10-13 16:35:59 +0000409 // Read hash.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000410 if (D + sizeof(uint64_t) >= End)
411 return data_type();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000412 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
413
Xinliang David Lic7583872015-10-13 16:35:59 +0000414 // Initialize number of counters for FormatVersion == 1.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000415 uint64_t CountsSize = N / sizeof(uint64_t) - 1;
Xinliang David Lic7583872015-10-13 16:35:59 +0000416 // If format version is different then read the number of counters.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000417 if (FormatVersion != 1) {
418 if (D + sizeof(uint64_t) > End)
419 return data_type();
420 CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
421 }
Xinliang David Lic7583872015-10-13 16:35:59 +0000422 // Read counter values.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000423 if (D + CountsSize * sizeof(uint64_t) > End)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000424 return data_type();
425
426 CounterBuffer.clear();
Justin Bogner9e9a0572015-09-29 22:13:58 +0000427 CounterBuffer.reserve(CountsSize);
428 for (uint64_t J = 0; J < CountsSize; ++J)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000429 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
430
Xinliang David Li2004f002015-11-02 05:08:23 +0000431 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
Justin Bogner9e9a0572015-09-29 22:13:58 +0000432
Xinliang David Lic7583872015-10-13 16:35:59 +0000433 // Read value profiling data.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000434 if (FormatVersion > 2 && !ReadValueProfilingData(D, End)) {
435 DataBuffer.clear();
436 return data_type();
437 }
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000438 }
439 return DataBuffer;
440}
441
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000442std::error_code
443InstrProfReaderIndex::getRecords(StringRef FuncName,
444 ArrayRef<InstrProfRecord> &Data) {
Xinliang David Li140f4c42015-10-28 04:20:31 +0000445 auto Iter = Index->find(FuncName);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000446 if (Iter == Index->end())
447 return instrprof_error::unknown_function;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000448
449 Data = (*Iter);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000450 if (Data.empty())
451 return instrprof_error::malformed;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000452
453 return instrprof_error::success;
454}
455
456std::error_code InstrProfReaderIndex::getRecords(
457 ArrayRef<InstrProfRecord> &Data) {
458 if (atEnd()) return instrprof_error::eof;
459
460 Data = *RecordIterator;
461
462 if (Data.empty()) return instrprof_error::malformed;
463
464 return instrprof_error::success;
465}
466
467void InstrProfReaderIndex::Init(const unsigned char *Buckets,
468 const unsigned char *const Payload,
469 const unsigned char *const Base,
470 IndexedInstrProf::HashT HashType,
471 uint64_t Version) {
472 FormatVersion = Version;
473 Index.reset(IndexType::Create(Buckets, Payload, Base,
474 InstrProfLookupTrait(HashType, Version)));
475 // Form the map of hash values to const char* keys in profiling data.
476 std::vector<std::pair<uint64_t, const char *>> HashKeys;
477 for (auto Key : Index->keys()) {
478 const char *KeyTableRef = StringTable.insertString(Key);
479 HashKeys.push_back(std::make_pair(ComputeHash(HashType, Key), KeyTableRef));
480 }
481 std::sort(HashKeys.begin(), HashKeys.end(), less_first());
482 HashKeys.erase(std::unique(HashKeys.begin(), HashKeys.end()), HashKeys.end());
483 // Set the hash key map for the InstrLookupTrait
484 Index->getInfoObj().setHashKeys(std::move(HashKeys));
485 RecordIterator = Index->data_begin();
486}
487
Justin Bognerb7aa2632014-04-18 21:48:40 +0000488bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000489 if (DataBuffer.getBufferSize() < 8)
490 return false;
Justin Bognerb7aa2632014-04-18 21:48:40 +0000491 using namespace support;
492 uint64_t Magic =
493 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
Xinliang David Lic7583872015-10-13 16:35:59 +0000494 // Verify that it's magical.
Justin Bognerb7aa2632014-04-18 21:48:40 +0000495 return Magic == IndexedInstrProf::Magic;
496}
497
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000498std::error_code IndexedInstrProfReader::readHeader() {
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000499 const unsigned char *Start =
500 (const unsigned char *)DataBuffer->getBufferStart();
Justin Bognerb7aa2632014-04-18 21:48:40 +0000501 const unsigned char *Cur = Start;
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000502 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000503 return error(instrprof_error::truncated);
504
505 using namespace support;
506
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000507 auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
508 Cur += sizeof(IndexedInstrProf::Header);
509
Justin Bognerb7aa2632014-04-18 21:48:40 +0000510 // Check the magic number.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000511 uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000512 if (Magic != IndexedInstrProf::Magic)
513 return error(instrprof_error::bad_magic);
514
515 // Read the version.
Xinliang David Li140f4c42015-10-28 04:20:31 +0000516 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
Justin Bogner821d7472014-08-01 22:50:07 +0000517 if (FormatVersion > IndexedInstrProf::Version)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000518 return error(instrprof_error::unsupported_version);
519
520 // Read the maximal function count.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000521 MaxFunctionCount =
522 endian::byte_swap<uint64_t, little>(Header->MaxFunctionCount);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000523
524 // Read the hash type and start offset.
525 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000526 endian::byte_swap<uint64_t, little>(Header->HashType));
Justin Bognerb7aa2632014-04-18 21:48:40 +0000527 if (HashType > IndexedInstrProf::HashT::Last)
528 return error(instrprof_error::unsupported_hash_type);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000529
530 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000531
532 // The rest of the file is an on disk hash table.
Xinliang David Li140f4c42015-10-28 04:20:31 +0000533 Index.Init(Start + HashOffset, Cur, Start, HashType, FormatVersion);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000534
535 return success();
536}
537
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000538ErrorOr<InstrProfRecord>
539IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
540 uint64_t FuncHash) {
Xinliang David Li140f4c42015-10-28 04:20:31 +0000541 ArrayRef<InstrProfRecord> Data;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000542 std::error_code EC = Index.getRecords(FuncName, Data);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000543 if (EC != instrprof_error::success)
544 return EC;
Justin Bogner821d7472014-08-01 22:50:07 +0000545 // Found it. Look for counters with the right hash.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000546 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
Justin Bogner821d7472014-08-01 22:50:07 +0000547 // Check for a match and fill the vector if there is one.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000548 if (Data[I].Hash == FuncHash) {
Xinliang David Li2004f002015-11-02 05:08:23 +0000549 return std::move(Data[I]);
Justin Bogner821d7472014-08-01 22:50:07 +0000550 }
551 }
552 return error(instrprof_error::hash_mismatch);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000553}
554
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000555std::error_code
556IndexedInstrProfReader::getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
557 std::vector<uint64_t> &Counts) {
Xinliang David Li2004f002015-11-02 05:08:23 +0000558 ErrorOr<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000559 if (std::error_code EC = Record.getError())
560 return EC;
Xinliang David Li2004f002015-11-02 05:08:23 +0000561
562 Counts = Record.get().Counts;
563 return success();
564}
565
Xinliang David Li140f4c42015-10-28 04:20:31 +0000566std::error_code IndexedInstrProfReader::readNextRecord(
567 InstrProfRecord &Record) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000568 static unsigned RecordIndex = 0;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000569
570 ArrayRef<InstrProfRecord> Data;
571
572 std::error_code EC = Index.getRecords(Data);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000573 if (EC != instrprof_error::success)
574 return error(EC);
Xinliang David Li140f4c42015-10-28 04:20:31 +0000575
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000576 Record = Data[RecordIndex++];
577 if (RecordIndex >= Data.size()) {
Xinliang David Li140f4c42015-10-28 04:20:31 +0000578 Index.advanceToNextKey();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000579 RecordIndex = 0;
Justin Bogner821d7472014-08-01 22:50:07 +0000580 }
Justin Bognerb7aa2632014-04-18 21:48:40 +0000581 return success();
582}