blob: 7e9b7ab7c8a4098e0874140ba421720f4b98d9e6 [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 Lia716cc52015-12-20 06:22:13 +0000112std::error_code TextInstrProfReader::readHeader() {
113 Symtab.reset(new InstrProfSymtab());
114 return success();
115}
116
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000117std::error_code
118TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
119
120#define CHECK_LINE_END(Line) \
121 if (Line.is_at_end()) \
122 return error(instrprof_error::truncated);
123#define READ_NUM(Str, Dst) \
124 if ((Str).getAsInteger(10, (Dst))) \
125 return error(instrprof_error::malformed);
126#define VP_READ_ADVANCE(Val) \
127 CHECK_LINE_END(Line); \
128 uint32_t Val; \
129 READ_NUM((*Line), (Val)); \
130 Line++;
131
132 if (Line.is_at_end())
133 return success();
Xinliang David Lia716cc52015-12-20 06:22:13 +0000134
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000135 uint32_t NumValueKinds;
136 if (Line->getAsInteger(10, NumValueKinds)) {
137 // No value profile data
138 return success();
139 }
140 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
141 return error(instrprof_error::malformed);
142 Line++;
143
144 for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
145 VP_READ_ADVANCE(ValueKind);
146 if (ValueKind > IPVK_Last)
147 return error(instrprof_error::malformed);
148 VP_READ_ADVANCE(NumValueSites);
149 if (!NumValueSites)
150 continue;
151
152 Record.reserveSites(VK, NumValueSites);
153 for (uint32_t S = 0; S < NumValueSites; S++) {
154 VP_READ_ADVANCE(NumValueData);
155
156 std::vector<InstrProfValueData> CurrentValues;
157 for (uint32_t V = 0; V < NumValueData; V++) {
158 CHECK_LINE_END(Line);
159 std::pair<StringRef, StringRef> VD = Line->split(':');
160 uint64_t TakenCount, Value;
Xinliang David Lia716cc52015-12-20 06:22:13 +0000161 if (VK == IPVK_IndirectCallTarget) {
162 Symtab->addFuncName(VD.first);
163 Value = IndexedInstrProf::ComputeHash(VD.first);
164 } else {
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000165 READ_NUM(VD.first, Value);
166 }
Xinliang David Lia716cc52015-12-20 06:22:13 +0000167 READ_NUM(VD.second, TakenCount);
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000168 CurrentValues.push_back({Value, TakenCount});
169 Line++;
170 }
171 Record.addValueData(VK, S, CurrentValues.data(), NumValueData, nullptr);
172 }
173 }
174 return success();
175
176#undef CHECK_LINE_END
177#undef READ_NUM
178#undef VP_READ_ADVANCE
179}
180
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000181std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
Justin Bognercf36a362014-07-29 22:29:23 +0000182 // Skip empty lines and comments.
183 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
Justin Bognerf8d79192014-03-21 17:24:48 +0000184 ++Line;
185 // If we hit EOF while looking for a name, we're done.
Xinliang David Lia716cc52015-12-20 06:22:13 +0000186 if (Line.is_at_end()) {
187 Symtab->finalizeSymtab();
Justin Bognerf8d79192014-03-21 17:24:48 +0000188 return error(instrprof_error::eof);
Xinliang David Lia716cc52015-12-20 06:22:13 +0000189 }
Justin Bognerf8d79192014-03-21 17:24:48 +0000190
191 // Read the function name.
192 Record.Name = *Line++;
Xinliang David Lia716cc52015-12-20 06:22:13 +0000193 Symtab->addFuncName(Record.Name);
Justin Bognerf8d79192014-03-21 17:24:48 +0000194
195 // Read the function hash.
196 if (Line.is_at_end())
197 return error(instrprof_error::truncated);
Justin Bognerf95ca072015-03-09 18:54:49 +0000198 if ((Line++)->getAsInteger(0, Record.Hash))
Justin Bognerf8d79192014-03-21 17:24:48 +0000199 return error(instrprof_error::malformed);
200
201 // Read the number of counters.
202 uint64_t NumCounters;
203 if (Line.is_at_end())
204 return error(instrprof_error::truncated);
205 if ((Line++)->getAsInteger(10, NumCounters))
206 return error(instrprof_error::malformed);
Justin Bognerb59d7c72014-04-25 02:45:33 +0000207 if (NumCounters == 0)
208 return error(instrprof_error::malformed);
Justin Bognerf8d79192014-03-21 17:24:48 +0000209
210 // Read each counter and fill our internal storage with the values.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000211 Record.Counts.clear();
212 Record.Counts.reserve(NumCounters);
Justin Bognerf8d79192014-03-21 17:24:48 +0000213 for (uint64_t I = 0; I < NumCounters; ++I) {
214 if (Line.is_at_end())
215 return error(instrprof_error::truncated);
216 uint64_t Count;
217 if ((Line++)->getAsInteger(10, Count))
218 return error(instrprof_error::malformed);
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000219 Record.Counts.push_back(Count);
Justin Bognerf8d79192014-03-21 17:24:48 +0000220 }
Justin Bognerf8d79192014-03-21 17:24:48 +0000221
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000222 // Check if value profile data exists and read it if so.
223 if (std::error_code EC = readValueProfileData(Record))
224 return EC;
225
Xinliang David Lia716cc52015-12-20 06:22:13 +0000226 // This is needed to avoid two pass parsing because llvm-profdata
227 // does dumping while reading.
228 Symtab->finalizeSymtab();
Justin Bognerf8d79192014-03-21 17:24:48 +0000229 return success();
230}
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000231
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000232template <class IntPtrT>
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000233bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000234 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000235 return false;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000236 uint64_t Magic =
237 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000238 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
239 sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000240}
241
242template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000243std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000244 if (!hasFormat(*DataBuffer))
245 return error(instrprof_error::bad_magic);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000246 if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000247 return error(instrprof_error::bad_header);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000248 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
249 DataBuffer->getBufferStart());
250 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000251 return readHeader(*Header);
252}
253
Justin Bognera119f322014-05-16 00:38:00 +0000254template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000255std::error_code
256RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
Justin Bognera119f322014-05-16 00:38:00 +0000257 const char *End = DataBuffer->getBufferEnd();
258 // Skip zero padding between profiles.
259 while (CurrentPos != End && *CurrentPos == 0)
260 ++CurrentPos;
261 // If there's nothing left, we're done.
262 if (CurrentPos == End)
263 return instrprof_error::eof;
264 // If there isn't enough space for another header, this is probably just
265 // garbage at the end of the file.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000266 if (CurrentPos + sizeof(RawInstrProf::Header) > End)
Justin Bognera119f322014-05-16 00:38:00 +0000267 return instrprof_error::malformed;
Justin Bogner54b11282014-09-12 21:22:55 +0000268 // The writer ensures each profile is padded to start at an aligned address.
269 if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
270 return instrprof_error::malformed;
Justin Bognera119f322014-05-16 00:38:00 +0000271 // The magic should have the same byte order as in the previous header.
272 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000273 if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
Justin Bognera119f322014-05-16 00:38:00 +0000274 return instrprof_error::bad_magic;
275
276 // There's another profile to read, so we need to process the header.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000277 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
Justin Bognera119f322014-05-16 00:38:00 +0000278 return readHeader(*Header);
279}
280
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000281template <class IntPtrT>
Xinliang David Lia716cc52015-12-20 06:22:13 +0000282void RawInstrProfReader<IntPtrT>::createSymtab(InstrProfSymtab &Symtab) {
283 for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
284 StringRef FunctionName(getName(I->NamePtr), swap(I->NameSize));
285 Symtab.addFuncName(FunctionName);
286 const IntPtrT FPtr = swap(I->FunctionPointer);
287 if (!FPtr)
288 continue;
289 Symtab.mapAddress(FPtr, IndexedInstrProf::ComputeHash(FunctionName));
290 }
291 Symtab.finalizeSymtab();
292}
293
294template <class IntPtrT>
295std::error_code
296RawInstrProfReader<IntPtrT>::readHeader(const RawInstrProf::Header &Header) {
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000297 if (swap(Header.Version) != RawInstrProf::Version)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000298 return error(instrprof_error::unsupported_version);
299
300 CountersDelta = swap(Header.CountersDelta);
301 NamesDelta = swap(Header.NamesDelta);
302 auto DataSize = swap(Header.DataSize);
303 auto CountersSize = swap(Header.CountersSize);
304 auto NamesSize = swap(Header.NamesSize);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000305 auto ValueDataSize = swap(Header.ValueDataSize);
306 ValueKindLast = swap(Header.ValueKindLast);
307
308 auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
309 auto PaddingSize = getNumPaddingBytes(NamesSize);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000310
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000311 ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000312 ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000313 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000314 ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
315 size_t ProfileSize = ValueDataOffset + ValueDataSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000316
Justin Bognera119f322014-05-16 00:38:00 +0000317 auto *Start = reinterpret_cast<const char *>(&Header);
318 if (Start + ProfileSize > DataBuffer->getBufferEnd())
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000319 return error(instrprof_error::bad_header);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000320
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000321 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
322 Start + DataOffset);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000323 DataEnd = Data + DataSize;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000324 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
325 NamesStart = Start + NamesOffset;
Xinliang David Lia716cc52015-12-20 06:22:13 +0000326 ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset);
Justin Bognera119f322014-05-16 00:38:00 +0000327 ProfileEnd = Start + ProfileSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000328
Xinliang David Lia716cc52015-12-20 06:22:13 +0000329 std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
330 createSymtab(*NewSymtab.get());
331 Symtab = std::move(NewSymtab);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000332 return success();
333}
334
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000335template <class IntPtrT>
Xinliang David Licf4a1282015-10-28 19:34:04 +0000336std::error_code RawInstrProfReader<IntPtrT>::readName(InstrProfRecord &Record) {
337 Record.Name = StringRef(getName(Data->NamePtr), swap(Data->NameSize));
338 if (Record.Name.data() < NamesStart ||
Xinliang David Licfb14562015-11-18 22:42:27 +0000339 Record.Name.data() + Record.Name.size() >
340 reinterpret_cast<const char *>(ValueDataStart))
Xinliang David Licf4a1282015-10-28 19:34:04 +0000341 return error(instrprof_error::malformed);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000342 return success();
343}
344
345template <class IntPtrT>
346std::error_code RawInstrProfReader<IntPtrT>::readFuncHash(
347 InstrProfRecord &Record) {
348 Record.Hash = swap(Data->FuncHash);
349 return success();
350}
351
352template <class IntPtrT>
353std::error_code RawInstrProfReader<IntPtrT>::readRawCounts(
354 InstrProfRecord &Record) {
Justin Bognerb59d7c72014-04-25 02:45:33 +0000355 uint32_t NumCounters = swap(Data->NumCounters);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000356 IntPtrT CounterPtr = Data->CounterPtr;
Justin Bognerb59d7c72014-04-25 02:45:33 +0000357 if (NumCounters == 0)
358 return error(instrprof_error::malformed);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000359
360 auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
361 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000362
363 // Check bounds.
Xinliang David Licf4a1282015-10-28 19:34:04 +0000364 if (RawCounts.data() < CountersStart ||
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000365 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000366 return error(instrprof_error::malformed);
367
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000368 if (ShouldSwapBytes) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000369 Record.Counts.clear();
370 Record.Counts.reserve(RawCounts.size());
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000371 for (uint64_t Count : RawCounts)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000372 Record.Counts.push_back(swap(Count));
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000373 } else
374 Record.Counts = RawCounts;
375
Xinliang David Licf4a1282015-10-28 19:34:04 +0000376 return success();
377}
378
379template <class IntPtrT>
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000380std::error_code
381RawInstrProfReader<IntPtrT>::readValueProfilingData(InstrProfRecord &Record) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000382
383 Record.clearValueData();
Xinliang David Lid922c262015-12-11 06:53:53 +0000384 CurValueDataSize = 0;
385 // Need to match the logic in value profile dumper code in compiler-rt:
386 uint32_t NumValueKinds = 0;
387 for (uint32_t I = 0; I < IPVK_Last + 1; I++)
388 NumValueKinds += (Data->NumValueSites[I] != 0);
389
390 if (!NumValueKinds)
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000391 return success();
392
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000393 ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
Xinliang David Lid922c262015-12-11 06:53:53 +0000394 ValueProfData::getValueProfData(ValueDataStart,
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000395 (const unsigned char *)ProfileEnd,
396 getDataEndianness());
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000397
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000398 if (VDataPtrOrErr.getError())
399 return VDataPtrOrErr.getError();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000400
Xinliang David Lia716cc52015-12-20 06:22:13 +0000401 VDataPtrOrErr.get()->deserializeTo(Record, &Symtab->getAddrHashMap());
Xinliang David Lid922c262015-12-11 06:53:53 +0000402 CurValueDataSize = VDataPtrOrErr.get()->getSize();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000403 return success();
404}
405
406template <class IntPtrT>
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000407std::error_code
408RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
Xinliang David Licf4a1282015-10-28 19:34:04 +0000409 if (atEnd())
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000410 if (std::error_code EC = readNextHeader(ProfileEnd))
411 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000412
413 // Read name ad set it in Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000414 if (std::error_code EC = readName(Record))
415 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000416
417 // Read FuncHash and set it in Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000418 if (std::error_code EC = readFuncHash(Record))
419 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000420
421 // Read raw counts and set Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000422 if (std::error_code EC = readRawCounts(Record))
423 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000424
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000425 // Read value data and set Record.
Xinliang David Li2d4803e2015-12-10 23:48:05 +0000426 if (std::error_code EC = readValueProfilingData(Record))
427 return EC;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000428
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000429 // Iterate.
Xinliang David Licf4a1282015-10-28 19:34:04 +0000430 advanceData();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000431 return success();
432}
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000433
434namespace llvm {
435template class RawInstrProfReader<uint32_t>;
436template class RawInstrProfReader<uint64_t>;
437}
Justin Bognerb7aa2632014-04-18 21:48:40 +0000438
Justin Bognerb5d368e2014-04-18 22:00:22 +0000439InstrProfLookupTrait::hash_value_type
440InstrProfLookupTrait::ComputeHash(StringRef K) {
441 return IndexedInstrProf::ComputeHash(HashType, K);
442}
443
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000444typedef InstrProfLookupTrait::data_type data_type;
445typedef InstrProfLookupTrait::offset_type offset_type;
446
Xinliang David Libe969c22015-11-28 05:06:00 +0000447bool InstrProfLookupTrait::readValueProfilingData(
Justin Bogner9e9a0572015-09-29 22:13:58 +0000448 const unsigned char *&D, const unsigned char *const End) {
Xinliang David Li99556872015-11-17 23:00:40 +0000449 ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
450 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
Justin Bogner9e9a0572015-09-29 22:13:58 +0000451
Xinliang David Liee415892015-11-10 00:24:45 +0000452 if (VDataPtrOrErr.getError())
Justin Bogner9e9a0572015-09-29 22:13:58 +0000453 return false;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000454
Xinliang David Lia716cc52015-12-20 06:22:13 +0000455 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);
Xinliang David Liee415892015-11-10 00:24:45 +0000456 D += VDataPtrOrErr.get()->TotalSize;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000457
Justin Bogner9e9a0572015-09-29 22:13:58 +0000458 return true;
459}
460
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000461data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
462 offset_type N) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000463 // Check if the data is corrupt. If so, don't try to read it.
464 if (N % sizeof(uint64_t))
465 return data_type();
466
467 DataBuffer.clear();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000468 std::vector<uint64_t> CounterBuffer;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000469
470 using namespace support;
471 const unsigned char *End = D + N;
472 while (D < End) {
Xinliang David Lic7583872015-10-13 16:35:59 +0000473 // Read hash.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000474 if (D + sizeof(uint64_t) >= End)
475 return data_type();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000476 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
477
Xinliang David Lic7583872015-10-13 16:35:59 +0000478 // Initialize number of counters for FormatVersion == 1.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000479 uint64_t CountsSize = N / sizeof(uint64_t) - 1;
Xinliang David Lic7583872015-10-13 16:35:59 +0000480 // If format version is different then read the number of counters.
Xinliang David Lia6b2c4f2016-01-14 02:47:01 +0000481 if (FormatVersion != IndexedInstrProf::ProfVersion::Version1) {
Justin Bogner9e9a0572015-09-29 22:13:58 +0000482 if (D + sizeof(uint64_t) > End)
483 return data_type();
484 CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
485 }
Xinliang David Lic7583872015-10-13 16:35:59 +0000486 // Read counter values.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000487 if (D + CountsSize * sizeof(uint64_t) > End)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000488 return data_type();
489
490 CounterBuffer.clear();
Justin Bogner9e9a0572015-09-29 22:13:58 +0000491 CounterBuffer.reserve(CountsSize);
492 for (uint64_t J = 0; J < CountsSize; ++J)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000493 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
494
Xinliang David Li2004f002015-11-02 05:08:23 +0000495 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
Justin Bogner9e9a0572015-09-29 22:13:58 +0000496
Xinliang David Lic7583872015-10-13 16:35:59 +0000497 // Read value profiling data.
Xinliang David Lia6b2c4f2016-01-14 02:47:01 +0000498 if (FormatVersion > IndexedInstrProf::ProfVersion::Version2 &&
499 !readValueProfilingData(D, End)) {
Justin Bogner9e9a0572015-09-29 22:13:58 +0000500 DataBuffer.clear();
501 return data_type();
502 }
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000503 }
504 return DataBuffer;
505}
506
Xinliang David Lia28306d2015-12-01 20:26:26 +0000507template <typename HashTableImpl>
508std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
509 StringRef FuncName, ArrayRef<InstrProfRecord> &Data) {
510 auto Iter = HashTable->find(FuncName);
511 if (Iter == HashTable->end())
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000512 return instrprof_error::unknown_function;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000513
514 Data = (*Iter);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000515 if (Data.empty())
516 return instrprof_error::malformed;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000517
518 return instrprof_error::success;
519}
520
Xinliang David Lia28306d2015-12-01 20:26:26 +0000521template <typename HashTableImpl>
522std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
Xinliang David Li140f4c42015-10-28 04:20:31 +0000523 ArrayRef<InstrProfRecord> &Data) {
Xinliang David Lia28306d2015-12-01 20:26:26 +0000524 if (atEnd())
525 return instrprof_error::eof;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000526
527 Data = *RecordIterator;
528
Xinliang David Li2d4803e2015-12-10 23:48:05 +0000529 if (Data.empty())
530 return instrprof_error::malformed;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000531
532 return instrprof_error::success;
533}
534
Xinliang David Lia28306d2015-12-01 20:26:26 +0000535template <typename HashTableImpl>
536InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
537 const unsigned char *Buckets, const unsigned char *const Payload,
538 const unsigned char *const Base, IndexedInstrProf::HashT HashType,
539 uint64_t Version) {
Xinliang David Li140f4c42015-10-28 04:20:31 +0000540 FormatVersion = Version;
Xinliang David Lia28306d2015-12-01 20:26:26 +0000541 HashTable.reset(HashTableImpl::Create(
542 Buckets, Payload, Base,
543 typename HashTableImpl::InfoType(HashType, Version)));
Xinliang David Lia28306d2015-12-01 20:26:26 +0000544 RecordIterator = HashTable->data_begin();
Xinliang David Li140f4c42015-10-28 04:20:31 +0000545}
546
Justin Bognerb7aa2632014-04-18 21:48:40 +0000547bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000548 if (DataBuffer.getBufferSize() < 8)
549 return false;
Justin Bognerb7aa2632014-04-18 21:48:40 +0000550 using namespace support;
551 uint64_t Magic =
552 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
Xinliang David Lic7583872015-10-13 16:35:59 +0000553 // Verify that it's magical.
Justin Bognerb7aa2632014-04-18 21:48:40 +0000554 return Magic == IndexedInstrProf::Magic;
555}
556
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000557std::error_code IndexedInstrProfReader::readHeader() {
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000558 const unsigned char *Start =
559 (const unsigned char *)DataBuffer->getBufferStart();
Justin Bognerb7aa2632014-04-18 21:48:40 +0000560 const unsigned char *Cur = Start;
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000561 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000562 return error(instrprof_error::truncated);
563
564 using namespace support;
565
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000566 auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
567 Cur += sizeof(IndexedInstrProf::Header);
568
Justin Bognerb7aa2632014-04-18 21:48:40 +0000569 // Check the magic number.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000570 uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000571 if (Magic != IndexedInstrProf::Magic)
572 return error(instrprof_error::bad_magic);
573
574 // Read the version.
Xinliang David Li140f4c42015-10-28 04:20:31 +0000575 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
Xinliang David Lia6b2c4f2016-01-14 02:47:01 +0000576 if (FormatVersion > IndexedInstrProf::ProfVersion::CurrentVersion)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000577 return error(instrprof_error::unsupported_version);
578
579 // Read the maximal function count.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000580 MaxFunctionCount =
581 endian::byte_swap<uint64_t, little>(Header->MaxFunctionCount);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000582
583 // Read the hash type and start offset.
584 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000585 endian::byte_swap<uint64_t, little>(Header->HashType));
Justin Bognerb7aa2632014-04-18 21:48:40 +0000586 if (HashType > IndexedInstrProf::HashT::Last)
587 return error(instrprof_error::unsupported_hash_type);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000588
589 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000590
591 // The rest of the file is an on disk hash table.
Xinliang David Lia28306d2015-12-01 20:26:26 +0000592 InstrProfReaderIndexBase *IndexPtr = nullptr;
593 IndexPtr = new InstrProfReaderIndex<OnDiskHashTableImplV3>(
594 Start + HashOffset, Cur, Start, HashType, FormatVersion);
595 Index.reset(IndexPtr);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000596 return success();
597}
598
Xinliang David Lia716cc52015-12-20 06:22:13 +0000599InstrProfSymtab &IndexedInstrProfReader::getSymtab() {
600 if (Symtab.get())
601 return *Symtab.get();
602
603 std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
604 Index->populateSymtab(*NewSymtab.get());
605
606 Symtab = std::move(NewSymtab);
607 return *Symtab.get();
608}
609
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000610ErrorOr<InstrProfRecord>
611IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
612 uint64_t FuncHash) {
Xinliang David Li140f4c42015-10-28 04:20:31 +0000613 ArrayRef<InstrProfRecord> Data;
Xinliang David Lia28306d2015-12-01 20:26:26 +0000614 std::error_code EC = Index->getRecords(FuncName, Data);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000615 if (EC != instrprof_error::success)
616 return EC;
Justin Bogner821d7472014-08-01 22:50:07 +0000617 // Found it. Look for counters with the right hash.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000618 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
Justin Bogner821d7472014-08-01 22:50:07 +0000619 // Check for a match and fill the vector if there is one.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000620 if (Data[I].Hash == FuncHash) {
Xinliang David Li2004f002015-11-02 05:08:23 +0000621 return std::move(Data[I]);
Justin Bogner821d7472014-08-01 22:50:07 +0000622 }
623 }
624 return error(instrprof_error::hash_mismatch);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000625}
626
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000627std::error_code
628IndexedInstrProfReader::getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
629 std::vector<uint64_t> &Counts) {
Xinliang David Li2004f002015-11-02 05:08:23 +0000630 ErrorOr<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000631 if (std::error_code EC = Record.getError())
632 return EC;
Xinliang David Li2004f002015-11-02 05:08:23 +0000633
634 Counts = Record.get().Counts;
635 return success();
636}
637
Xinliang David Li140f4c42015-10-28 04:20:31 +0000638std::error_code IndexedInstrProfReader::readNextRecord(
639 InstrProfRecord &Record) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000640 static unsigned RecordIndex = 0;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000641
642 ArrayRef<InstrProfRecord> Data;
643
Xinliang David Lia28306d2015-12-01 20:26:26 +0000644 std::error_code EC = Index->getRecords(Data);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000645 if (EC != instrprof_error::success)
646 return error(EC);
Xinliang David Li140f4c42015-10-28 04:20:31 +0000647
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000648 Record = Data[RecordIndex++];
649 if (RecordIndex >= Data.size()) {
Xinliang David Lia28306d2015-12-01 20:26:26 +0000650 Index->advanceToNextKey();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000651 RecordIndex = 0;
Justin Bogner821d7472014-08-01 22:50:07 +0000652 }
Justin Bognerb7aa2632014-04-18 21:48:40 +0000653 return success();
654}