LLVM 24.0.0git
InstrProfReader.cpp
Go to the documentation of this file.
1//===- InstrProfReader.cpp - Instrumented profiling reader ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for reading profiling data for clang's
10// instrumentation based PGO and coverage.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/StringRef.h"
21// #include "llvm/ProfileData/MemProf.h"
25#include "llvm/Support/Endian.h"
26#include "llvm/Support/Error.h"
31#include <algorithm>
32#include <cstddef>
33#include <cstdint>
34#include <limits>
35#include <memory>
36#include <optional>
37#include <system_error>
38#include <utility>
39#include <vector>
40
41using namespace llvm;
42
43// Extracts the variant information from the top 32 bits in the version and
44// returns an enum specifying the variants present.
47 if (Version & VARIANT_MASK_IR_PROF) {
49 }
50 if (Version & VARIANT_MASK_CSIR_PROF) {
52 }
53 if (Version & VARIANT_MASK_INSTR_ENTRY) {
55 }
56 if (Version & VARIANT_MASK_INSTR_LOOP_ENTRIES) {
58 }
59 if (Version & VARIANT_MASK_BYTE_COVERAGE) {
61 }
64 }
65 if (Version & VARIANT_MASK_MEMPROF) {
66 ProfileKind |= InstrProfKind::MemProf;
67 }
68 if (Version & VARIANT_MASK_TEMPORAL_PROF) {
69 ProfileKind |= InstrProfKind::TemporalProfile;
70 }
71 return ProfileKind;
72}
73
76 auto BufferOrErr = Filename.str() == "-" ? MemoryBuffer::getSTDIN()
77 : FS.getBufferForFile(Filename);
78 if (std::error_code EC = BufferOrErr.getError())
79 return errorCodeToError(EC);
80 return std::move(BufferOrErr.get());
81}
82
84 return Reader.readHeader();
85}
86
87/// Read a list of binary ids from a profile that consist of
88/// a. uint64_t binary id length
89/// b. uint8_t binary id data
90/// c. uint8_t padding (if necessary)
91/// This function is shared between raw and indexed profiles.
92/// Raw profiles are in host-endian format, and indexed profiles are in
93/// little-endian format. So, this function takes an argument indicating the
94/// associated endian format to read the binary ids correctly.
95static Error
97 ArrayRef<uint8_t> BinaryIdsBuffer,
98 std::vector<llvm::object::BuildID> &BinaryIds,
99 const llvm::endianness Endian) {
100 using namespace support;
101
102 const uint64_t BinaryIdsSize = BinaryIdsBuffer.size();
103 const uint8_t *BinaryIdsStart = BinaryIdsBuffer.data();
104
105 if (BinaryIdsSize == 0)
106 return Error::success();
107
108 const uint8_t *BI = BinaryIdsStart;
109 const uint8_t *BIEnd = BinaryIdsStart + BinaryIdsSize;
110 const uint8_t *End =
111 reinterpret_cast<const uint8_t *>(DataBuffer.getBufferEnd());
112
113 while (BI < BIEnd) {
114 size_t Remaining = BIEnd - BI;
115 // There should be enough left to read the binary id length.
116 if (Remaining < sizeof(uint64_t))
119 "not enough data to read binary id length");
120
121 uint64_t BILen = endian::readNext<uint64_t>(BI, Endian);
122 if (BILen == 0)
124 "binary id length is 0");
125
126 Remaining = BIEnd - BI;
127 // There should be enough left to read the binary id data.
128 if (Remaining < alignToPowerOf2(BILen, sizeof(uint64_t)))
130 instrprof_error::malformed, "not enough data to read binary id data");
131
132 // Add binary id to the binary ids list.
133 BinaryIds.push_back(object::BuildID(BI, BI + BILen));
134
135 // Increment by binary id data length, which aligned to the size of uint64.
136 BI += alignToPowerOf2(BILen, sizeof(uint64_t));
137 if (BI > End)
140 "binary id section is greater than buffer size");
141 }
142
143 return Error::success();
144}
145
148 OS << "Binary IDs: \n";
149 for (const auto &BI : BinaryIds) {
150 for (auto I : BI)
151 OS << format("%02x", I);
152 OS << "\n";
153 }
154}
155
157 const Twine &Path, vfs::FileSystem &FS,
158 const InstrProfCorrelator *Correlator,
159 const object::BuildIDFetcher *BIDFetcher,
160 const InstrProfCorrelator::ProfCorrelatorKind BIDFetcherCorrelatorKind,
161 std::function<void(Error)> Warn) {
162 // Set up the buffer to read.
163 auto BufferOrError = setupMemoryBuffer(Path, FS);
164 if (Error E = BufferOrError.takeError())
165 return std::move(E);
166 return InstrProfReader::create(std::move(BufferOrError.get()), Correlator,
167 BIDFetcher, BIDFetcherCorrelatorKind, Warn);
168}
169
171 std::unique_ptr<MemoryBuffer> Buffer, const InstrProfCorrelator *Correlator,
172 const object::BuildIDFetcher *BIDFetcher,
173 const InstrProfCorrelator::ProfCorrelatorKind BIDFetcherCorrelatorKind,
174 std::function<void(Error)> Warn) {
175 if (Buffer->getBufferSize() == 0)
177
178 std::unique_ptr<InstrProfReader> Result;
179 // Create the reader.
181 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
182 else if (RawInstrProfReader64::hasFormat(*Buffer))
183 Result.reset(new RawInstrProfReader64(std::move(Buffer), Correlator,
184 BIDFetcher, BIDFetcherCorrelatorKind,
185 Warn));
186 else if (RawInstrProfReader32::hasFormat(*Buffer))
187 Result.reset(new RawInstrProfReader32(std::move(Buffer), Correlator,
188 BIDFetcher, BIDFetcherCorrelatorKind,
189 Warn));
190 else if (TextInstrProfReader::hasFormat(*Buffer))
191 Result.reset(new TextInstrProfReader(std::move(Buffer)));
192 else
194
195 // Initialize the reader and return the result.
196 if (Error E = initializeReader(*Result))
197 return std::move(E);
198
199 return std::move(Result);
200}
201
204 const Twine &RemappingPath) {
205 // Set up the buffer to read.
206 auto BufferOrError = setupMemoryBuffer(Path, FS);
207 if (Error E = BufferOrError.takeError())
208 return std::move(E);
209
210 // Set up the remapping buffer if requested.
211 std::unique_ptr<MemoryBuffer> RemappingBuffer;
212 std::string RemappingPathStr = RemappingPath.str();
213 if (!RemappingPathStr.empty()) {
214 auto RemappingBufferOrError = setupMemoryBuffer(RemappingPathStr, FS);
215 if (Error E = RemappingBufferOrError.takeError())
216 return std::move(E);
217 RemappingBuffer = std::move(RemappingBufferOrError.get());
218 }
219
220 return IndexedInstrProfReader::create(std::move(BufferOrError.get()),
221 std::move(RemappingBuffer));
222}
223
225IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer,
226 std::unique_ptr<MemoryBuffer> RemappingBuffer) {
227 // Create the reader.
230 auto Result = std::make_unique<IndexedInstrProfReader>(
231 std::move(Buffer), std::move(RemappingBuffer));
232
233 // Initialize the reader and return the result.
234 if (Error E = initializeReader(*Result))
235 return std::move(E);
236
237 return std::move(Result);
238}
239
241 // Verify that this really looks like plain ASCII text by checking a
242 // 'reasonable' number of characters (up to profile magic size).
243 size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));
244 StringRef buffer = Buffer.getBufferStart();
245 return count == 0 ||
246 std::all_of(buffer.begin(), buffer.begin() + count,
247 [](char c) { return isPrint(c) || isSpace(c); });
248}
249
250// Read the profile variant flag from the header: ":FE" means this is a FE
251// generated profile. ":IR" means this is an IR level profile. Other strings
252// with a leading ':' will be reported an error format.
254 Symtab.reset(new InstrProfSymtab());
255
256 while (Line->starts_with(":")) {
257 StringRef Str = Line->substr(1);
258 if (Str.equals_insensitive("ir"))
260 else if (Str.equals_insensitive("fe"))
262 else if (Str.equals_insensitive("csir")) {
264 ProfileKind |= InstrProfKind::ContextSensitive;
265 } else if (Str.equals_insensitive("entry_first"))
267 else if (Str.equals_insensitive("not_entry_first"))
269 else if (Str.equals_insensitive("instrument_loop_entries"))
271 else if (Str.equals_insensitive("single_byte_coverage"))
273 else if (Str.equals_insensitive("temporal_prof_traces")) {
274 ProfileKind |= InstrProfKind::TemporalProfile;
275 if (auto Err = readTemporalProfTraceData())
276 return error(std::move(Err));
277 } else
279 ++Line;
280 }
281 return success();
282}
283
284/// Temporal profile trace data is stored in the header immediately after
285/// ":temporal_prof_traces". The first integer is the number of traces, the
286/// second integer is the stream size, then the following lines are the actual
287/// traces which consist of a weight and a comma separated list of function
288/// names.
289Error TextInstrProfReader::readTemporalProfTraceData() {
290 if ((++Line).is_at_end())
292
293 uint32_t NumTraces;
294 if (Line->getAsInteger(0, NumTraces))
296
297 if ((++Line).is_at_end())
299
300 if (Line->getAsInteger(0, TemporalProfTraceStreamSize))
302
303 for (uint32_t i = 0; i < NumTraces; i++) {
304 if ((++Line).is_at_end())
306
308 if (Line->getAsInteger(0, Trace.Weight))
310
311 if ((++Line).is_at_end())
313
314 SmallVector<StringRef> FuncNames;
315 Line->split(FuncNames, ",", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
316 for (auto &FuncName : FuncNames)
317 Trace.FunctionNameRefs.push_back(
318 IndexedInstrProf::ComputeHash(FuncName.trim()));
319 TemporalProfTraces.push_back(std::move(Trace));
320 }
321 return success();
322}
323
324Error
325TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
326
327#define CHECK_LINE_END(Line) \
328 if (Line.is_at_end()) \
329 return error(instrprof_error::truncated);
330#define READ_NUM(Str, Dst) \
331 if ((Str).getAsInteger(10, (Dst))) \
332 return error(instrprof_error::malformed);
333#define VP_READ_ADVANCE(Val) \
334 CHECK_LINE_END(Line); \
335 uint32_t Val; \
336 READ_NUM((*Line), (Val)); \
337 Line++;
338
339 if (Line.is_at_end())
340 return success();
341
342 uint32_t NumValueKinds;
343 if (Line->getAsInteger(10, NumValueKinds)) {
344 // No value profile data
345 return success();
346 }
347 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
349 "number of value kinds is invalid");
350 Line++;
351
352 for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
353 VP_READ_ADVANCE(ValueKind);
354 if (ValueKind > IPVK_Last)
355 return error(instrprof_error::malformed, "value kind is invalid");
356 ;
358 if (!NumValueSites)
359 continue;
360
361 Record.reserveSites(VK, NumValueSites);
362 for (uint32_t S = 0; S < NumValueSites; S++) {
363 VP_READ_ADVANCE(NumValueData);
364
365 std::vector<InstrProfValueData> CurrentValues;
366 for (uint32_t V = 0; V < NumValueData; V++) {
367 CHECK_LINE_END(Line);
368 std::pair<StringRef, StringRef> VD = Line->rsplit(':');
369 uint64_t TakenCount, Value;
370 if (ValueKind == IPVK_IndirectCallTarget) {
371 if (InstrProfSymtab::isExternalSymbol(VD.first)) {
372 Value = 0;
373 } else {
374 if (Error E = Symtab->addFuncName(VD.first))
375 return E;
377 }
378 } else if (ValueKind == IPVK_VTableTarget) {
380 Value = 0;
381 else {
382 if (Error E = Symtab->addVTableName(VD.first))
383 return E;
385 }
386 } else {
387 READ_NUM(VD.first, Value);
388 }
389 READ_NUM(VD.second, TakenCount);
390 CurrentValues.push_back({Value, TakenCount});
391 Line++;
392 }
393 assert(CurrentValues.size() == NumValueData);
394 Record.addValueData(ValueKind, S, CurrentValues, nullptr);
395 }
396 }
397 return success();
398
399#undef CHECK_LINE_END
400#undef READ_NUM
401#undef VP_READ_ADVANCE
402}
403
405 // Skip empty lines and comments.
406 while (!Line.is_at_end() && (Line->empty() || Line->starts_with("#")))
407 ++Line;
408 // If we hit EOF while looking for a name, we're done.
409 if (Line.is_at_end()) {
411 }
412
413 // Read the function name.
414 Record.Name = *Line++;
415 if (Error E = Symtab->addFuncName(Record.Name))
416 return error(std::move(E));
417
418 // Read the function hash.
419 if (Line.is_at_end())
421 if ((Line++)->getAsInteger(0, Record.Hash))
423 "function hash is not a valid integer");
424
425 // Read the number of counters.
426 uint64_t NumCounters;
427 if (Line.is_at_end())
429 if ((Line++)->getAsInteger(10, NumCounters))
431 "number of counters is not a valid integer");
432 if (NumCounters == 0)
433 return error(instrprof_error::malformed, "number of counters is zero");
434
435 // Read each counter and fill our internal storage with the values.
436 Record.Clear();
437 Record.Counts.reserve(NumCounters);
438 for (uint64_t I = 0; I < NumCounters; ++I) {
439 if (Line.is_at_end())
441 uint64_t Count;
442 if ((Line++)->getAsInteger(10, Count))
443 return error(instrprof_error::malformed, "count is invalid");
444 Record.Counts.push_back(Count);
445 }
446
447 // Bitmap byte information is indicated by '$' followed by an integer. Only
448 // treat numeric-looking lines as bitmap records so function names such as
449 // Swift manglings beginning with "$s" remain unambiguous.
450 StringRef BitmapSize =
451 Line->starts_with("$") ? Line->drop_front(1).trim() : StringRef();
452 if (!BitmapSize.empty() && isDigit(BitmapSize.front())) {
453 Record.BitmapBytes.clear();
454 // Read the number of bitmap bytes.
455 uint64_t NumBitmapBytes;
456 if ((Line++)->drop_front(1).trim().getAsInteger(0, NumBitmapBytes))
458 "number of bitmap bytes is not a valid integer");
459 if (NumBitmapBytes != 0) {
460 // Read each bitmap and fill our internal storage with the values.
461 Record.BitmapBytes.reserve(NumBitmapBytes);
462 for (uint64_t I = 0; I < NumBitmapBytes; ++I) {
463 if (Line.is_at_end())
465 uint8_t BitmapByte;
466 if ((Line++)->getAsInteger(0, BitmapByte))
468 "bitmap byte is not a valid integer");
469 Record.BitmapBytes.push_back(BitmapByte);
470 }
471 }
472 }
473
474 // Check if value profile data exists and read it if so.
475 if (Error E = readValueProfileData(Record))
476 return error(std::move(E));
477
478 return success();
479}
480
481template <class IntPtrT>
485
486template <class IntPtrT>
489 std::optional<uint64_t> Weight) {
490 if (TemporalProfTimestamps.empty()) {
491 assert(TemporalProfTraces.empty());
492 return TemporalProfTraces;
493 }
494 // Sort functions by their timestamps to build the trace.
495 std::sort(TemporalProfTimestamps.begin(), TemporalProfTimestamps.end());
497 if (Weight)
498 Trace.Weight = *Weight;
499 for (auto &[TimestampValue, NameRef] : TemporalProfTimestamps)
500 Trace.FunctionNameRefs.push_back(NameRef);
501 TemporalProfTraces = {std::move(Trace)};
502 return TemporalProfTraces;
503}
504
505template <class IntPtrT>
507 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
508 return false;
509 uint64_t Magic =
510 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
511 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
513}
514
515template <class IntPtrT>
517 if (!hasFormat(*DataBuffer))
519 if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
521 std::string("profile file header is truncated"));
522 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
523 DataBuffer->getBufferStart());
524 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
525 return readHeader(*Header);
526}
527
528template <class IntPtrT>
529Error RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
530 const char *End = DataBuffer->getBufferEnd();
531 // Skip zero padding between profiles.
532 while (CurrentPos != End && *CurrentPos == 0)
533 ++CurrentPos;
534 // If there's nothing left, we're done.
535 if (CurrentPos == End)
537 // If there isn't enough space for another header, this is probably just
538 // garbage at the end of the file.
539 if (CurrentPos + sizeof(RawInstrProf::Header) > End)
541 "not enough space for another header");
542 // The writer ensures each profile is padded to start at an aligned address.
543 if (reinterpret_cast<size_t>(CurrentPos) % alignof(uint64_t))
545 "insufficient padding");
546 // The magic should have the same byte order as in the previous header.
547 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
548 if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
550
551 // There's another profile to read, so we need to process the header.
552 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
553 return readHeader(*Header);
554}
555
556template <class IntPtrT>
557Error RawInstrProfReader<IntPtrT>::createSymtab(InstrProfSymtab &Symtab) {
558 if (Error E = Symtab.create(StringRef(NamesStart, NamesEnd - NamesStart),
559 StringRef(VNamesStart, VNamesEnd - VNamesStart)))
560 return error(std::move(E));
561 for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
562 const IntPtrT FPtr = swap(I->FunctionPointer);
563 if (!FPtr)
564 continue;
565 Symtab.mapAddress(FPtr, swap(I->NameRef));
566 }
567
568 if (VTableBegin != nullptr && VTableEnd != nullptr) {
569 for (const RawInstrProf::VTableProfileData<IntPtrT> *I = VTableBegin;
570 I != VTableEnd; ++I) {
571 const IntPtrT VPtr = swap(I->VTablePointer);
572 if (!VPtr)
573 continue;
574 // Map both begin and end address to the name hash, since the instrumented
575 // address could be somewhere in the middle.
576 // VPtr is of type uint32_t or uint64_t so 'VPtr + I->VTableSize' marks
577 // the end of vtable address.
578 Symtab.mapVTableAddress(VPtr, VPtr + swap(I->VTableSize),
579 swap(I->VTableNameHash));
580 }
581 }
582 return success();
583}
584
585template <class IntPtrT>
587 const RawInstrProf::Header &Header) {
588 Version = swap(Header.Version);
591 ("Profile uses raw profile format version = " +
593 "; expected version = " + Twine(RawInstrProf::Version) +
594 "\nPLEASE update this tool to version in the raw profile, or "
595 "regenerate raw profile with expected version.")
596 .str());
597 uint64_t BinaryIdSize = swap(Header.BinaryIdsSize);
598 // Binary id start just after the header if exists.
599 const uint8_t *BinaryIdStart =
600 reinterpret_cast<const uint8_t *>(&Header) + sizeof(RawInstrProf::Header);
601 const uint8_t *BinaryIdEnd = BinaryIdStart + BinaryIdSize;
602 const uint8_t *BufferEnd = (const uint8_t *)DataBuffer->getBufferEnd();
603 if (BinaryIdSize % sizeof(uint64_t))
604 return error(
606 ("BinaryIdSize (" + Twine(BinaryIdSize) + ") is not a multiple of 8")
607 .str());
608 if (BinaryIdEnd > BufferEnd)
610 ("Header.BinaryIdSize = " + Twine(BinaryIdSize) + " bytes; " +
611 Twine(BufferEnd - BinaryIdStart) + " bytes available")
612 .str());
613
614 ArrayRef<uint8_t> BinaryIdsBuffer(BinaryIdStart, BinaryIdSize);
615 if (!BinaryIdsBuffer.empty()) {
616 if (Error Err = readBinaryIdsInternal(*DataBuffer, BinaryIdsBuffer,
617 BinaryIds, getDataEndianness()))
618 return Err;
619 }
620
621 CountersDelta = swap(Header.CountersDelta);
622 BitmapDelta = swap(Header.BitmapDelta);
623 UniformCountersDelta = swap(Header.UniformCountersDelta);
624 NamesDelta = swap(Header.NamesDelta);
625 auto NumData = swap(Header.NumData);
626 auto PaddingBytesBeforeCounters = swap(Header.PaddingBytesBeforeCounters);
627 auto CountersSize = swap(Header.NumCounters) * getCounterTypeSize();
628 auto PaddingBytesAfterCounters = swap(Header.PaddingBytesAfterCounters);
629 auto NumBitmapBytes = swap(Header.NumBitmapBytes);
630 auto PaddingBytesAfterBitmapBytes = swap(Header.PaddingBytesAfterBitmapBytes);
631 auto NumUniformCounters = swap(Header.NumUniformCounters);
632 auto PaddingBytesAfterUniformCounters =
633 swap(Header.PaddingBytesAfterUniformCounters);
634 auto NamesSize = swap(Header.NamesSize);
635 auto VTableNameSize = swap(Header.VNamesSize);
636 auto NumVTables = swap(Header.NumVTables);
637 ValueKindLast = swap(Header.ValueKindLast);
638
639 auto DataSize = NumData * sizeof(RawInstrProf::ProfileData<IntPtrT>);
640 auto PaddingBytesAfterNames = getNumPaddingBytes(NamesSize);
641 auto PaddingBytesAfterVTableNames = getNumPaddingBytes(VTableNameSize);
642
643 auto VTableSectionSize =
644 NumVTables * sizeof(RawInstrProf::VTableProfileData<IntPtrT>);
645 auto PaddingBytesAfterVTableProfData = getNumPaddingBytes(VTableSectionSize);
646 auto UniformCountersSectionSize = NumUniformCounters * sizeof(uint64_t);
647
648 // Profile data starts after profile header and binary ids if exist.
649 ptrdiff_t DataOffset = sizeof(RawInstrProf::Header) + BinaryIdSize;
650 ptrdiff_t CountersOffset = DataOffset + DataSize + PaddingBytesBeforeCounters;
651 ptrdiff_t BitmapOffset =
652 CountersOffset + CountersSize + PaddingBytesAfterCounters;
653 ptrdiff_t UniformCountersOffset =
654 BitmapOffset + NumBitmapBytes + PaddingBytesAfterBitmapBytes;
655 ptrdiff_t NamesOffset = UniformCountersOffset + UniformCountersSectionSize +
656 PaddingBytesAfterUniformCounters;
657 ptrdiff_t VTableProfDataOffset =
658 NamesOffset + NamesSize + PaddingBytesAfterNames;
659 ptrdiff_t VTableNameOffset = VTableProfDataOffset + VTableSectionSize +
660 PaddingBytesAfterVTableProfData;
661 ptrdiff_t ValueDataOffset =
662 VTableNameOffset + VTableNameSize + PaddingBytesAfterVTableNames;
663
664 auto *Start = reinterpret_cast<const char *>(&Header);
665 if (Start + ValueDataOffset > DataBuffer->getBufferEnd())
666 // clang-format off
667 return error(
669 ("profile file size (" + Twine(DataBuffer->getBufferSize()) +
670 " bytes) smaller than expected (at least " + Twine(ValueDataOffset) +
671 " bytes: " +
672 Twine(sizeof(RawInstrProf::Header)) + "(Header) + " +
673 Twine(BinaryIdSize) + "(BinaryIdSize) + " +
674 Twine(DataSize) + "(DataSize) + " +
675 Twine(CountersSize) + "(CountersSize) + " +
676 Twine(NumBitmapBytes) + "(NumBitmapBytes) + " +
677 Twine(UniformCountersSectionSize) + "(UniformCountersSectionSize) + " +
678 Twine(NamesSize) + "(NamesSize) + " +
679 Twine(VTableSectionSize) + "(VTableSectionSize) + " +
680 Twine(VTableNameSize) + "(VTableNameSize) + " +
681 Twine(PaddingBytesBeforeCounters + PaddingBytesAfterCounters +
682 PaddingBytesAfterBitmapBytes + PaddingBytesAfterUniformCounters +
683 PaddingBytesAfterNames + PaddingBytesAfterVTableProfData +
684 PaddingBytesAfterVTableNames) +
685 "(Padding))")
686 .str());
687 // clang-format on
688
689 if (BIDFetcher) {
690 std::vector<object::BuildID> BinaryIDs;
691 if (Error E = readBinaryIds(BinaryIDs))
692 return E;
693 if (auto E = InstrProfCorrelator::get("", BIDFetcherCorrelatorKind,
694 BIDFetcher, BinaryIDs)
695 .moveInto(BIDFetcherCorrelator)) {
696 return E;
697 }
698 if (auto Err = BIDFetcherCorrelator->correlateProfileData(0))
699 return Err;
700 }
701
702 if (Correlator) {
703 // These sizes in the raw file are zero because we constructed them in the
704 // Correlator.
705 if (!(DataSize == 0 && NamesSize == 0 && CountersDelta == 0 &&
706 BitmapDelta == 0 && NamesDelta == 0))
708 Data = Correlator->getDataPointer();
709 DataEnd = Data + Correlator->getDataSize();
710 NamesStart = Correlator->getNamesPointer();
711 NamesEnd = NamesStart + Correlator->getNamesSize();
712 } else if (BIDFetcherCorrelator) {
713 InstrProfCorrelatorImpl<IntPtrT> *BIDFetcherCorrelatorImpl =
715 BIDFetcherCorrelator.get());
716 Data = BIDFetcherCorrelatorImpl->getDataPointer();
717 DataEnd = Data + BIDFetcherCorrelatorImpl->getDataSize();
718 NamesStart = BIDFetcherCorrelatorImpl->getNamesPointer();
719 NamesEnd = NamesStart + BIDFetcherCorrelatorImpl->getNamesSize();
720 } else {
721 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
722 Start + DataOffset);
723 DataEnd = Data + NumData;
724 VTableBegin =
725 reinterpret_cast<const RawInstrProf::VTableProfileData<IntPtrT> *>(
726 Start + VTableProfDataOffset);
727 VTableEnd = VTableBegin + NumVTables;
728 NamesStart = Start + NamesOffset;
729 NamesEnd = NamesStart + NamesSize;
730 VNamesStart = Start + VTableNameOffset;
731 VNamesEnd = VNamesStart + VTableNameSize;
732 }
733
734 CountersStart = Start + CountersOffset;
735 CountersEnd = CountersStart + CountersSize;
736 BitmapStart = Start + BitmapOffset;
737 BitmapEnd = BitmapStart + NumBitmapBytes;
738 UniformCountersStart = Start + UniformCountersOffset;
739 UniformCountersEnd = UniformCountersStart + UniformCountersSectionSize;
740 ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset);
741
742 std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>();
743 if (Error E = createSymtab(*NewSymtab))
744 return E;
745
746 Symtab = std::move(NewSymtab);
747 return success();
748}
749
750template <class IntPtrT>
751Error RawInstrProfReader<IntPtrT>::readName(NamedInstrProfRecord &Record) {
752 Record.Name = getName(Data->NameRef);
753 return success();
754}
755
756template <class IntPtrT>
757Error RawInstrProfReader<IntPtrT>::readFuncHash(NamedInstrProfRecord &Record) {
758 Record.Hash = swap(Data->FuncHash);
759 return success();
760}
761
762template <class IntPtrT>
763Error RawInstrProfReader<IntPtrT>::readRawCounts(
765 uint32_t NumCounters = swap(Data->NumCounters);
766 if (NumCounters == 0)
767 return error(instrprof_error::malformed, "number of counters is zero");
768
769 ptrdiff_t CounterBaseOffset = swap(Data->CounterPtr) - CountersDelta;
770 if (CounterBaseOffset < 0)
771 return error(
773 ("counter offset " + Twine(CounterBaseOffset) + " is negative").str());
774
775 if (CounterBaseOffset >= CountersEnd - CountersStart)
777 ("counter offset " + Twine(CounterBaseOffset) +
778 " is greater than the maximum counter offset " +
779 Twine(CountersEnd - CountersStart - 1))
780 .str());
781
782 uint64_t MaxNumCounters =
783 (CountersEnd - (CountersStart + CounterBaseOffset)) /
784 getCounterTypeSize();
785 if (NumCounters > MaxNumCounters)
787 ("number of counters " + Twine(NumCounters) +
788 " is greater than the maximum number of counters " +
789 Twine(MaxNumCounters))
790 .str());
791
792 Record.Counts.clear();
793 Record.Counts.reserve(NumCounters);
794 for (uint32_t I = 0; I < NumCounters; I++) {
795 const char *Ptr =
796 CountersStart + CounterBaseOffset + I * getCounterTypeSize();
797 if (I == 0 && hasTemporalProfile()) {
798 uint64_t TimestampValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));
799 if (TimestampValue != 0 &&
800 TimestampValue != std::numeric_limits<uint64_t>::max()) {
801 TemporalProfTimestamps.emplace_back(TimestampValue,
802 swap(Data->NameRef));
803 TemporalProfTraceStreamSize = 1;
804 }
805 if (hasSingleByteCoverage()) {
806 // In coverage mode, getCounterTypeSize() returns 1 byte but our
807 // timestamp field has size uint64_t. Increment I so that the next
808 // iteration of this for loop points to the byte after the timestamp
809 // field, i.e., I += 8.
810 I += 7;
811 }
812 continue;
813 }
814 if (hasSingleByteCoverage()) {
815 // A value of zero signifies the block is covered.
816 Record.Counts.push_back(*Ptr == 0 ? 1 : 0);
817 } else {
818 uint64_t CounterValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));
819 if (CounterValue > MaxCounterValue && Warn)
822
823 Record.Counts.push_back(CounterValue);
824 }
825 }
826
827 return success();
828}
829
830template <class IntPtrT>
831Error RawInstrProfReader<IntPtrT>::readRawBitmapBytes(InstrProfRecord &Record) {
832 uint32_t NumBitmapBytes = swap(Data->NumBitmapBytes);
833
834 Record.BitmapBytes.clear();
835 Record.BitmapBytes.reserve(NumBitmapBytes);
836
837 // It's possible MCDC is either not enabled or only used for some functions
838 // and not others. So if we record 0 bytes, just move on.
839 if (NumBitmapBytes == 0)
840 return success();
841
842 // BitmapDelta decreases as we advance to the next data record.
843 ptrdiff_t BitmapOffset = swap(Data->BitmapPtr) - BitmapDelta;
844 if (BitmapOffset < 0)
845 return error(
847 ("bitmap offset " + Twine(BitmapOffset) + " is negative").str());
848
849 if (BitmapOffset >= BitmapEnd - BitmapStart)
851 ("bitmap offset " + Twine(BitmapOffset) +
852 " is greater than the maximum bitmap offset " +
853 Twine(BitmapEnd - BitmapStart - 1))
854 .str());
855
856 uint64_t MaxNumBitmapBytes =
857 (BitmapEnd - (BitmapStart + BitmapOffset)) / sizeof(uint8_t);
858 if (NumBitmapBytes > MaxNumBitmapBytes)
860 ("number of bitmap bytes " + Twine(NumBitmapBytes) +
861 " is greater than the maximum number of bitmap bytes " +
862 Twine(MaxNumBitmapBytes))
863 .str());
864
865 for (uint32_t I = 0; I < NumBitmapBytes; I++) {
866 const char *Ptr = BitmapStart + BitmapOffset + I;
867 Record.BitmapBytes.push_back(swap(*Ptr));
868 }
869
870 return success();
871}
872
873template <class IntPtrT>
874Error RawInstrProfReader<IntPtrT>::readRawUniformCounters(
876 Record.UniformCounts.clear();
877
878 if (UniformCountersStart == UniformCountersEnd)
879 return success();
880
881 uint32_t NumCounters = swap(Data->NumCounters);
882
883 ptrdiff_t UniformCounterOffset =
884 swap(Data->UniformCounterPtr) - UniformCountersDelta;
885 if (UniformCounterOffset < 0)
887 ("uniform counter offset " + Twine(UniformCounterOffset) +
888 " is negative")
889 .str());
890
891 if (UniformCounterOffset >= UniformCountersEnd - UniformCountersStart)
893 ("uniform counter offset " + Twine(UniformCounterOffset) +
894 " is greater than the maximum uniform counter offset " +
895 Twine(UniformCountersEnd - UniformCountersStart - 1))
896 .str());
897
898 uint64_t MaxNumCounters =
899 (UniformCountersEnd - (UniformCountersStart + UniformCounterOffset)) /
900 sizeof(uint64_t);
901 if (NumCounters > MaxNumCounters)
903 ("number of uniform counters " + Twine(NumCounters) +
904 " is greater than the maximum number of uniform counters " +
905 Twine(MaxNumCounters))
906 .str());
907
908 Record.UniformCounts.reserve(NumCounters);
909 for (uint32_t I = 0; I < NumCounters; I++) {
910 const char *Ptr =
911 UniformCountersStart + UniformCounterOffset + I * sizeof(uint64_t);
912 uint64_t CounterValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));
913 Record.UniformCounts.push_back(CounterValue);
914 }
915
916 return success();
917}
918
919template <class IntPtrT>
920Error RawInstrProfReader<IntPtrT>::readValueProfilingData(
922 Record.clearValueData();
923 CurValueDataSize = 0;
924 // Need to match the logic in value profile dumper code in compiler-rt:
925 uint32_t NumValueKinds = 0;
926 for (uint32_t I = 0; I < IPVK_Last + 1; I++)
927 NumValueKinds += (Data->NumValueSites[I] != 0);
928
929 if (!NumValueKinds)
930 return success();
931
933 ValueProfData::getValueProfData(
934 ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(),
935 getDataEndianness());
936
937 if (Error E = VDataPtrOrErr.takeError())
938 return E;
939
940 // Note that besides deserialization, this also performs the conversion for
941 // indirect call targets. The function pointers from the raw profile are
942 // remapped into function name hashes.
943 VDataPtrOrErr.get()->deserializeTo(Record, Symtab.get());
944 CurValueDataSize = VDataPtrOrErr.get()->getSize();
945 return success();
946}
947
948template <class IntPtrT>
950 // Keep reading profiles that consist of only headers and no profile data and
951 // counters.
952 while (atEnd())
953 // At this point, ValueDataStart field points to the next header.
954 if (Error E = readNextHeader(getNextHeaderPos()))
955 return error(std::move(E));
956
957 // Read name and set it in Record.
958 if (Error E = readName(Record))
959 return error(std::move(E));
960
961 // Read FuncHash and set it in Record.
962 if (Error E = readFuncHash(Record))
963 return error(std::move(E));
964
965 Record.OffloadDeviceWaveSize = swap(Data->OffloadDeviceWaveSize);
966
967 // Read raw counts and set Record.
968 if (Error E = readRawCounts(Record))
969 return error(std::move(E));
970
971 // Read raw bitmap bytes and set Record.
972 if (Error E = readRawBitmapBytes(Record))
973 return error(std::move(E));
974
975 // Read raw uniform counters and set Record.
976 if (Error E = readRawUniformCounters(Record))
977 return error(std::move(E));
978
979 // Read value data and set Record.
980 if (Error E = readValueProfilingData(Record))
981 return error(std::move(E));
982
983 // Iterate.
984 advanceData();
985 return success();
986}
987
988template <class IntPtrT>
990 std::vector<llvm::object::BuildID> &BinaryIds) {
991 BinaryIds.insert(BinaryIds.begin(), this->BinaryIds.begin(),
992 this->BinaryIds.end());
993 return Error::success();
994}
995
996template <class IntPtrT>
998 if (!BinaryIds.empty())
999 printBinaryIdsInternal(OS, BinaryIds);
1000 return Error::success();
1001}
1002
1003namespace llvm {
1004
1005template class RawInstrProfReader<uint32_t>;
1006template class RawInstrProfReader<uint64_t>;
1007
1008} // end namespace llvm
1009
1014
1017
1019 const unsigned char *&D, const unsigned char *const End) {
1021 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
1022
1023 if (VDataPtrOrErr.takeError())
1024 return false;
1025
1026 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);
1027 D += VDataPtrOrErr.get()->TotalSize;
1028
1029 return true;
1030}
1031
1033 offset_type N) {
1034 using namespace support;
1035
1036 // Check if the data is corrupt. If so, don't try to read it.
1037 if (N % sizeof(uint64_t))
1038 return data_type();
1039
1040 DataBuffer.clear();
1041 std::vector<uint64_t> CounterBuffer;
1042 std::vector<uint8_t> BitmapByteBuffer;
1043 std::vector<uint8_t> UniformityBitsBuffer;
1044
1045 const unsigned char *End = D + N;
1046 while (D < End) {
1047 // Read hash.
1048 if (D + sizeof(uint64_t) > End)
1049 return data_type();
1051
1052 // Initialize number of counters for GET_VERSION(FormatVersion) == 1.
1053 uint64_t CountsSize = N / sizeof(uint64_t) - 1;
1054 // If format version is different then read the number of counters.
1056 if (D + sizeof(uint64_t) > End)
1057 return data_type();
1059 }
1060 // Read counter values.
1061 if (D + CountsSize * sizeof(uint64_t) > End)
1062 return data_type();
1063
1064 CounterBuffer.clear();
1065 CounterBuffer.reserve(CountsSize);
1066 for (uint64_t J = 0; J < CountsSize; ++J)
1067 CounterBuffer.push_back(
1069
1070 // Read bitmap bytes for GET_VERSION(FormatVersion) > 10.
1072 uint64_t BitmapBytes = 0;
1073 if (D + sizeof(uint64_t) > End)
1074 return data_type();
1076 BitmapByteBuffer.clear();
1077 BitmapByteBuffer.reserve(BitmapBytes);
1078
1079 if (GET_VERSION(FormatVersion) >=
1081 // Version 14+: bitmap bytes stored as uint8_t with padding.
1082 uint64_t PaddedSize = alignTo(BitmapBytes, sizeof(uint64_t));
1083 if (D + PaddedSize > End)
1084 return data_type();
1085 for (uint64_t J = 0; J < BitmapBytes; ++J)
1086 BitmapByteBuffer.push_back(
1088 for (uint64_t J = BitmapBytes; J < PaddedSize; ++J)
1090
1091 // Read uniformity bits (AMDGPU offload profiling).
1092 uint64_t UniformityBitsSize = 0;
1093 if (D + sizeof(uint64_t) > End)
1094 return data_type();
1095 UniformityBitsSize =
1097 uint64_t PaddedUniformitySize =
1098 alignTo(UniformityBitsSize, sizeof(uint64_t));
1099 if (D + PaddedUniformitySize > End)
1100 return data_type();
1101 UniformityBitsBuffer.clear();
1102 UniformityBitsBuffer.reserve(UniformityBitsSize);
1103 for (uint64_t J = 0; J < UniformityBitsSize; ++J)
1104 UniformityBitsBuffer.push_back(
1106 for (uint64_t J = UniformityBitsSize; J < PaddedUniformitySize; ++J)
1108 } else {
1109 // Version 11-13: each bitmap byte stored as a uint64_t.
1110 if (D + BitmapBytes * sizeof(uint64_t) > End)
1111 return data_type();
1112 for (uint64_t J = 0; J < BitmapBytes; ++J)
1113 BitmapByteBuffer.push_back(static_cast<uint8_t>(
1115 }
1116 }
1117
1118 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer),
1119 std::move(BitmapByteBuffer),
1120 std::move(UniformityBitsBuffer));
1121
1122 // Read value profiling data.
1124 !readValueProfilingData(D, End)) {
1125 DataBuffer.clear();
1126 return data_type();
1127 }
1128 }
1129 return DataBuffer;
1130}
1131
1132template <typename HashTableImpl>
1135 auto Iter = HashTable->find(FuncName);
1136 if (Iter == HashTable->end())
1138
1139 Data = (*Iter);
1140 if (Data.empty())
1142 "profile data is empty");
1143
1144 return Error::success();
1145}
1146
1147template <typename HashTableImpl>
1150 if (atEnd())
1152
1153 Data = *RecordIterator;
1154
1155 if (Data.empty())
1157 "profile data is empty");
1158
1159 return Error::success();
1160}
1161
1162template <typename HashTableImpl>
1164 const unsigned char *Buckets, const unsigned char *const Payload,
1165 const unsigned char *const Base, IndexedInstrProf::HashT HashType,
1166 uint64_t Version) {
1167 FormatVersion = Version;
1168 HashTable.reset(HashTableImpl::Create(
1169 Buckets, Payload, Base,
1170 typename HashTableImpl::InfoType(HashType, Version)));
1171 RecordIterator = HashTable->data_begin();
1172}
1173
1174template <typename HashTableImpl>
1178
1179namespace {
1180/// A remapper that does not apply any remappings.
1181class InstrProfReaderNullRemapper : public InstrProfReaderRemapper {
1182 InstrProfReaderIndexBase &Underlying;
1183
1184public:
1185 InstrProfReaderNullRemapper(InstrProfReaderIndexBase &Underlying)
1186 : Underlying(Underlying) {}
1187
1188 Error getRecords(StringRef FuncName,
1190 return Underlying.getRecords(FuncName, Data);
1191 }
1192};
1193} // namespace
1194
1195/// A remapper that applies remappings based on a symbol remapping file.
1196template <typename HashTableImpl>
1198 : public InstrProfReaderRemapper {
1199public:
1201 std::unique_ptr<MemoryBuffer> RemapBuffer,
1203 : RemapBuffer(std::move(RemapBuffer)), Underlying(Underlying) {
1204 }
1205
1206 /// Extract the original function name from a PGO function name.
1208 // We can have multiple pieces separated by kGlobalIdentifierDelimiter (
1209 // semicolon now and colon in older profiles); there can be pieces both
1210 // before and after the mangled name. Find the first part that starts with
1211 // '_Z'; we'll assume that's the mangled name we want.
1212 std::pair<StringRef, StringRef> Parts = {StringRef(), Name};
1213 while (true) {
1214 Parts = Parts.second.split(GlobalIdentifierDelimiter);
1215 if (Parts.first.starts_with("_Z"))
1216 return Parts.first;
1217 if (Parts.second.empty())
1218 return Name;
1219 }
1220 }
1221
1222 /// Given a mangled name extracted from a PGO function name, and a new
1223 /// form for that mangled name, reconstitute the name.
1224 static void reconstituteName(StringRef OrigName, StringRef ExtractedName,
1225 StringRef Replacement,
1226 SmallVectorImpl<char> &Out) {
1227 Out.reserve(OrigName.size() + Replacement.size() - ExtractedName.size());
1228 Out.insert(Out.end(), OrigName.begin(), ExtractedName.begin());
1229 llvm::append_range(Out, Replacement);
1230 Out.insert(Out.end(), ExtractedName.end(), OrigName.end());
1231 }
1232
1234 if (Error E = Remappings.read(*RemapBuffer))
1235 return E;
1236 for (StringRef Name : Underlying.HashTable->keys()) {
1237 StringRef RealName = extractName(Name);
1238 if (auto Key = Remappings.insert(RealName)) {
1239 // FIXME: We could theoretically map the same equivalence class to
1240 // multiple names in the profile data. If that happens, we should
1241 // return NamedInstrProfRecords from all of them.
1242 MappedNames.insert({Key, RealName});
1243 }
1244 }
1245 return Error::success();
1246 }
1247
1250 StringRef RealName = extractName(FuncName);
1251 if (auto Key = Remappings.lookup(RealName)) {
1252 StringRef Remapped = MappedNames.lookup(Key);
1253 if (!Remapped.empty()) {
1254 if (RealName.begin() == FuncName.begin() &&
1255 RealName.end() == FuncName.end())
1256 FuncName = Remapped;
1257 else {
1258 // Try rebuilding the name from the given remapping.
1259 SmallString<256> Reconstituted;
1260 reconstituteName(FuncName, RealName, Remapped, Reconstituted);
1261 Error E = Underlying.getRecords(Reconstituted, Data);
1262 if (!E)
1263 return E;
1264
1265 // If we failed because the name doesn't exist, fall back to asking
1266 // about the original name.
1267 if (Error Unhandled = handleErrors(
1268 std::move(E), [](std::unique_ptr<InstrProfError> Err) {
1269 return Err->get() == instrprof_error::unknown_function
1270 ? Error::success()
1271 : Error(std::move(Err));
1272 }))
1273 return Unhandled;
1274 }
1275 }
1276 }
1277 return Underlying.getRecords(FuncName, Data);
1278 }
1279
1280private:
1281 /// The memory buffer containing the remapping configuration. Remappings
1282 /// holds pointers into this buffer.
1283 std::unique_ptr<MemoryBuffer> RemapBuffer;
1284
1285 /// The mangling remapper.
1286 SymbolRemappingReader Remappings;
1287
1288 /// Mapping from mangled name keys to the name used for the key in the
1289 /// profile data.
1290 /// FIXME: Can we store a location within the on-disk hash table instead of
1291 /// redoing lookup?
1293
1294 /// The real profile data reader.
1296};
1297
1299 using namespace support;
1300
1301 if (DataBuffer.getBufferSize() < 8)
1302 return false;
1303 uint64_t Magic = endian::read<uint64_t, aligned>(DataBuffer.getBufferStart(),
1305 // Verify that it's magical.
1306 return Magic == IndexedInstrProf::Magic;
1307}
1308
1309const unsigned char *
1310IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version,
1311 const unsigned char *Cur, bool UseCS) {
1312 using namespace IndexedInstrProf;
1313 using namespace support;
1314
1316 const IndexedInstrProf::Summary *SummaryInLE =
1317 reinterpret_cast<const IndexedInstrProf::Summary *>(Cur);
1318 uint64_t NFields = endian::byte_swap<uint64_t>(
1320 uint64_t NEntries = endian::byte_swap<uint64_t>(
1322 uint32_t SummarySize =
1323 IndexedInstrProf::Summary::getSize(NFields, NEntries);
1324 std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
1325 IndexedInstrProf::allocSummary(SummarySize);
1326
1327 const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE);
1328 uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get());
1329 for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
1331
1332 SummaryEntryVector DetailedSummary;
1333 for (unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
1334 const IndexedInstrProf::Summary::Entry &Ent = SummaryData->getEntry(I);
1335 DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,
1336 Ent.NumBlocks);
1337 }
1338 std::unique_ptr<llvm::ProfileSummary> &Summary =
1339 UseCS ? this->CS_Summary : this->Summary;
1340
1341 // initialize InstrProfSummary using the SummaryData from disk.
1342 Summary = std::make_unique<ProfileSummary>(
1344 DetailedSummary, SummaryData->get(Summary::TotalBlockCount),
1345 SummaryData->get(Summary::MaxBlockCount),
1346 SummaryData->get(Summary::MaxInternalBlockCount),
1347 SummaryData->get(Summary::MaxFunctionCount),
1348 SummaryData->get(Summary::TotalNumBlocks),
1349 SummaryData->get(Summary::TotalNumFunctions));
1350 return Cur + SummarySize;
1351 } else {
1352 // The older versions do not support a profile summary. This just computes
1353 // an empty summary, which will not result in accurate hot/cold detection.
1354 // We would need to call addRecord for all NamedInstrProfRecords to get the
1355 // correct summary. However, this version is old (prior to early 2016) and
1356 // has not been supporting an accurate summary for several years.
1357 InstrProfSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1358 Summary = Builder.getSummary();
1359 return Cur;
1360 }
1361}
1362
1364 using namespace support;
1365
1366 const unsigned char *Start =
1367 (const unsigned char *)DataBuffer->getBufferStart();
1368 const unsigned char *Cur = Start;
1369 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
1371
1372 auto HeaderOr = IndexedInstrProf::Header::readFromBuffer(Start);
1373 if (!HeaderOr)
1374 return HeaderOr.takeError();
1375
1376 const IndexedInstrProf::Header *Header = &HeaderOr.get();
1377 Cur += Header->size();
1378
1379 Cur = readSummary((IndexedInstrProf::ProfVersion)Header->Version, Cur,
1380 /* UseCS */ false);
1381 if (Header->Version & VARIANT_MASK_CSIR_PROF)
1382 Cur = readSummary((IndexedInstrProf::ProfVersion)Header->Version, Cur,
1383 /* UseCS */ true);
1384 // Read the hash type and start offset.
1385 IndexedInstrProf::HashT HashType =
1386 static_cast<IndexedInstrProf::HashT>(Header->HashType);
1387 if (HashType > IndexedInstrProf::HashT::Last)
1389
1390 // The hash table with profile counts comes next.
1391 auto IndexPtr = std::make_unique<InstrProfReaderIndex<OnDiskHashTableImplV3>>(
1392 Start + Header->HashOffset, Cur, Start, HashType, Header->Version);
1393
1394 // The MemProfOffset field in the header is only valid when the format
1395 // version is higher than 8 (when it was introduced).
1396 if (Header->getIndexedProfileVersion() >= 8 &&
1397 Header->Version & VARIANT_MASK_MEMPROF) {
1398 if (Error E = MemProfReader.deserialize(Start, Header->MemProfOffset))
1399 return E;
1400 }
1401
1402 // BinaryIdOffset field in the header is only valid when the format version
1403 // is higher than 9 (when it was introduced).
1404 if (Header->getIndexedProfileVersion() >= 9) {
1405 const unsigned char *Ptr = Start + Header->BinaryIdOffset;
1406 // Read binary ids size.
1407 uint64_t BinaryIdsSize =
1409 if (BinaryIdsSize % sizeof(uint64_t))
1410 return error(
1412 ("BinaryIdSize (" + Twine(BinaryIdsSize) + ") is not a multiple of 8")
1413 .str());
1414 // Set the binary ids start.
1415 BinaryIdsBuffer = ArrayRef<uint8_t>(Ptr, BinaryIdsSize);
1416 if (Ptr > (const unsigned char *)DataBuffer->getBufferEnd())
1418 "corrupted binary ids");
1419 }
1420
1421 if (Header->getIndexedProfileVersion() >= 12) {
1422 const unsigned char *Ptr = Start + Header->VTableNamesOffset;
1423
1424 uint64_t CompressedVTableNamesLen =
1426
1427 // Writer first writes the length of compressed string, and then the actual
1428 // content.
1429 const char *VTableNamePtr = (const char *)Ptr;
1430 if (VTableNamePtr > DataBuffer->getBufferEnd())
1432
1433 VTableName = StringRef(VTableNamePtr, CompressedVTableNamesLen);
1434 }
1435
1436 if (Header->getIndexedProfileVersion() >= 10 &&
1437 Header->Version & VARIANT_MASK_TEMPORAL_PROF) {
1438 const unsigned char *Ptr = Start + Header->TemporalProfTracesOffset;
1439 const auto *PtrEnd = (const unsigned char *)DataBuffer->getBufferEnd();
1440 // Expect at least two 64 bit fields: NumTraces, and TraceStreamSize
1441 if (Ptr + 2 * sizeof(uint64_t) > PtrEnd)
1443 const uint64_t NumTraces =
1447 for (unsigned i = 0; i < NumTraces; i++) {
1448 // Expect at least two 64 bit fields: Weight and NumFunctions
1449 if (Ptr + 2 * sizeof(uint64_t) > PtrEnd)
1452 Trace.Weight =
1454 const uint64_t NumFunctions =
1456 // Expect at least NumFunctions 64 bit fields
1457 if (Ptr + NumFunctions * sizeof(uint64_t) > PtrEnd)
1459 for (unsigned j = 0; j < NumFunctions; j++) {
1460 const uint64_t NameRef =
1462 Trace.FunctionNameRefs.push_back(NameRef);
1463 }
1464 TemporalProfTraces.push_back(std::move(Trace));
1465 }
1466 }
1467
1468 // Load the remapping table now if requested.
1469 if (RemappingBuffer) {
1470 Remapper =
1471 std::make_unique<InstrProfReaderItaniumRemapper<OnDiskHashTableImplV3>>(
1472 std::move(RemappingBuffer), *IndexPtr);
1473 if (Error E = Remapper->populateRemappings())
1474 return E;
1475 } else {
1476 Remapper = std::make_unique<InstrProfReaderNullRemapper>(*IndexPtr);
1477 }
1478 Index = std::move(IndexPtr);
1479
1480 return success();
1481}
1482
1484 if (Symtab)
1485 return *Symtab;
1486
1487 auto NewSymtab = std::make_unique<InstrProfSymtab>();
1488
1489 if (Error E = NewSymtab->initVTableNamesFromCompressedStrings(VTableName)) {
1490 auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
1491 consumeError(error(ErrCode, Msg));
1492 }
1493
1494 // finalizeSymtab is called inside populateSymtab.
1495 if (Error E = Index->populateSymtab(*NewSymtab)) {
1496 auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
1497 consumeError(error(ErrCode, Msg));
1498 }
1499
1500 Symtab = std::move(NewSymtab);
1501 return *Symtab;
1502}
1503
1505 StringRef FuncName, uint64_t FuncHash, StringRef DeprecatedFuncName,
1506 uint64_t *MismatchedFuncSum) {
1508 uint64_t FuncSum = 0;
1509 auto Err = Remapper->getRecords(FuncName, Data);
1510 if (Err) {
1511 // If we don't find FuncName, try DeprecatedFuncName to handle profiles
1512 // built by older compilers.
1513 auto Err2 =
1514 handleErrors(std::move(Err), [&](const InstrProfError &IE) -> Error {
1515 if (IE.get() != instrprof_error::unknown_function)
1516 return make_error<InstrProfError>(IE);
1517 if (auto Err = Remapper->getRecords(DeprecatedFuncName, Data))
1518 return Err;
1519 return Error::success();
1520 });
1521 if (Err2)
1522 return std::move(Err2);
1523 }
1524 // Found it. Look for counters with the right hash.
1525
1526 // A flag to indicate if the records are from the same type
1527 // of profile (i.e cs vs nocs).
1528 bool CSBitMatch = false;
1529 auto getFuncSum = [](ArrayRef<uint64_t> Counts) {
1530 uint64_t ValueSum = 0;
1531 for (uint64_t CountValue : Counts) {
1532 if (CountValue == (uint64_t)-1)
1533 continue;
1534 // Handle overflow -- if that happens, return max.
1535 if (std::numeric_limits<uint64_t>::max() - CountValue <= ValueSum)
1536 return std::numeric_limits<uint64_t>::max();
1537 ValueSum += CountValue;
1538 }
1539 return ValueSum;
1540 };
1541
1542 for (const NamedInstrProfRecord &I : Data) {
1543 // Check for a match and fill the vector if there is one.
1544 if (I.Hash == FuncHash)
1545 return std::move(I);
1548 CSBitMatch = true;
1549 if (MismatchedFuncSum == nullptr)
1550 continue;
1551 FuncSum = std::max(FuncSum, getFuncSum(I.Counts));
1552 }
1553 }
1554 if (CSBitMatch) {
1555 if (MismatchedFuncSum != nullptr)
1556 *MismatchedFuncSum = FuncSum;
1558 }
1560}
1561
1564 MemProfFrameHashTable &MemProfFrameTable,
1565 MemProfCallStackHashTable &MemProfCallStackTable) {
1567 MemProfFrameTable);
1568
1570 MemProfCallStackTable, FrameIdConv);
1571
1572 memprof::MemProfRecord Record = IndexedRecord.toMemProfRecord(CSIdConv);
1573
1574 // Check that all call stack ids were successfully converted to call stacks.
1575 if (CSIdConv.LastUnmappedId) {
1578 "memprof call stack not found for call stack id " +
1579 Twine(*CSIdConv.LastUnmappedId));
1580 }
1581
1582 // Check that all frame ids were successfully converted to frames.
1583 if (FrameIdConv.LastUnmappedId) {
1585 "memprof frame not found for frame id " +
1586 Twine(*FrameIdConv.LastUnmappedId));
1587 }
1588
1589 return Record;
1590}
1591
1593IndexedMemProfReader::getMemProfRecord(const uint64_t FuncNameHash) const {
1594 // TODO: Add memprof specific errors.
1595 if (MemProfRecordTable == nullptr)
1597 "no memprof data available in profile");
1598 auto Iter = MemProfRecordTable->find(FuncNameHash);
1599 if (Iter == MemProfRecordTable->end())
1602 "memprof record not found for function hash " + Twine(FuncNameHash));
1603
1604 const memprof::IndexedMemProfRecord &IndexedRecord = *Iter;
1605 switch (Version) {
1606 case memprof::Version2:
1607 assert(MemProfFrameTable && "MemProfFrameTable must be available");
1608 assert(MemProfCallStackTable && "MemProfCallStackTable must be available");
1609 return getMemProfRecordV2(IndexedRecord, *MemProfFrameTable,
1610 *MemProfCallStackTable);
1611 // Combine V3 and V4 cases as the record conversion logic is the same.
1612 case memprof::Version3:
1613 case memprof::Version4:
1614 assert(!MemProfFrameTable && "MemProfFrameTable must not be available");
1615 assert(!MemProfCallStackTable &&
1616 "MemProfCallStackTable must not be available");
1617 assert(FrameBase && "FrameBase must be available");
1618 assert(CallStackBase && "CallStackBase must be available");
1619 {
1620 memprof::LinearFrameIdConverter FrameIdConv(FrameBase);
1621 memprof::LinearCallStackIdConverter CSIdConv(CallStackBase, FrameIdConv);
1622 memprof::MemProfRecord Record = IndexedRecord.toMemProfRecord(CSIdConv);
1623 return Record;
1624 }
1625 }
1626
1629 formatv("MemProf version {} not supported; "
1630 "requires version between {} and {}, inclusive",
1633}
1634
1637 assert(MemProfRecordTable);
1638 assert(Version == memprof::Version3 || Version == memprof::Version4);
1639
1640 memprof::LinearFrameIdConverter FrameIdConv(FrameBase);
1641 memprof::CallerCalleePairExtractor Extractor(CallStackBase, FrameIdConv,
1642 RadixTreeSize);
1643
1644 // The set of linear call stack IDs that we need to traverse from. We expect
1645 // the set to be dense, so we use a BitVector.
1646 BitVector Worklist(RadixTreeSize);
1647
1648 // Collect the set of linear call stack IDs. Since we expect a lot of
1649 // duplicates, we first collect them in the form of a bit vector before
1650 // processing them.
1651 for (const memprof::IndexedMemProfRecord &IndexedRecord :
1652 MemProfRecordTable->data()) {
1653 for (const memprof::IndexedAllocationInfo &IndexedAI :
1654 IndexedRecord.AllocSites)
1655 Worklist.set(IndexedAI.CSId);
1656 }
1657
1658 // Collect caller-callee pairs for each linear call stack ID in Worklist.
1659 for (unsigned CS : Worklist.set_bits())
1660 Extractor(CS);
1661
1663 std::move(Extractor.CallerCalleePairs);
1664
1665 // Sort each call list by the source location.
1666 for (auto &[CallerGUID, CallList] : Pairs) {
1667 llvm::sort(CallList);
1668 CallList.erase(llvm::unique(CallList), CallList.end());
1669 }
1670
1671 return Pairs;
1672}
1673
1675 memprof::AllMemProfData AllMemProfData;
1676 AllMemProfData.HeapProfileRecords.reserve(
1677 MemProfRecordTable->getNumEntries());
1678 for (uint64_t Key : MemProfRecordTable->keys()) {
1679 auto Record = getMemProfRecord(Key);
1680 if (Record.takeError())
1681 continue;
1683 Pair.GUID = Key;
1684 Pair.Record = std::move(*Record);
1685 AllMemProfData.HeapProfileRecords.push_back(std::move(Pair));
1686 }
1687 // Populate the data access profiles for yaml output.
1688 if (DataAccessProfileData != nullptr) {
1689 AllMemProfData.YamlifiedDataAccessProfiles.Records.reserve(
1690 DataAccessProfileData->getRecords().size());
1691 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdSymbols.reserve(
1692 DataAccessProfileData->getKnownColdSymbols().size());
1693 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdStrHashes.reserve(
1694 DataAccessProfileData->getKnownColdHashes().size());
1695 for (const auto &[SymHandleRef, RecordRef] :
1696 DataAccessProfileData->getRecords())
1697 AllMemProfData.YamlifiedDataAccessProfiles.Records.push_back(
1698 memprof::DataAccessProfRecord(SymHandleRef, RecordRef.AccessCount,
1699 RecordRef.Locations));
1700 for (StringRef ColdSymbol : DataAccessProfileData->getKnownColdSymbols())
1701 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdSymbols.push_back(
1702 ColdSymbol.str());
1703 for (uint64_t Hash : DataAccessProfileData->getKnownColdHashes())
1704 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdStrHashes.push_back(
1705 Hash);
1709 return lhs.AccessCount > rhs.AccessCount;
1710 });
1713 [](const std::string &lhs, const std::string &rhs) {
1714 return lhs < rhs;
1715 });
1718 [](const uint64_t &lhs, const uint64_t &rhs) { return lhs < rhs; });
1719 }
1720 return AllMemProfData;
1721}
1722
1724 uint64_t FuncHash,
1725 std::vector<uint64_t> &Counts) {
1726 auto Record = getInstrProfRecord(FuncName, FuncHash);
1727 if (Error E = Record.takeError())
1728 return error(std::move(E));
1729
1730 Counts = Record.get().Counts;
1731 return success();
1732}
1733
1735 uint64_t FuncHash,
1736 BitVector &Bitmap) {
1737 auto Record = getInstrProfRecord(FuncName, FuncHash);
1738 if (Error E = Record.takeError())
1739 return error(std::move(E));
1740
1741 const auto &BitmapBytes = Record.get().BitmapBytes;
1742 size_t I = 0, E = BitmapBytes.size();
1743 Bitmap.resize(E * CHAR_BIT);
1745 [&](auto X) {
1746 using XTy = decltype(X);
1747 alignas(XTy) uint8_t W[sizeof(X)];
1748 size_t N = std::min(E - I, sizeof(W));
1749 std::memset(W, 0, sizeof(W));
1750 std::memcpy(W, &BitmapBytes[I], N);
1751 I += N;
1754 },
1755 Bitmap, Bitmap);
1756 assert(I == E);
1757
1758 return success();
1759}
1760
1763
1764 Error E = Index->getRecords(Data);
1765 if (E)
1766 return error(std::move(E));
1767
1768 Record = Data[RecordIndex++];
1769 if (RecordIndex >= Data.size()) {
1770 Index->advanceToNextKey();
1771 RecordIndex = 0;
1772 }
1773 return success();
1774}
1775
1777 std::vector<llvm::object::BuildID> &BinaryIds) {
1778 return readBinaryIdsInternal(*DataBuffer, BinaryIdsBuffer, BinaryIds,
1780}
1781
1783 std::vector<llvm::object::BuildID> BinaryIds;
1784 if (Error E = readBinaryIds(BinaryIds))
1785 return E;
1786 printBinaryIdsInternal(OS, BinaryIds);
1787 return Error::success();
1788}
1789
1791 uint64_t NumFuncs = 0;
1792 for (const auto &Func : *this) {
1793 if (isIRLevelProfile()) {
1794 bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
1795 if (FuncIsCS != IsCS)
1796 continue;
1797 }
1798 Func.accumulateCounts(Sum);
1799 ++NumFuncs;
1800 }
1801 Sum.NumEntries = NumFuncs;
1802}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
Provides ErrorOr<T> smart pointer.
InstrProfLookupTrait::offset_type offset_type
static Error initializeReader(InstrProfReader &Reader)
#define READ_NUM(Str, Dst)
#define CHECK_LINE_END(Line)
static Error readBinaryIdsInternal(const MemoryBuffer &DataBuffer, ArrayRef< uint8_t > BinaryIdsBuffer, std::vector< llvm::object::BuildID > &BinaryIds, const llvm::endianness Endian)
Read a list of binary ids from a profile that consist of a.
#define VP_READ_ADVANCE(Val)
InstrProfLookupTrait::data_type data_type
static InstrProfKind getProfileKindFromVersion(uint64_t Version)
static Expected< memprof::MemProfRecord > getMemProfRecordV2(const memprof::IndexedMemProfRecord &IndexedRecord, MemProfFrameHashTable &MemProfFrameTable, MemProfCallStackHashTable &MemProfCallStackTable)
static void printBinaryIdsInternal(raw_ostream &OS, ArrayRef< llvm::object::BuildID > BinaryIds)
#define GET_VERSION(V)
#define VARIANT_MASK_CSIR_PROF
#define VARIANT_MASK_MEMPROF
#define VARIANT_MASK_TEMPORAL_PROF
#define VARIANT_MASK_IR_PROF
#define VARIANT_MASK_BYTE_COVERAGE
#define VARIANT_MASK_INSTR_ENTRY
#define VARIANT_MASK_FUNCTION_ENTRY_ONLY
#define VARIANT_MASK_INSTR_LOOP_ENTRIES
#define I(x, y, z)
Definition MD5.cpp:57
static constexpr StringLiteral Filename
static StringRef getName(Value *V)
const char * Msg
This file contains some functions that are useful when dealing with strings.
#define error(X)
Defines the virtual file system interface vfs::FileSystem.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
static BitVector & apply(F &&f, BitVector &Out, BitVector const &Arg, ArgTys const &...Args)
Definition BitVector.h:594
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
Reader for the indexed binary instrprof format.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const Twine &RemappingPath="")
Factory method to create an indexed reader.
Error readHeader() override
Read the file header.
Error printBinaryIds(raw_ostream &OS) override
Print binary ids.
Error getFunctionBitmap(StringRef FuncName, uint64_t FuncHash, BitVector &Bitmap)
Fill Bitmap with the profile data for the given function name.
InstrProfSymtab & getSymtab() override
Return the PGO symtab.
static bool hasFormat(const MemoryBuffer &DataBuffer)
Return true if the given buffer is in an indexed instrprof format.
Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash, std::vector< uint64_t > &Counts)
Fill Counts with the profile data for the given function name.
Expected< NamedInstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash, StringRef DeprecatedFuncName="", uint64_t *MismatchedFuncSum=nullptr)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
Error readBinaryIds(std::vector< llvm::object::BuildID > &BinaryIds) override
Read a list of binary ids.
LLVM_ABI memprof::AllMemProfData getAllMemProfData() const
LLVM_ABI Expected< memprof::MemProfRecord > getMemProfRecord(const uint64_t FuncNameHash) const
LLVM_ABI DenseMap< uint64_t, SmallVector< memprof::CallEdgeTy, 0 > > getMemProfCallerCalleePairs() const
InstrProfCorrelatorImpl - A child of InstrProfCorrelator with a template pointer type so that the Pro...
const RawInstrProf::ProfileData< IntPtrT > * getDataPointer() const
Return a pointer to the underlying ProfileData vector that this class constructs.
size_t getDataSize() const
Return the number of ProfileData elements.
InstrProfCorrelator - A base class used to create raw instrumentation data to their functions.
const char * getNamesPointer() const
Return a pointer to the names string that this class constructs.
ProfCorrelatorKind
Indicate if we should use the debug info or profile metadata sections to correlate.
LLVM_ABI std::optional< size_t > getDataSize() const
Return the number of ProfileData elements.
static LLVM_ABI llvm::Expected< std::unique_ptr< InstrProfCorrelator > > get(StringRef Filename, ProfCorrelatorKind FileKind, const object::BuildIDFetcher *BIDFetcher=nullptr, const ArrayRef< llvm::object::BuildID > BIs={})
size_t getNamesSize() const
Return the number of bytes in the names string.
static std::pair< instrprof_error, std::string > take(Error E)
Consume an Error and return the raw enum value contained within it, and the optional error message.
Definition InstrProf.h:484
LLVM_ABI data_type ReadData(StringRef K, const unsigned char *D, offset_type N)
LLVM_ABI bool readValueProfilingData(const unsigned char *&D, const unsigned char *const End)
LLVM_ABI hash_value_type ComputeHash(StringRef K)
ArrayRef< NamedInstrProfRecord > data_type
InstrProfKind getProfileKind() const override
Error getRecords(ArrayRef< NamedInstrProfRecord > &Data) override
InstrProfReaderIndex(const unsigned char *Buckets, const unsigned char *const Payload, const unsigned char *const Base, IndexedInstrProf::HashT HashType, uint64_t Version)
bool atEnd() const override
A remapper that applies remappings based on a symbol remapping file.
static StringRef extractName(StringRef Name)
Extract the original function name from a PGO function name.
InstrProfReaderItaniumRemapper(std::unique_ptr< MemoryBuffer > RemapBuffer, InstrProfReaderIndex< HashTableImpl > &Underlying)
static void reconstituteName(StringRef OrigName, StringRef ExtractedName, StringRef Replacement, SmallVectorImpl< char > &Out)
Given a mangled name extracted from a PGO function name, and a new form for that mangled name,...
Error getRecords(StringRef FuncName, ArrayRef< NamedInstrProfRecord > &Data) override
Name matcher supporting fuzzy matching of symbol names to names in profiles.
Base class and interface for reading profiling data of any known instrprof format.
std::unique_ptr< InstrProfSymtab > Symtab
Error success()
Clear the current error and return a successful one.
SmallVector< TemporalProfTraceTy > TemporalProfTraces
A list of temporal profile traces.
uint64_t TemporalProfTraceStreamSize
The total number of temporal profile traces seen.
virtual bool isIRLevelProfile() const =0
virtual Error readHeader()=0
Read the header. Required before reading first record.
LLVM_ABI void accumulateCounts(CountSumOrPercent &Sum, bool IsCS)
Compute the sum of counts and return in Sum.
static LLVM_ABI Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const InstrProfCorrelator *Correlator=nullptr, const object::BuildIDFetcher *BIDFetcher=nullptr, const InstrProfCorrelator::ProfCorrelatorKind BIDFetcherCorrelatorKind=InstrProfCorrelator::ProfCorrelatorKind::NONE, std::function< void(Error)> Warn=nullptr)
Factory method to create an appropriately typed reader for the given instrprof file.
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition InstrProf.h:519
static bool isExternalSymbol(const StringRef &Symbol)
True if Symbol is the value used to represent external symbols.
Definition InstrProf.h:722
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
Definition InstrProf.h:689
LLVM_ABI Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
void mapVTableAddress(uint64_t StartAddr, uint64_t EndAddr, uint64_t MD5Val)
Map the address range (i.e., [start_address, end_address)) of a variable to its names' MD5 hash.
Definition InstrProf.h:696
This interface provides simple read-only access to a block of memory, and provides simple methods for...
size_t getBufferSize() const
const char * getBufferEnd() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getSTDIN()
Read all of stdin into a file buffer, and return it.
const char * getBufferStart() const
static LLVM_ABI const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
Reader for the raw instrprof binary format from runtime.
Error readHeader() override
Read the header. Required before reading first record.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
Error printBinaryIds(raw_ostream &OS) override
Print binary ids.
static bool hasFormat(const MemoryBuffer &DataBuffer)
InstrProfKind getProfileKind() const override
Returns a BitsetEnum describing the attributes of the raw instr profile.
Error readBinaryIds(std::vector< llvm::object::BuildID > &BinaryIds) override
Read a list of binary ids.
SmallVector< TemporalProfTraceTy > & getTemporalProfTraces(std::optional< uint64_t > Weight={}) override
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
iterator begin() const
Definition StringRef.h:114
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
char front() const
Get the first character in the string.
Definition StringRef.h:147
iterator end() const
Definition StringRef.h:116
Reader for symbol remapping files.
Reader for the simple text based instrprof format.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if the given buffer is in text instrprof format.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
Error readHeader() override
Read the header.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
BuildIDFetcher searches local cache directories for debug info.
Definition BuildID.h:41
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
The virtual file system interface.
std::unique_ptr< Summary > allocSummary(uint32_t TotalSize)
Definition InstrProf.h:1360
uint64_t ComputeHash(StringRef K)
Definition InstrProf.h:1241
const uint64_t Magic
Definition InstrProf.h:1194
uint64_t getMagic()
const uint64_t Version
Definition InstrProf.h:1383
constexpr uint64_t MaximumSupportedVersion
Definition MemProf.h:53
constexpr uint64_t MinimumSupportedVersion
Definition MemProf.h:52
SmallVector< uint8_t, 10 > BuildID
A build ID in binary form.
Definition BuildID.h:27
value_type byte_swap(value_type value, endianness endian)
Swap the bytes of value to match the given endianness.
Definition Endian.h:45
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition Endian.h:53
value_type readNext(const CharT *&memory, endianness endian)
Read a value of a particular endianness from a buffer, and increment the buffer past that value.
Definition Endian.h:67
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
Definition STLExtras.h:2132
RawInstrProfReader< uint64_t > RawInstrProfReader64
static Expected< std::unique_ptr< MemoryBuffer > > setupMemoryBuffer(const Twine &Filename, vfs::FileSystem &FS)
RelativeUniformCounterPtr ValuesPtrExpr NumBitmapBytes
Definition InstrProf.h:101
RelativeUniformCounterPtr ValuesPtrExpr NumValueSites[IPVK_Last+1]
Definition InstrProf.h:95
constexpr T byteswap(T V) noexcept
Reverses the bytes in the given integer value V.
Definition bit.h:102
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition Error.h:990
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr UniformCountersDelta
Definition InstrProf.h:210
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr UniformCountersStart
Definition InstrProf.h:179
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
FuncHash
Definition InstrProf.h:78
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
OnDiskIterableChainedHashTable< memprof::CallStackLookupTrait > MemProfCallStackHashTable
constexpr T alignToPowerOf2(U Value, V Align)
Will overflow only if result is not representable in T.
Definition MathExtras.h:488
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
OnDiskIterableChainedHashTable< memprof::FrameLookupTrait > MemProfFrameHashTable
bool isDigit(char C)
Checks if character C is one of the 10 decimal digits.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr CountersStart
Definition InstrProf.h:167
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr NamesStart
Definition InstrProf.h:161
constexpr char GlobalIdentifierDelimiter
Definition GlobalValue.h:47
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
std::vector< ProfileSummaryEntry > SummaryEntryVector
endianness
Definition bit.h:71
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
InstrProfKind
An enum describing the attributes of an instrumented profile.
Definition InstrProf.h:385
RawInstrProfReader< uint32_t > RawInstrProfReader32
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
LLVM_ABI size_t size() const
static LLVM_ABI Expected< Header > readFromBuffer(const unsigned char *Buffer)
uint64_t Cutoff
The required percentile of total execution count.
Definition InstrProf.h:1284
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
Definition InstrProf.h:1287
uint64_t MinBlockCount
The minimum execution count for this percentile.
Definition InstrProf.h:1286
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
Definition InstrProf.h:1320
Profiling information for a single function.
Definition InstrProf.h:908
static bool hasCSFlagInHash(uint64_t FuncHash)
Definition InstrProf.h:1127
An ordered list of functions identified by their NameRef found in INSTR_PROF_DATA.
Definition InstrProf.h:443
YamlDataAccessProfData YamlifiedDataAccessProfiles
Definition MemProfYAML.h:41
std::vector< GUIDMemProfRecordPair > HeapProfileRecords
Definition MemProfYAML.h:40
std::optional< CallStackId > LastUnmappedId
The data access profiles for a symbol.
std::optional< FrameId > LastUnmappedId
LLVM_ABI MemProfRecord toMemProfRecord(llvm::function_ref< std::vector< Frame >(const CallStackId)> Callback) const
Definition MemProf.cpp:323
std::vector< memprof::DataAccessProfRecord > Records
Definition MemProfYAML.h:28
std::vector< uint64_t > KnownColdStrHashes
Definition MemProfYAML.h:29
std::vector< std::string > KnownColdSymbols
Definition MemProfYAML.h:30