blob: aca43544145329d2da4dab4e7e3702db06c66797 [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();
Vedant Kumar2491dd12015-12-11 00:40:05 +0000107 return count == 0 ||
108 std::all_of(buffer.begin(), buffer.begin() + count,
109 [](char c) { return ::isprint(c) || ::isspace(c); });
Nathan Slingerland4f823662015-11-13 03:47:58 +0000110}
111
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000112std::error_code
113TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
114
115#define CHECK_LINE_END(Line) \
116 if (Line.is_at_end()) \
117 return error(instrprof_error::truncated);
118#define READ_NUM(Str, Dst) \
119 if ((Str).getAsInteger(10, (Dst))) \
120 return error(instrprof_error::malformed);
121#define VP_READ_ADVANCE(Val) \
122 CHECK_LINE_END(Line); \
123 uint32_t Val; \
124 READ_NUM((*Line), (Val)); \
125 Line++;
126
127 if (Line.is_at_end())
128 return success();
129 uint32_t NumValueKinds;
130 if (Line->getAsInteger(10, NumValueKinds)) {
131 // No value profile data
132 return success();
133 }
134 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
135 return error(instrprof_error::malformed);
136 Line++;
137
138 for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
139 VP_READ_ADVANCE(ValueKind);
140 if (ValueKind > IPVK_Last)
141 return error(instrprof_error::malformed);
142 VP_READ_ADVANCE(NumValueSites);
143 if (!NumValueSites)
144 continue;
145
146 Record.reserveSites(VK, NumValueSites);
147 for (uint32_t S = 0; S < NumValueSites; S++) {
148 VP_READ_ADVANCE(NumValueData);
149
150 std::vector<InstrProfValueData> CurrentValues;
151 for (uint32_t V = 0; V < NumValueData; V++) {
152 CHECK_LINE_END(Line);
153 std::pair<StringRef, StringRef> VD = Line->split(':');
154 uint64_t TakenCount, Value;
155 READ_NUM(VD.second, TakenCount);
156 if (VK == IPVK_IndirectCallTarget)
157 Value = (uint64_t)StringTable.insertString(VD.first);
158 else {
159 READ_NUM(VD.first, Value);
160 }
161 CurrentValues.push_back({Value, TakenCount});
162 Line++;
163 }
164 Record.addValueData(VK, S, CurrentValues.data(), NumValueData, nullptr);
165 }
166 }
167 return success();
168
169#undef CHECK_LINE_END
170#undef READ_NUM
171#undef VP_READ_ADVANCE
172}
173
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000174std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
Justin Bognercf36a362014-07-29 22:29:23 +0000175 // Skip empty lines and comments.
176 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
Justin Bognerf8d79192014-03-21 17:24:48 +0000177 ++Line;
178 // If we hit EOF while looking for a name, we're done.
179 if (Line.is_at_end())
180 return error(instrprof_error::eof);
181
182 // Read the function name.
183 Record.Name = *Line++;
184
185 // Read the function hash.
186 if (Line.is_at_end())
187 return error(instrprof_error::truncated);
Justin Bognerf95ca072015-03-09 18:54:49 +0000188 if ((Line++)->getAsInteger(0, Record.Hash))
Justin Bognerf8d79192014-03-21 17:24:48 +0000189 return error(instrprof_error::malformed);
190
191 // Read the number of counters.
192 uint64_t NumCounters;
193 if (Line.is_at_end())
194 return error(instrprof_error::truncated);
195 if ((Line++)->getAsInteger(10, NumCounters))
196 return error(instrprof_error::malformed);
Justin Bognerb59d7c72014-04-25 02:45:33 +0000197 if (NumCounters == 0)
198 return error(instrprof_error::malformed);
Justin Bognerf8d79192014-03-21 17:24:48 +0000199
200 // Read each counter and fill our internal storage with the values.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000201 Record.Counts.clear();
202 Record.Counts.reserve(NumCounters);
Justin Bognerf8d79192014-03-21 17:24:48 +0000203 for (uint64_t I = 0; I < NumCounters; ++I) {
204 if (Line.is_at_end())
205 return error(instrprof_error::truncated);
206 uint64_t Count;
207 if ((Line++)->getAsInteger(10, Count))
208 return error(instrprof_error::malformed);
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000209 Record.Counts.push_back(Count);
Justin Bognerf8d79192014-03-21 17:24:48 +0000210 }
Justin Bognerf8d79192014-03-21 17:24:48 +0000211
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000212 // Check if value profile data exists and read it if so.
213 if (std::error_code EC = readValueProfileData(Record))
214 return EC;
215
Justin Bognerf8d79192014-03-21 17:24:48 +0000216 return success();
217}
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000218
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000219template <class IntPtrT>
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000220bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000221 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000222 return false;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000223 uint64_t Magic =
224 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000225 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
226 sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000227}
228
229template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000230std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000231 if (!hasFormat(*DataBuffer))
232 return error(instrprof_error::bad_magic);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000233 if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000234 return error(instrprof_error::bad_header);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000235 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
236 DataBuffer->getBufferStart());
237 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000238 return readHeader(*Header);
239}
240
Justin Bognera119f322014-05-16 00:38:00 +0000241template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000242std::error_code
243RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
Justin Bognera119f322014-05-16 00:38:00 +0000244 const char *End = DataBuffer->getBufferEnd();
245 // Skip zero padding between profiles.
246 while (CurrentPos != End && *CurrentPos == 0)
247 ++CurrentPos;
248 // If there's nothing left, we're done.
249 if (CurrentPos == End)
250 return instrprof_error::eof;
251 // If there isn't enough space for another header, this is probably just
252 // garbage at the end of the file.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000253 if (CurrentPos + sizeof(RawInstrProf::Header) > End)
Justin Bognera119f322014-05-16 00:38:00 +0000254 return instrprof_error::malformed;
Justin Bogner54b11282014-09-12 21:22:55 +0000255 // The writer ensures each profile is padded to start at an aligned address.
256 if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
257 return instrprof_error::malformed;
Justin Bognera119f322014-05-16 00:38:00 +0000258 // The magic should have the same byte order as in the previous header.
259 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000260 if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
Justin Bognera119f322014-05-16 00:38:00 +0000261 return instrprof_error::bad_magic;
262
263 // There's another profile to read, so we need to process the header.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000264 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
Justin Bognera119f322014-05-16 00:38:00 +0000265 return readHeader(*Header);
266}
267
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000268template <class IntPtrT>
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000269std::error_code RawInstrProfReader<IntPtrT>::readHeader(
270 const RawInstrProf::Header &Header) {
271 if (swap(Header.Version) != RawInstrProf::Version)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000272 return error(instrprof_error::unsupported_version);
273
274 CountersDelta = swap(Header.CountersDelta);
275 NamesDelta = swap(Header.NamesDelta);
276 auto DataSize = swap(Header.DataSize);
277 auto CountersSize = swap(Header.CountersSize);
278 auto NamesSize = swap(Header.NamesSize);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000279 auto ValueDataSize = swap(Header.ValueDataSize);
280 ValueKindLast = swap(Header.ValueKindLast);
281
282 auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
283 auto PaddingSize = getNumPaddingBytes(NamesSize);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000284
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000285 ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000286 ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000287 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000288 ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
289 size_t ProfileSize = ValueDataOffset + ValueDataSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000290
Justin Bognera119f322014-05-16 00:38:00 +0000291 auto *Start = reinterpret_cast<const char *>(&Header);
292 if (Start + ProfileSize > DataBuffer->getBufferEnd())
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000293 return error(instrprof_error::bad_header);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000294
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000295 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
296 Start + DataOffset);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000297 DataEnd = Data + DataSize;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000298 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
299 NamesStart = Start + NamesOffset;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000300 ValueDataStart = reinterpret_cast<const uint8_t*>(Start + ValueDataOffset);
Justin Bognera119f322014-05-16 00:38:00 +0000301 ProfileEnd = Start + ProfileSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000302
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000303 FunctionPtrToNameMap.clear();
304 for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
305 const IntPtrT FPtr = swap(I->FunctionPointer);
306 if (!FPtr)
307 continue;
308 StringRef FunctionName(getName(I->NamePtr), swap(I->NameSize));
309 const char* NameEntryPtr = StringTable.insertString(FunctionName);
310 FunctionPtrToNameMap.push_back(std::pair<const IntPtrT, const char*>
311 (FPtr, NameEntryPtr));
312 }
313 std::sort(FunctionPtrToNameMap.begin(), FunctionPtrToNameMap.end(), less_first());
314 FunctionPtrToNameMap.erase(std::unique(FunctionPtrToNameMap.begin(),
315 FunctionPtrToNameMap.end()),
316 FunctionPtrToNameMap.end());
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000317 return success();
318}
319
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000320template <class IntPtrT>
Xinliang David Licf4a1282015-10-28 19:34:04 +0000321std::error_code RawInstrProfReader<IntPtrT>::readName(InstrProfRecord &Record) {
322 Record.Name = StringRef(getName(Data->NamePtr), swap(Data->NameSize));
323 if (Record.Name.data() < NamesStart ||
Xinliang David Licfb14562015-11-18 22:42:27 +0000324 Record.Name.data() + Record.Name.size() >
325 reinterpret_cast<const char *>(ValueDataStart))
Xinliang David Licf4a1282015-10-28 19:34:04 +0000326 return error(instrprof_error::malformed);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000327 return success();
328}
329
330template <class IntPtrT>
331std::error_code RawInstrProfReader<IntPtrT>::readFuncHash(
332 InstrProfRecord &Record) {
333 Record.Hash = swap(Data->FuncHash);
334 return success();
335}
336
337template <class IntPtrT>
338std::error_code RawInstrProfReader<IntPtrT>::readRawCounts(
339 InstrProfRecord &Record) {
Justin Bognerb59d7c72014-04-25 02:45:33 +0000340 uint32_t NumCounters = swap(Data->NumCounters);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000341 IntPtrT CounterPtr = Data->CounterPtr;
Justin Bognerb59d7c72014-04-25 02:45:33 +0000342 if (NumCounters == 0)
343 return error(instrprof_error::malformed);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000344
345 auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
346 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000347
348 // Check bounds.
Xinliang David Licf4a1282015-10-28 19:34:04 +0000349 if (RawCounts.data() < CountersStart ||
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000350 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000351 return error(instrprof_error::malformed);
352
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000353 if (ShouldSwapBytes) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000354 Record.Counts.clear();
355 Record.Counts.reserve(RawCounts.size());
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000356 for (uint64_t Count : RawCounts)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000357 Record.Counts.push_back(swap(Count));
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000358 } else
359 Record.Counts = RawCounts;
360
Xinliang David Licf4a1282015-10-28 19:34:04 +0000361 return success();
362}
363
364template <class IntPtrT>
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000365std::error_code
366RawInstrProfReader<IntPtrT>::readValueProfilingData(InstrProfRecord &Record) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000367
368 Record.clearValueData();
Xinliang David Lid922c262015-12-11 06:53:53 +0000369 CurValueDataSize = 0;
370 // Need to match the logic in value profile dumper code in compiler-rt:
371 uint32_t NumValueKinds = 0;
372 for (uint32_t I = 0; I < IPVK_Last + 1; I++)
373 NumValueKinds += (Data->NumValueSites[I] != 0);
374
375 if (!NumValueKinds)
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000376 return success();
377
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000378 ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
Xinliang David Lid922c262015-12-11 06:53:53 +0000379 ValueProfData::getValueProfData(ValueDataStart,
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000380 (const unsigned char *)ProfileEnd,
381 getDataEndianness());
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000382
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000383 if (VDataPtrOrErr.getError())
384 return VDataPtrOrErr.getError();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000385
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000386 VDataPtrOrErr.get()->deserializeTo(Record, &FunctionPtrToNameMap);
Xinliang David Lid922c262015-12-11 06:53:53 +0000387 CurValueDataSize = VDataPtrOrErr.get()->getSize();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000388 return success();
389}
390
391template <class IntPtrT>
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000392std::error_code
393RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
Xinliang David Licf4a1282015-10-28 19:34:04 +0000394 if (atEnd())
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000395 if (std::error_code EC = readNextHeader(ProfileEnd))
396 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000397
398 // Read name ad set it in Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000399 if (std::error_code EC = readName(Record))
400 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000401
402 // Read FuncHash and set it in Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000403 if (std::error_code EC = readFuncHash(Record))
404 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000405
406 // Read raw counts and set Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000407 if (std::error_code EC = readRawCounts(Record))
408 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000409
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000410 // Read value data and set Record.
Xinliang David Li2d4803e2015-12-10 23:48:05 +0000411 if (std::error_code EC = readValueProfilingData(Record))
412 return EC;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000413
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000414 // Iterate.
Xinliang David Licf4a1282015-10-28 19:34:04 +0000415 advanceData();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000416 return success();
417}
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000418
419namespace llvm {
420template class RawInstrProfReader<uint32_t>;
421template class RawInstrProfReader<uint64_t>;
422}
Justin Bognerb7aa2632014-04-18 21:48:40 +0000423
Justin Bognerb5d368e2014-04-18 22:00:22 +0000424InstrProfLookupTrait::hash_value_type
425InstrProfLookupTrait::ComputeHash(StringRef K) {
426 return IndexedInstrProf::ComputeHash(HashType, K);
427}
428
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000429typedef InstrProfLookupTrait::data_type data_type;
430typedef InstrProfLookupTrait::offset_type offset_type;
431
Xinliang David Libe969c22015-11-28 05:06:00 +0000432bool InstrProfLookupTrait::readValueProfilingData(
Justin Bogner9e9a0572015-09-29 22:13:58 +0000433 const unsigned char *&D, const unsigned char *const End) {
Xinliang David Li99556872015-11-17 23:00:40 +0000434 ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
435 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
Justin Bogner9e9a0572015-09-29 22:13:58 +0000436
Xinliang David Liee415892015-11-10 00:24:45 +0000437 if (VDataPtrOrErr.getError())
Justin Bogner9e9a0572015-09-29 22:13:58 +0000438 return false;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000439
Xinliang David Liee415892015-11-10 00:24:45 +0000440 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), &HashKeys);
441 D += VDataPtrOrErr.get()->TotalSize;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000442
Justin Bogner9e9a0572015-09-29 22:13:58 +0000443 return true;
444}
445
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000446data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
447 offset_type N) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000448 // Check if the data is corrupt. If so, don't try to read it.
449 if (N % sizeof(uint64_t))
450 return data_type();
451
452 DataBuffer.clear();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000453 std::vector<uint64_t> CounterBuffer;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000454
455 using namespace support;
456 const unsigned char *End = D + N;
457 while (D < End) {
Xinliang David Lic7583872015-10-13 16:35:59 +0000458 // Read hash.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000459 if (D + sizeof(uint64_t) >= End)
460 return data_type();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000461 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
462
Xinliang David Lic7583872015-10-13 16:35:59 +0000463 // Initialize number of counters for FormatVersion == 1.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000464 uint64_t CountsSize = N / sizeof(uint64_t) - 1;
Xinliang David Lic7583872015-10-13 16:35:59 +0000465 // If format version is different then read the number of counters.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000466 if (FormatVersion != 1) {
467 if (D + sizeof(uint64_t) > End)
468 return data_type();
469 CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
470 }
Xinliang David Lic7583872015-10-13 16:35:59 +0000471 // Read counter values.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000472 if (D + CountsSize * sizeof(uint64_t) > End)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000473 return data_type();
474
475 CounterBuffer.clear();
Justin Bogner9e9a0572015-09-29 22:13:58 +0000476 CounterBuffer.reserve(CountsSize);
477 for (uint64_t J = 0; J < CountsSize; ++J)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000478 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
479
Xinliang David Li2004f002015-11-02 05:08:23 +0000480 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
Justin Bogner9e9a0572015-09-29 22:13:58 +0000481
Xinliang David Lic7583872015-10-13 16:35:59 +0000482 // Read value profiling data.
Xinliang David Libe969c22015-11-28 05:06:00 +0000483 if (FormatVersion > 2 && !readValueProfilingData(D, End)) {
Justin Bogner9e9a0572015-09-29 22:13:58 +0000484 DataBuffer.clear();
485 return data_type();
486 }
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000487 }
488 return DataBuffer;
489}
490
Xinliang David Lia28306d2015-12-01 20:26:26 +0000491template <typename HashTableImpl>
492std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
493 StringRef FuncName, ArrayRef<InstrProfRecord> &Data) {
494 auto Iter = HashTable->find(FuncName);
495 if (Iter == HashTable->end())
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000496 return instrprof_error::unknown_function;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000497
498 Data = (*Iter);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000499 if (Data.empty())
500 return instrprof_error::malformed;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000501
502 return instrprof_error::success;
503}
504
Xinliang David Lia28306d2015-12-01 20:26:26 +0000505template <typename HashTableImpl>
506std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
Xinliang David Li140f4c42015-10-28 04:20:31 +0000507 ArrayRef<InstrProfRecord> &Data) {
Xinliang David Lia28306d2015-12-01 20:26:26 +0000508 if (atEnd())
509 return instrprof_error::eof;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000510
511 Data = *RecordIterator;
512
Xinliang David Li2d4803e2015-12-10 23:48:05 +0000513 if (Data.empty())
514 return instrprof_error::malformed;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000515
516 return instrprof_error::success;
517}
518
Xinliang David Lia28306d2015-12-01 20:26:26 +0000519template <typename HashTableImpl>
520InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
521 const unsigned char *Buckets, const unsigned char *const Payload,
522 const unsigned char *const Base, IndexedInstrProf::HashT HashType,
523 uint64_t Version) {
Xinliang David Li140f4c42015-10-28 04:20:31 +0000524 FormatVersion = Version;
Xinliang David Lia28306d2015-12-01 20:26:26 +0000525 HashTable.reset(HashTableImpl::Create(
526 Buckets, Payload, Base,
527 typename HashTableImpl::InfoType(HashType, Version)));
Xinliang David Li140f4c42015-10-28 04:20:31 +0000528 // Form the map of hash values to const char* keys in profiling data.
529 std::vector<std::pair<uint64_t, const char *>> HashKeys;
Xinliang David Lia28306d2015-12-01 20:26:26 +0000530 for (auto Key : HashTable->keys()) {
Xinliang David Li140f4c42015-10-28 04:20:31 +0000531 const char *KeyTableRef = StringTable.insertString(Key);
532 HashKeys.push_back(std::make_pair(ComputeHash(HashType, Key), KeyTableRef));
533 }
534 std::sort(HashKeys.begin(), HashKeys.end(), less_first());
535 HashKeys.erase(std::unique(HashKeys.begin(), HashKeys.end()), HashKeys.end());
536 // Set the hash key map for the InstrLookupTrait
Xinliang David Lia28306d2015-12-01 20:26:26 +0000537 HashTable->getInfoObj().setHashKeys(std::move(HashKeys));
538 RecordIterator = HashTable->data_begin();
Xinliang David Li140f4c42015-10-28 04:20:31 +0000539}
540
Justin Bognerb7aa2632014-04-18 21:48:40 +0000541bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000542 if (DataBuffer.getBufferSize() < 8)
543 return false;
Justin Bognerb7aa2632014-04-18 21:48:40 +0000544 using namespace support;
545 uint64_t Magic =
546 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
Xinliang David Lic7583872015-10-13 16:35:59 +0000547 // Verify that it's magical.
Justin Bognerb7aa2632014-04-18 21:48:40 +0000548 return Magic == IndexedInstrProf::Magic;
549}
550
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000551std::error_code IndexedInstrProfReader::readHeader() {
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000552 const unsigned char *Start =
553 (const unsigned char *)DataBuffer->getBufferStart();
Justin Bognerb7aa2632014-04-18 21:48:40 +0000554 const unsigned char *Cur = Start;
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000555 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000556 return error(instrprof_error::truncated);
557
558 using namespace support;
559
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000560 auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
561 Cur += sizeof(IndexedInstrProf::Header);
562
Justin Bognerb7aa2632014-04-18 21:48:40 +0000563 // Check the magic number.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000564 uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000565 if (Magic != IndexedInstrProf::Magic)
566 return error(instrprof_error::bad_magic);
567
568 // Read the version.
Xinliang David Li140f4c42015-10-28 04:20:31 +0000569 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
Justin Bogner821d7472014-08-01 22:50:07 +0000570 if (FormatVersion > IndexedInstrProf::Version)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000571 return error(instrprof_error::unsupported_version);
572
573 // Read the maximal function count.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000574 MaxFunctionCount =
575 endian::byte_swap<uint64_t, little>(Header->MaxFunctionCount);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000576
577 // Read the hash type and start offset.
578 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000579 endian::byte_swap<uint64_t, little>(Header->HashType));
Justin Bognerb7aa2632014-04-18 21:48:40 +0000580 if (HashType > IndexedInstrProf::HashT::Last)
581 return error(instrprof_error::unsupported_hash_type);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000582
583 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000584
585 // The rest of the file is an on disk hash table.
Xinliang David Lia28306d2015-12-01 20:26:26 +0000586 InstrProfReaderIndexBase *IndexPtr = nullptr;
587 IndexPtr = new InstrProfReaderIndex<OnDiskHashTableImplV3>(
588 Start + HashOffset, Cur, Start, HashType, FormatVersion);
589 Index.reset(IndexPtr);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000590 return success();
591}
592
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000593ErrorOr<InstrProfRecord>
594IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
595 uint64_t FuncHash) {
Xinliang David Li140f4c42015-10-28 04:20:31 +0000596 ArrayRef<InstrProfRecord> Data;
Xinliang David Lia28306d2015-12-01 20:26:26 +0000597 std::error_code EC = Index->getRecords(FuncName, Data);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000598 if (EC != instrprof_error::success)
599 return EC;
Justin Bogner821d7472014-08-01 22:50:07 +0000600 // Found it. Look for counters with the right hash.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000601 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
Justin Bogner821d7472014-08-01 22:50:07 +0000602 // Check for a match and fill the vector if there is one.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000603 if (Data[I].Hash == FuncHash) {
Xinliang David Li2004f002015-11-02 05:08:23 +0000604 return std::move(Data[I]);
Justin Bogner821d7472014-08-01 22:50:07 +0000605 }
606 }
607 return error(instrprof_error::hash_mismatch);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000608}
609
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000610std::error_code
611IndexedInstrProfReader::getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
612 std::vector<uint64_t> &Counts) {
Xinliang David Li2004f002015-11-02 05:08:23 +0000613 ErrorOr<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000614 if (std::error_code EC = Record.getError())
615 return EC;
Xinliang David Li2004f002015-11-02 05:08:23 +0000616
617 Counts = Record.get().Counts;
618 return success();
619}
620
Xinliang David Li140f4c42015-10-28 04:20:31 +0000621std::error_code IndexedInstrProfReader::readNextRecord(
622 InstrProfRecord &Record) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000623 static unsigned RecordIndex = 0;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000624
625 ArrayRef<InstrProfRecord> Data;
626
Xinliang David Lia28306d2015-12-01 20:26:26 +0000627 std::error_code EC = Index->getRecords(Data);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000628 if (EC != instrprof_error::success)
629 return error(EC);
Xinliang David Li140f4c42015-10-28 04:20:31 +0000630
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000631 Record = Data[RecordIndex++];
632 if (RecordIndex >= Data.size()) {
Xinliang David Lia28306d2015-12-01 20:26:26 +0000633 Index->advanceToNextKey();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000634 RecordIndex = 0;
Justin Bogner821d7472014-08-01 22:50:07 +0000635 }
Justin Bognerb7aa2632014-04-18 21:48:40 +0000636 return success();
637}