LLVM 24.0.0git
SampleProfReader.h
Go to the documentation of this file.
1//===- SampleProfReader.h - Read LLVM sample profile data -------*- C++ -*-===//
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 definitions needed for reading sample profiles.
10//
11// NOTE: If you are making changes to this file format, please remember
12// to document them in the Clang documentation at
13// tools/clang/docs/UsersManual.rst.
14//
15// Text format
16// -----------
17//
18// Sample profiles are written as ASCII text. The file is divided into
19// sections, which correspond to each of the functions executed at runtime.
20// Each section has the following format
21//
22// function1:total_samples:total_head_samples
23// offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
24// offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
25// ...
26// offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
27// offsetA[.discriminator]: fnA:num_of_total_samples
28// offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
29// ...
30// !CFGChecksum: num
31// !Attribute: flags
32//
33// This is a nested tree in which the indentation represents the nesting level
34// of the inline stack. There are no blank lines in the file. And the spacing
35// within a single line is fixed. Additional spaces will result in an error
36// while reading the file.
37//
38// Any line starting with the '#' character is completely ignored.
39//
40// Inlined calls are represented with indentation. The Inline stack is a
41// stack of source locations in which the top of the stack represents the
42// leaf function, and the bottom of the stack represents the actual
43// symbol to which the instruction belongs.
44//
45// Function names must be mangled in order for the profile loader to
46// match them in the current translation unit. The two numbers in the
47// function header specify how many total samples were accumulated in the
48// function (first number), and the total number of samples accumulated
49// in the prologue of the function (second number). This head sample
50// count provides an indicator of how frequently the function is invoked.
51//
52// There are three types of lines in the function body.
53//
54// * Sampled line represents the profile information of a source location.
55// * Callsite line represents the profile information of a callsite.
56// * Metadata line represents extra metadata of the function.
57//
58// Each sampled line may contain several items. Some are optional (marked
59// below):
60//
61// a. Source line offset. This number represents the line number
62// in the function where the sample was collected. The line number is
63// always relative to the line where symbol of the function is
64// defined. So, if the function has its header at line 280, the offset
65// 13 is at line 293 in the file.
66//
67// Note that this offset should never be a negative number. This could
68// happen in cases like macros. The debug machinery will register the
69// line number at the point of macro expansion. So, if the macro was
70// expanded in a line before the start of the function, the profile
71// converter should emit a 0 as the offset (this means that the optimizers
72// will not be able to associate a meaningful weight to the instructions
73// in the macro).
74//
75// b. [OPTIONAL] Discriminator. This is used if the sampled program
76// was compiled with DWARF discriminator support
77// (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
78// DWARF discriminators are unsigned integer values that allow the
79// compiler to distinguish between multiple execution paths on the
80// same source line location.
81//
82// For example, consider the line of code ``if (cond) foo(); else bar();``.
83// If the predicate ``cond`` is true 80% of the time, then the edge
84// into function ``foo`` should be considered to be taken most of the
85// time. But both calls to ``foo`` and ``bar`` are at the same source
86// line, so a sample count at that line is not sufficient. The
87// compiler needs to know which part of that line is taken more
88// frequently.
89//
90// This is what discriminators provide. In this case, the calls to
91// ``foo`` and ``bar`` will be at the same line, but will have
92// different discriminator values. This allows the compiler to correctly
93// set edge weights into ``foo`` and ``bar``.
94//
95// c. Number of samples. This is an integer quantity representing the
96// number of samples collected by the profiler at this source
97// location.
98//
99// d. [OPTIONAL] Potential call targets and samples. If present, this
100// line contains a call instruction. This models both direct and
101// number of samples. For example,
102//
103// 130: 7 foo:3 bar:2 baz:7
104//
105// The above means that at relative line offset 130 there is a call
106// instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
107// with ``baz()`` being the relatively more frequently called target.
108//
109// Each callsite line may contain several items. Some are optional.
110//
111// a. Source line offset. This number represents the line number of the
112// callsite that is inlined in the profiled binary.
113//
114// b. [OPTIONAL] Discriminator. Same as the discriminator for sampled line.
115//
116// c. Number of samples. This is an integer quantity representing the
117// total number of samples collected for the inlined instance at this
118// callsite
119//
120// Metadata line can occur in lines with one indent only, containing extra
121// information for the top-level function. Furthermore, metadata can only
122// occur after all the body samples and callsite samples.
123// Each metadata line may contain a particular type of metadata, marked by
124// the starting characters annotated with !. We process each metadata line
125// independently, hence each metadata line has to form an independent piece
126// of information that does not require cross-line reference.
127// We support the following types of metadata:
128//
129// a. CFG Checksum (a.k.a. function hash):
130// !CFGChecksum: 12345
131// b. CFG Checksum (see ContextAttributeMask):
132// !Atribute: 1
133//
134//
135// Binary format
136// -------------
137//
138// This is a more compact encoding. Numbers are encoded as ULEB128 values
139// and all strings are encoded in a name table. The file is organized in
140// the following sections:
141//
142// MAGIC (uint64_t)
143// File identifier computed by function SPMagic() (0x5350524f463432ff)
144//
145// VERSION (uint32_t)
146// File format version number computed by SPVersion()
147//
148// SUMMARY
149// TOTAL_COUNT (uint64_t)
150// Total number of samples in the profile.
151// MAX_COUNT (uint64_t)
152// Maximum value of samples on a line.
153// MAX_FUNCTION_COUNT (uint64_t)
154// Maximum number of samples at function entry (head samples).
155// NUM_COUNTS (uint64_t)
156// Number of lines with samples.
157// NUM_FUNCTIONS (uint64_t)
158// Number of functions with samples.
159// NUM_DETAILED_SUMMARY_ENTRIES (size_t)
160// Number of entries in detailed summary
161// DETAILED_SUMMARY
162// A list of detailed summary entry. Each entry consists of
163// CUTOFF (uint32_t)
164// Required percentile of total sample count expressed as a fraction
165// multiplied by 1000000.
166// MIN_COUNT (uint64_t)
167// The minimum number of samples required to reach the target
168// CUTOFF.
169// NUM_COUNTS (uint64_t)
170// Number of samples to get to the desrired percentile.
171//
172// NAME TABLE
173// SIZE (uint64_t)
174// Number of entries in the name table.
175// NAMES
176// A NUL-separated list of SIZE strings.
177//
178// FUNCTION BODY (one for each uninlined function body present in the profile)
179// HEAD_SAMPLES (uint64_t) [only for top-level functions]
180// Total number of samples collected at the head (prologue) of the
181// function.
182// NOTE: This field should only be present for top-level functions
183// (i.e., not inlined into any caller). Inlined function calls
184// have no prologue, so they don't need this.
185// NAME_IDX (uint64_t)
186// Index into the name table indicating the function name.
187// SAMPLES (uint64_t)
188// Total number of samples collected in this function.
189// NRECS (uint32_t)
190// Total number of sampling records this function's profile.
191// BODY RECORDS
192// A list of NRECS entries. Each entry contains:
193// OFFSET (uint32_t)
194// Line offset from the start of the function.
195// DISCRIMINATOR (uint32_t)
196// Discriminator value (see description of discriminators
197// in the text format documentation above).
198// SAMPLES (uint64_t)
199// Number of samples collected at this location.
200// NUM_CALLS (uint32_t)
201// Number of non-inlined function calls made at this location. In the
202// case of direct calls, this number will always be 1. For indirect
203// calls (virtual functions and function pointers) this will
204// represent all the actual functions called at runtime.
205// CALL_TARGETS
206// A list of NUM_CALLS entries for each called function:
207// NAME_IDX (uint64_t)
208// Index into the name table with the callee name.
209// SAMPLES (uint64_t)
210// Number of samples collected at the call site.
211// NUM_INLINED_FUNCTIONS (uint32_t)
212// Number of callees inlined into this function.
213// INLINED FUNCTION RECORDS
214// A list of NUM_INLINED_FUNCTIONS entries describing each of the inlined
215// callees.
216// OFFSET (uint32_t)
217// Line offset from the start of the function.
218// DISCRIMINATOR (uint32_t)
219// Discriminator value (see description of discriminators
220// in the text format documentation above).
221// FUNCTION BODY
222// A FUNCTION BODY entry describing the inlined function.
223//
224// An ExtBinary file may contain both legacy and composite profile sections.
225// Each section's type independently selects its function-body encoding.
226//
227// COMPOSITE FUNCTION BODY (used by SecCompositeProfile)
228// NAME_IDX (uint64_t)
229// Index into the name table indicating the function name.
230// NUM_PROFILE_TYPES (uint64_t)
231// Number of typed profile blocks attached to this function. Zero is
232// valid when the function has no payload for any profile type.
233// PROFILE TYPE BLOCKS
234// A list of NUM_PROFILE_TYPES entries. Each entry contains:
235// TYPE (uint64_t)
236// Profile type ID. A type may occur at most once per function;
237// duplicate IDs make the profile malformed.
238// PAYLOAD_SIZE (uint64_t)
239// Size of PAYLOAD in bytes.
240// PAYLOAD
241// Type-specific data occupying exactly PAYLOAD_SIZE bytes.
242// Readers skip unknown types using PAYLOAD_SIZE.
243// A known type must consume exactly PAYLOAD_SIZE bytes; extend an
244// existing payload by assigning a new profile type ID.
245//
246// The ProfTypeLBR payload contains HEAD_SAMPLES for top-level functions,
247// followed by SAMPLES, NRECS, and BODY RECORDS as described above.
248// Nested functions omit HEAD_SAMPLES.
249// NUM_INLINED_FUNCTIONS (uint32_t)
250// Number of callees inlined into this function.
251// INLINED FUNCTION RECORDS
252// Encoded as described above, except each nested FUNCTION BODY uses the
253// composite representation.
254//===----------------------------------------------------------------------===//
255
256#ifndef LLVM_PROFILEDATA_SAMPLEPROFREADER_H
257#define LLVM_PROFILEDATA_SAMPLEPROFREADER_H
258
259#include "llvm/ADT/Eytzinger.h"
260#include "llvm/ADT/STLExtras.h"
262#include "llvm/ADT/SmallVector.h"
263#include "llvm/ADT/StringRef.h"
264#include "llvm/ADT/StringSet.h"
266#include "llvm/IR/LLVMContext.h"
272#include "llvm/Support/Debug.h"
274#include "llvm/Support/ErrorOr.h"
277#include <array>
278#include <cstdint>
279#include <list>
280#include <memory>
281#include <optional>
282#include <string>
283#include <system_error>
284#include <vector>
285
286namespace llvm {
287
288class raw_ostream;
289class Twine;
290
291namespace sampleprof {
292
294
295/// SampleProfileReaderItaniumRemapper remaps the profile data from a
296/// sample profile data reader, by applying a provided set of equivalences
297/// between components of the symbol names in the profile.
299public:
300 SampleProfileReaderItaniumRemapper(std::unique_ptr<MemoryBuffer> B,
301 std::unique_ptr<SymbolRemappingReader> SRR,
303 : Buffer(std::move(B)), Remappings(std::move(SRR)), Reader(R) {
304 assert(Remappings && "Remappings cannot be nullptr");
305 }
306
307 /// Create a remapper from the given remapping file. The remapper will
308 /// be used for profile read in by Reader.
311 LLVMContext &C);
312
313 /// Create a remapper from the given Buffer. The remapper will
314 /// be used for profile read in by Reader.
316 create(std::unique_ptr<MemoryBuffer> &B, SampleProfileReader &Reader,
317 LLVMContext &C);
318
319 /// Apply remappings to the profile read by Reader.
321
322 bool hasApplied() { return RemappingApplied; }
323
324 /// Insert function name into remapper.
325 void insert(StringRef FunctionName) { Remappings->insert(FunctionName); }
326
327 /// Query whether there is equivalent in the remapper which has been
328 /// inserted.
329 bool exist(StringRef FunctionName) {
330 return Remappings->lookup(FunctionName);
331 }
332
333 /// Return the equivalent name in the profile for \p FunctionName if
334 /// it exists.
335 LLVM_ABI std::optional<StringRef> lookUpNameInProfile(StringRef FunctionName);
336
337private:
338 // The buffer holding the content read from remapping file.
339 std::unique_ptr<MemoryBuffer> Buffer;
340 std::unique_ptr<SymbolRemappingReader> Remappings;
341 // Map remapping key to the name in the profile. By looking up the
342 // key in the remapper, a given new name can be mapped to the
343 // cannonical name using the NameMap.
345 // The Reader the remapper is servicing.
346 SampleProfileReader &Reader;
347 // Indicate whether remapping has been applied to the profile read
348 // by Reader -- by calling applyRemapping.
349 bool RemappingApplied = false;
350};
351
352/// Sample-based profile reader.
353///
354/// Each profile contains sample counts for all the functions
355/// executed. Inside each function, statements are annotated with the
356/// collected samples on all the instructions associated with that
357/// statement.
358///
359/// For this to produce meaningful data, the program needs to be
360/// compiled with some debug information (at minimum, line numbers:
361/// -gline-tables-only). Otherwise, it will be impossible to match IR
362/// instructions to the line numbers collected by the profiler.
363///
364/// From the profile file, we are interested in collecting the
365/// following information:
366///
367/// * A list of functions included in the profile (mangled names).
368///
369/// * For each function F:
370/// 1. The total number of samples collected in F.
371///
372/// 2. The samples collected at each line in F. To provide some
373/// protection against source code shuffling, line numbers should
374/// be relative to the start of the function.
375///
376/// The reader supports two file formats: text and binary. The text format
377/// is useful for debugging and testing, while the binary format is more
378/// compact and I/O efficient. They can both be used interchangeably.
379
380/// Manages the sample profile name table, supporting both an eagerly loaded
381/// std::vector of FunctionId objects and lazy-loaded MD5 hashes read directly
382/// from the memory-mapped buffer. It enforces the exclusivity of these
383/// two formats and provides a unified read-only container interface.
385public:
387 : public llvm::iterator_facade_base<iterator, std::input_iterator_tag,
388 FunctionId, std::ptrdiff_t,
389 const FunctionId *, FunctionId> {
390 public:
391 iterator() = default;
392 iterator(const SampleProfileNameTable *Table, size_t Idx)
393 : Table(Table), Idx(Idx) {}
394
395 bool operator==(const iterator &RHS) const {
396 return Table == RHS.Table && Idx == RHS.Idx;
397 }
398
400 ++Idx;
401 return *this;
402 }
403
405 assert(Table && Idx < Table->size() &&
406 "Dereferencing invalid or out-of-bounds iterator");
407 return (*Table)[Idx];
408 }
409
410 private:
411 const SampleProfileNameTable *Table = nullptr;
412 size_t Idx = 0;
413 };
414
416
422 virtual ~SampleProfileNameTable() = default;
423
424 virtual size_t size() const = 0;
425 bool empty() const { return size() == 0; }
426 virtual FunctionId operator[](size_t Idx) const = 0;
427
429 getEytzingerSpan(bool IsNested) const {
431 "getEytzingerSpan is exclusively supported for Eytzinger layout");
432 }
433 virtual bool contains(StringRef Key) const {
434 return contains(FunctionId(Key).getHashCode());
435 }
436 virtual bool contains(uint64_t GUID) const {
437 return getOrCreateSet(GUIDSet, *this, GetFunctionIdHash).contains(GUID);
438 }
439
440 iterator begin() const { return iterator(this, 0); }
441 iterator end() const { return iterator(this, size()); }
442
443protected:
444 mutable std::optional<DenseSet<uint64_t>> GUIDSet;
445
446 static constexpr auto GetFunctionIdHash = [](FunctionId F) {
447 return F.getHashCode();
448 };
449 static constexpr auto GetFunctionIdString = [](FunctionId F) {
450 return F.stringRef();
451 };
452
453 template <typename SetT, typename RangeT, typename ProjT = llvm::identity>
454 static const SetT &getOrCreateSet(std::optional<SetT> &Set,
455 const RangeT &Range, ProjT Proj = ProjT()) {
456 if (!Set) {
457 Set.emplace();
458 Set->reserve(Range.size());
459 for (const auto &Item : Range)
460 Set->insert(Proj(Item));
461 }
462 return *Set;
463 }
464};
465
467 const uint8_t *Start = nullptr;
468 size_t Size = 0;
469
470public:
471 LazySampleProfileNameTable(const uint8_t *Start, size_t Size)
472 : Start(Start), Size(Size) {}
473
474 size_t size() const override { return Size; }
475
476 FunctionId operator[](size_t Idx) const override {
477 assert(Idx < Size && "Index out of bounds");
478 using namespace support;
480 Start + Idx * sizeof(uint64_t), endianness::little));
481 }
482
483 bool contains(uint64_t GUID) const override {
485 reinterpret_cast<const support::ulittle64_t *>(Start), Size);
486 return getOrCreateSet(GUIDSet, Table).contains(GUID);
487 }
488};
489
491 std::vector<FunctionId> Vec;
492 mutable std::optional<DenseSet<StringRef>> NameSet;
493
494public:
495 explicit StringSampleProfileNameTable(std::vector<FunctionId> &&Vec)
496 : Vec(std::move(Vec)) {}
497 explicit StringSampleProfileNameTable(const std::vector<FunctionId> &Vec)
498 : Vec(Vec) {}
499
500 size_t size() const override { return Vec.size(); }
501
502 FunctionId operator[](size_t Idx) const override {
503 assert(Idx < Vec.size() && "Index out of bounds");
504 return Vec[Idx];
505 }
506
507 bool contains(StringRef Key) const override {
508 return getOrCreateSet(NameSet, Vec, GetFunctionIdString).contains(Key);
509 }
510};
511
513 std::vector<FunctionId> Vec;
514
515public:
516 explicit MD5SampleProfileNameTable(std::vector<FunctionId> &&Vec)
517 : Vec(std::move(Vec)) {}
518 explicit MD5SampleProfileNameTable(const std::vector<FunctionId> &Vec)
519 : Vec(Vec) {}
520
521 size_t size() const override { return Vec.size(); }
522
523 FunctionId operator[](size_t Idx) const override {
524 assert(Idx < Vec.size() && "Index out of bounds");
525 return Vec[Idx];
526 }
527};
528
531 std::array<EytzingerTableSpan<support::ulittle64_t>,
532 static_cast<size_t>(EytzingerSpan::NumSpans)>
533 Spans;
534
535public:
537 size_t NumNested, size_t NumFlat,
538 size_t NumInlinees)
539 : Array(Data, NumNested + NumFlat + NumInlinees),
540 Spans{{{Data, NumNested},
541 {Data + NumNested, NumFlat},
542 {Data + NumNested + NumFlat, NumInlinees}}} {}
543
544 size_t size() const override { return Array.size(); }
545
546 FunctionId operator[](size_t Idx) const override {
547 return FunctionId(Array[Idx]);
548 }
549
551 getEytzingerSpan(bool IsNested) const override {
552 return Spans[static_cast<size_t>(IsNested ? EytzingerSpan::Nested
554 }
555
556 bool contains(uint64_t GUID) const override {
557 return llvm::any_of(Spans,
558 [&](const auto &Span) { return Span.contains(GUID); });
559 }
560};
561
563public:
564 SampleProfileReader(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
566 : Profiles(), Ctx(C), Buffer(std::move(B)), Format(Format) {}
567
568 virtual ~SampleProfileReader() = default;
569
570 /// Read and validate the file header.
571 virtual std::error_code readHeader() = 0;
572
573 /// Set the bits for FS discriminators. Parameter Pass specify the sequence
574 /// number, Pass == i is for the i-th round of adding FS discriminators.
575 /// Pass == 0 is for using base discriminators.
579
580 /// Get the bitmask the discriminators: For FS profiles, return the bit
581 /// mask for this pass. For non FS profiles, return (unsigned) -1.
583 if (!ProfileIsFS)
584 return 0xFFFFFFFF;
585 assert((MaskedBitFrom != 0) && "MaskedBitFrom is not set properly");
586 return getN1Bits(MaskedBitFrom);
587 }
588
589 /// The interface to read sample profiles from the associated file.
590 std::error_code read() {
591 if (std::error_code EC = readImpl())
592 return EC;
593 if (Remapper)
594 Remapper->applyRemapping(Ctx);
597 }
598
599 /// Read sample profiles for the given functions.
600 std::error_code read(const DenseSet<StringRef> &FuncsToUse) {
602 for (StringRef F : FuncsToUse)
603 if (Profiles.find(FunctionId(F)) == Profiles.end())
604 S.insert(F);
605 if (std::error_code EC = read(S, Profiles))
606 return EC;
608 }
609
610 /// The implementaion to read sample profiles from the associated file.
611 virtual std::error_code readImpl() = 0;
612
613 /// Print the profile for \p FunctionSamples on stream \p OS.
615 raw_ostream &OS = dbgs());
616
617 /// Collect functions with definitions in Module M. For reader which
618 /// support loading function profiles on demand, return true when the
619 /// reader has been given a module. Always return false for reader
620 /// which doesn't support loading function profiles on demand.
621 virtual bool collectFuncsFromModule() { return false; }
622
623 /// Print all the profiles on stream \p OS.
624 LLVM_ABI void dump(raw_ostream &OS = dbgs());
625
626 /// Print all the profiles on stream \p OS in the JSON format.
627 LLVM_ABI void dumpJson(raw_ostream &OS = dbgs());
628
629 /// Return the format version of the profile. For tests only.
631
632 /// Return the samples collected for function \p F.
634 // The function name may have been updated by adding suffix. Call
635 // a helper to (optionally) strip off suffixes so that we can
636 // match against the original function name in the profile.
638 return getSamplesFor(CanonName);
639 }
640
641 /// Return the samples collected for function \p F.
643 auto It = Profiles.find(FunctionId(Fname));
644 if (It != Profiles.end())
645 return &It->second;
646
648 auto R = FuncNameToProfNameMap->find(FunctionId(Fname));
649 if (R != FuncNameToProfNameMap->end()) {
650 Fname = R->second.stringRef();
651 auto It = Profiles.find(FunctionId(Fname));
652 if (It != Profiles.end())
653 return &It->second;
654 }
655 }
656
657 if (Remapper) {
658 if (auto NameInProfile = Remapper->lookUpNameInProfile(Fname)) {
659 auto It = Profiles.find(FunctionId(*NameInProfile));
660 if (It != Profiles.end())
661 return &It->second;
662 }
663 }
664 return nullptr;
665 }
666
667 /// Return all the profiles.
669
670 /// Report a parse error message.
671 void reportError(int64_t LineNumber, const Twine &Msg) const {
672 Ctx.diagnose(DiagnosticInfoSampleProfile(Buffer->getBufferIdentifier(),
673 LineNumber, Msg));
674 }
675
676 /// Create a sample profile reader appropriate to the file format.
677 /// Create a remapper underlying if RemapFilename is not empty.
678 /// Parameter P specifies the FSDiscriminatorPass.
682 StringRef RemapFilename = "");
683
684 /// Create a sample profile reader from the supplied memory buffer.
685 /// Create a remapper underlying if RemapFilename is not empty.
686 /// Parameter P specifies the FSDiscriminatorPass.
688 create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C, vfs::FileSystem &FS,
690 StringRef RemapFilename = "");
691
692 /// Return the profile summary.
693 ProfileSummary &getSummary() const { return *Summary; }
694
695 MemoryBuffer *getBuffer() const { return Buffer.get(); }
696
697 /// \brief Return the profile format.
699
700 /// Whether input profile is based on pseudo probes.
702
703 /// Whether input profile is fully context-sensitive.
704 bool profileIsCS() const { return ProfileIsCS; }
705
706 /// Whether input profile contains ShouldBeInlined contexts.
708
709 /// Whether input profile is flow-sensitive.
710 bool profileIsFS() const { return ProfileIsFS; }
711
712 virtual std::unique_ptr<ProfileSymbolList> getProfileSymbolList() {
713 return nullptr;
714 };
715
716 /// It includes all the names that have samples either in outline instance
717 /// or inline instance.
723 virtual bool dumpSectionInfo(raw_ostream &OS = dbgs()) { return false; };
724 virtual bool contains(StringRef Key) const { return false; }
725 virtual bool contains(uint64_t GUID) const { return false; }
726
727 /// Read the profile and print the structure of composite profile blocks.
728 std::error_code dumpProfileTypeInfo(raw_ostream &OS) {
729 ProfileTypeInfoOS = &OS;
730 std::error_code EC = read();
731 ProfileTypeInfoOS = nullptr;
732 return EC;
733 }
734
735 /// Return whether the input contains a composite profile section.
736 virtual bool hasCompositeProfileSection() const { return false; }
737
738 /// Return whether any unknown composite profile blocks were skipped.
740
741 /// Return whether names in the profile are all MD5 numbers.
742 bool useMD5() const { return ProfileIsMD5; }
743
744 /// Force the profile to use MD5 in Sample contexts, even if function names
745 /// are present.
746 virtual void setProfileUseMD5() { ProfileIsMD5 = true; }
747
748 /// Don't read profile without context if the flag is set.
749 void setSkipFlatProf(bool Skip) { SkipFlatProf = Skip; }
750
751 /// Return whether any name in the profile contains ".__uniq." suffix.
752 virtual bool hasUniqSuffix() { return false; }
753
755
756 void setModule(const Module *Mod) { M = Mod; }
757
762
763protected:
764 /// Map every function to its associated profile.
765 ///
766 /// The profile of every function executed at runtime is collected
767 /// in the structure FunctionSamples. This maps function objects
768 /// to their corresponding profiles.
770
771 /// LLVM context used to emit diagnostics.
773
774 /// Memory buffer holding the profile file.
775 std::unique_ptr<MemoryBuffer> Buffer;
776
777 /// Profile summary information.
778 std::unique_ptr<ProfileSummary> Summary;
779
780 /// Take ownership of the summary of this reader.
781 static std::unique_ptr<ProfileSummary>
783 return std::move(Reader.Summary);
784 }
785
786 /// Compute summary for this profile.
788
789 /// Read sample profiles for the given functions and write them to the given
790 /// profile map. Currently it's only used for extended binary format to load
791 /// the profiles on-demand.
792 virtual std::error_code read(const DenseSet<StringRef> &FuncsToUse,
795 }
796
797 std::unique_ptr<SampleProfileReaderItaniumRemapper> Remapper;
798
799 // A map pointer to the FuncNameToProfNameMap in SampleProfileLoader,
800 // which maps the function name to the matched profile name. This is used
801 // for sample loader to look up profile using the new name.
803 nullptr;
804
805 // A map from a function's context hash to its meta data section range, used
806 // for on-demand read function profile metadata.
809
810 /// A profile section retained for loading additional functions on demand.
812 /// First byte of the retained section.
813 const uint8_t *Start = nullptr;
814 /// One-past-the-end byte of the retained section.
815 const uint8_t *End = nullptr;
816 /// Whether the retained section uses composite payload encoding.
817 bool IsComposite = false;
818 };
819 /// Profile section most recently selected for on-demand loading.
821 /// Optional stream for composite block structure; null disables the output.
823 /// Whether reading skipped at least one unknown composite profile block.
825
826 /// Whether the profile has attribute metadata.
828
829 /// \brief Whether samples are collected based on pseudo probes.
831
832 /// Whether function profiles are context-sensitive flat profiles.
833 bool ProfileIsCS = false;
834
835 /// Whether function profile contains ShouldBeInlined contexts.
837
838 /// Number of context-sensitive profiles.
840
841 /// Whether the function profiles use FS discriminators.
842 bool ProfileIsFS = false;
843
844 /// Format version of the profile.
846
847 /// If true, the profile has vtable profiles and reader should decode them
848 /// to parse profiles correctly.
849 bool ReadVTableProf = false;
850
851 /// \brief The format of sample.
853
854 /// \brief The current module being compiled if SampleProfileReader
855 /// is used by compiler. If SampleProfileReader is used by other
856 /// tools which are not compiler, M is usually nullptr.
857 const Module *M = nullptr;
858
859 /// Zero out the discriminator bits higher than bit MaskedBitFrom (0 based).
860 /// The default is to keep all the bits.
862
863 /// Whether the profile uses MD5 for Sample Contexts and function names. This
864 /// can be one-way overriden by the user to force use MD5.
865 bool ProfileIsMD5 = false;
866
867 /// If SkipFlatProf is true, skip functions marked with !Flat in text mode or
868 /// sections with SecFlagFlat flag in ExtBinary mode.
869 bool SkipFlatProf = false;
870};
871
873public:
874 SampleProfileReaderText(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
876
877 /// Read and validate the file header.
878 std::error_code readHeader() override { return sampleprof_error::success; }
879
880 /// Read sample profiles from the associated file.
881 std::error_code readImpl() override;
882
883 /// Return true if \p Buffer is in the format supported by this class.
884 static bool hasFormat(const MemoryBuffer &Buffer);
885
886 /// Text format sample profile does not support MD5 for now.
887 void setProfileUseMD5() override {}
888
889private:
890 /// CSNameTable is used to save full context vectors. This serves as an
891 /// underlying immutable buffer for all clients.
892 std::list<SampleContextFrameVector> CSNameTable;
893};
894
896public:
900
901 /// Read and validate the file header.
902 std::error_code readHeader() override;
903
904 /// Read sample profiles from the associated file.
905 std::error_code readImpl() override;
906
907 /// It includes all the names that have samples either in outline instance
908 /// or inline instance.
910 getNameTable() const override {
911 if (!NameTable)
914 return {NameTable->begin(), NameTable->end()};
915 }
916
917 bool contains(StringRef Key) const override {
918 assert(NameTable && "NameTable should be populated before querying");
919 return NameTable->contains(Key);
920 }
921
922 bool contains(uint64_t GUID) const override {
923 assert(NameTable && "NameTable should be populated before querying");
924 return NameTable->contains(GUID);
925 }
926
927protected:
928 /// Read a numeric value of type T from the profile.
929 ///
930 /// If an error occurs during decoding, a diagnostic message is emitted and
931 /// EC is set.
932 ///
933 /// \returns the read value.
934 template <typename T> ErrorOr<T> readNumber();
935
936 /// Read a numeric value of type T from the profile. The value is saved
937 /// without encoded.
938 template <typename T> ErrorOr<T> readUnencodedNumber();
939
940 /// Read a string from the profile.
941 ///
942 /// If an error occurs during decoding, a diagnostic message is emitted and
943 /// EC is set.
944 ///
945 /// \returns the read value.
947
948 /// Read the string index and check whether it overflows the table.
949 template <typename T> inline ErrorOr<size_t> readStringIndex(T &Table);
950
951 /// Read the next function profile instance.
952 std::error_code readFuncProfile(const uint8_t *Start);
953 std::error_code readFuncProfile(const uint8_t *Start,
954 SampleProfileMap &Profiles);
955
956 /// Read the contents of the given profile instance.
957 std::error_code readProfile(FunctionSamples &FProfile, bool IsNested);
958
959 /// Read specific profile types.
960 std::error_code readLBRProfile(FunctionSamples &FProfile, bool IsNested);
961 std::error_code readCompositeProfile(FunctionSamples &FProfile,
962 bool IsNested);
963
964 /// Read the contents of Magic number and Version number.
965 std::error_code readMagicIdent();
966
967 /// Read profile summary.
968 std::error_code readSummary();
969
970 /// Read the whole name table.
971 std::error_code readNameTable();
972
973 /// Read a string indirectly via the name table. Optionally return the index.
974 ErrorOr<FunctionId> readStringFromTable(size_t *RetIdx = nullptr);
975
976 /// Read a context indirectly via the CSNameTable. Optionally return the
977 /// index.
978 ErrorOr<SampleContextFrames> readContextFromTable(size_t *RetIdx = nullptr);
979
980 /// Read a context indirectly via the CSNameTable if the profile has context,
981 /// otherwise same as readStringFromTable, also return its hash value.
982 ErrorOr<std::pair<SampleContext, uint64_t>> readSampleContextFromTable();
983
984 /// Read all virtual functions' vtable access counts for \p FProfile.
985 std::error_code readCallsiteVTableProf(FunctionSamples &FProfile);
986
987 /// Read bytes from the input buffer pointed by `Data` and decode them into
988 /// \p M. `Data` will be advanced to the end of the read bytes when this
989 /// function returns. Returns error if any.
990 std::error_code readVTableTypeCountMap(TypeCountMap &M);
991
992 /// Points to the current location in the buffer.
993 const uint8_t *Data = nullptr;
994
995 /// Points to the end of the buffer.
996 const uint8_t *End = nullptr;
997
998 /// Function name table.
999 std::unique_ptr<SampleProfileNameTable> NameTable;
1000
1001 /// CSNameTable is used to save full context vectors. It is the backing buffer
1002 /// for SampleContextFrames.
1003 std::vector<SampleContextFrameVector> CSNameTable;
1004
1005 /// Table to cache MD5 values of sample contexts corresponding to
1006 /// readSampleContextFromTable(), used to index into Profiles or
1007 /// FuncOffsetTable.
1008 std::vector<uint64_t> MD5SampleContextTable;
1009
1010 /// The starting address of the table of MD5 values of sample contexts. For
1011 /// fixed length MD5 non-CS profile it is same as MD5NameMemStart because
1012 /// hashes of non-CS contexts are already in the profile. Otherwise it points
1013 /// to the start of MD5SampleContextTable.
1015
1016private:
1017 std::error_code readSummaryEntry(std::vector<ProfileSummaryEntry> &Entries);
1018 virtual std::error_code verifySPMagic(uint64_t Magic) = 0;
1019};
1020
1022private:
1023 std::error_code verifySPMagic(uint64_t Magic) override;
1024
1025public:
1029
1030 /// \brief Return true if \p Buffer is in the format supported by this class.
1031 static bool hasFormat(const MemoryBuffer &Buffer);
1032};
1033
1034/// Tags to select the initialization mode of SampleProfileFuncOffsetTable.
1037
1038inline constexpr InMemoryModeT InMemoryMode{};
1040
1041/// A unified wrapper representing the function offset table.
1042///
1043/// This class abstracts away the physical representation of the offset table,
1044/// which can either be:
1045///
1046/// - An llvm::DenseMap mapping function GUIDs (or context hashes) to their
1047/// profile offsets, populated when reading the array of offsets in
1048/// context-sensitive (CS) profiles or version 103 profiles.
1049///
1050/// - A raw slice of 32-bit relative offsets for Eytzinger parallel lookups.
1051///
1052/// It exposes a single, type-agnostic lookup interface, shielding the reader
1053/// from the underlying container types. To prevent hybrid-state corruption, the
1054/// table's mode is locked at construction time.
1056public:
1058
1066
1068 size_t InitialCapacity = 0)
1069 : Mode(TableMode::InMemory) {
1070 InMemoryTable.reserve(InitialCapacity);
1071 }
1072
1075 ArrayRef<support::ulittle32_t> FuncOffsetSpan)
1076 : Mode(TableMode::Eytzinger), NameSpan(NameSpan),
1077 FuncOffsetSpan(FuncOffsetSpan) {}
1078
1079 /// Insert a function GUID and its profile offset into the in-memory map.
1081 assert(Mode == TableMode::InMemory &&
1082 "Cannot insert into a non-in-memory offset table");
1083 InMemoryTable[GUID] = Offset;
1084 }
1085
1086 /// Query the offset table for the profile offset associated with the given
1087 /// GUID. Returns the offset if found, or std::nullopt if the key is missing.
1088 std::optional<uint64_t> lookup(uint64_t GUID) const {
1089 if (isEytzinger()) {
1090 if (std::optional<size_t> Idx = NameSpan.findIndex(GUID)) {
1091 uint32_t RelOffset = FuncOffsetSpan[*Idx];
1092 if (RelOffset != UINT32_MAX)
1093 return RelOffset;
1094 }
1095 return std::nullopt;
1096 }
1097 auto Iter = InMemoryTable.find(GUID);
1098 if (Iter != InMemoryTable.end())
1099 return Iter->second;
1100 return std::nullopt;
1101 }
1102
1103 /// Direct read-only array (`ArrayRef`) of function offsets aligned parallel
1104 /// to the corresponding Eytzinger name span.
1106 assert(isEytzinger() &&
1107 "Cannot call getFuncOffsets() on non-Eytzinger table");
1108 return FuncOffsetSpan;
1109 }
1110
1111 size_t getExpectedSize() const {
1112 assert(isEytzinger() &&
1113 "Cannot call getExpectedSize() on non-Eytzinger table");
1114 return NameSpan.size();
1115 }
1116
1117 bool isEytzinger() const { return Mode == TableMode::Eytzinger; }
1118
1119private:
1120 TableMode Mode;
1123 ArrayRef<support::ulittle32_t> FuncOffsetSpan;
1124};
1125
1126/// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase defines
1127/// the basic structure of the extensible binary format.
1128/// The format is organized in sections except the magic and version number
1129/// at the beginning. There is a section table before all the sections, and
1130/// each entry in the table describes the entry type, start, size and
1131/// attributes. The format in each section is defined by the section itself.
1132///
1133/// It is easy to add a new section while maintaining the backward
1134/// compatibility of the profile. Nothing extra needs to be done. If we want
1135/// to extend an existing section, like add cache misses information in
1136/// addition to the sample count in the profile body, we can add a new section
1137/// with the extension and retire the existing section, and we could choose
1138/// to keep the parser of the old section if we want the reader to be able
1139/// to read both new and old format profile.
1140///
1141/// SampleProfileReaderExtBinary/SampleProfileWriterExtBinary define the
1142/// commonly used sections of a profile in extensible binary format. It is
1143/// possible to define other types of profile inherited from
1144/// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase.
1146 : public SampleProfileReaderBinary {
1147private:
1148 std::error_code decompressSection(const uint8_t *SecStart,
1149 const uint64_t SecSize,
1150 const uint8_t *&DecompressBuf,
1151 uint64_t &DecompressBufSize);
1152
1153 BumpPtrAllocator Allocator;
1154
1155protected:
1156 std::vector<SecHdrTableEntry> SecHdrTable;
1157 std::error_code readSecHdrTableEntry(uint64_t Idx);
1158 std::error_code readSecHdrTable();
1159
1161 std::error_code readFuncMetadata();
1162 std::error_code readFuncMetadata(FunctionSamples *FProfile);
1163 std::error_code readFuncOffsetTable(bool IsEytzinger, bool IsNested);
1164 std::error_code readEytzingerFuncOffsetTable(bool IsNested);
1165 std::error_code readLegacyFuncOffsetTable();
1166 std::error_code readFuncProfiles();
1167 std::error_code readFuncProfiles(const DenseSet<StringRef> &FuncsToUse,
1169 std::error_code readNameTableSec(bool IsMD5, bool FixedLengthMD5,
1170 bool IsEytzinger = false);
1171 std::error_code readNameTableSecEytzinger(bool IsMD5, bool FixedLengthMD5);
1172 std::error_code readNameTableSecLegacy(bool IsMD5, bool FixedLengthMD5);
1173 std::error_code readCSNameTableSec();
1174 std::error_code readProfileSymbolList(bool IsMD5);
1175 std::error_code readStringBasedProfileSymbolList();
1176 std::error_code readMD5ProfileSymbolList();
1177
1178 std::error_code readHeader() override;
1179 std::error_code verifySPMagic(uint64_t Magic) override = 0;
1180 virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size,
1181 const SecHdrTableEntry &Entry);
1182 // placeholder for subclasses to dispatch their own section readers.
1183 virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry) = 0;
1184
1185 /// Determine which container readFuncOffsetTable() should populate, the list
1186 /// FuncOffsetList or the map FuncOffsetTable.
1187 bool useFuncOffsetList() const;
1188
1189 std::unique_ptr<ProfileSymbolList> ProfSymList;
1190
1191 /// The table mapping from a function context's MD5 to the offset of its
1192 /// FunctionSample towards file start.
1193 /// At most one of FuncOffsetTable and FuncOffsetList is populated.
1194 std::optional<SampleProfileFuncOffsetTable> FuncOffsetTable;
1195
1196 /// The list version of FuncOffsetTable. This is used if every entry is
1197 /// being accessed.
1198 std::vector<std::pair<SampleContext, uint64_t>> FuncOffsetList;
1199
1200 /// The set containing the functions to use when compiling a module.
1202
1203public:
1209
1210 /// Read sample profiles in extensible format from the associated file.
1211 std::error_code readImpl() override;
1212
1213 /// Get the total size of all \p Type sections.
1214 uint64_t getSectionSize(SecType Type);
1215 /// Get the total size of header and all sections.
1216 uint64_t getFileSize();
1217 bool dumpSectionInfo(raw_ostream &OS = dbgs()) override;
1218 /// Return whether the section table contains a composite profile section.
1219 bool hasCompositeProfileSection() const override {
1220 for (const auto &Entry : SecHdrTable)
1221 if (Entry.Type == SecCompositeProfile)
1222 return true;
1223 return false;
1224 }
1225
1226 /// Collect functions with definitions in Module M. Return true if
1227 /// the reader has been given a module.
1228 bool collectFuncsFromModule() override;
1229
1230 std::unique_ptr<ProfileSymbolList> getProfileSymbolList() override {
1231 return std::move(ProfSymList);
1232 };
1233
1234private:
1235 /// Read the profiles on-demand for the given functions. This is used after
1236 /// stale call graph matching finds new functions whose profiles aren't loaded
1237 /// at the beginning and we need to loaded the profiles explicitly for
1238 /// potential matching.
1239 std::error_code read(const DenseSet<StringRef> &FuncsToUse,
1240 SampleProfileMap &Profiles) override;
1241};
1242
1245private:
1246 std::error_code verifySPMagic(uint64_t Magic) override;
1247 std::error_code readCustomSection(const SecHdrTableEntry &Entry) override {
1248 // Update the data reader pointer to the end of the section.
1249 Data = End;
1251 };
1252
1253public:
1257
1258 /// \brief Return true if \p Buffer is in the format supported by this class.
1259 static bool hasFormat(const MemoryBuffer &Buffer);
1260};
1261
1263
1264// Supported histogram types in GCC. Currently, we only need support for
1265// call target histograms.
1276
1278public:
1279 SampleProfileReaderGCC(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
1281 GcovBuffer(Buffer.get()) {}
1282
1283 /// Read and validate the file header.
1284 std::error_code readHeader() override;
1285
1286 /// Read sample profiles from the associated file.
1287 std::error_code readImpl() override;
1288
1289 /// Return true if \p Buffer is in the format supported by this class.
1290 static bool hasFormat(const MemoryBuffer &Buffer);
1291
1292protected:
1293 std::error_code readNameTable();
1294 std::error_code readOneFunctionProfile(const InlineCallStack &InlineStack,
1295 bool Update, uint32_t Offset);
1296 std::error_code readFunctionProfiles();
1297 std::error_code skipNextWord();
1298 template <typename T> ErrorOr<T> readNumber();
1300
1301 /// Read the section tag and check that it's the same as \p Expected.
1302 std::error_code readSectionTag(uint32_t Expected);
1303
1304 /// GCOV buffer containing the profile.
1306
1307 /// Function names in this profile.
1308 std::vector<std::string> Names;
1309
1310 /// GCOV tags used to separate sections in the profile file.
1311 static const uint32_t GCOVTagAFDOFileNames = 0xaa000000;
1312 static const uint32_t GCOVTagAFDOFunction = 0xac000000;
1313};
1314
1315} // end namespace sampleprof
1316
1317} // end namespace llvm
1318
1319#endif // LLVM_PROFILEDATA_SAMPLEPROFREADER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
Provides ErrorOr<T> smart pointer.
This file defines the EytzingerTableSpan class, a non-owning view of a buffer formatted as a complete...
#define F(x, y, z)
Definition MD5.cpp:54
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static Error readString(StringRef Buffer, const char *&Src, size_t MaxSize, StringRef &Val, Twine Desc)
Read a null-terminated string at the position Src from Buffer, with maximum byte size of MaxSize (inc...
static constexpr StringLiteral Filename
#define P(N)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
This file contains library features backported from future STL versions.
This file defines the SmallVector class.
StringSet - A set-like wrapper for the StringMap.
Contains the forward declaration for vfs::FileSystem, as well as the IntrusiveRefCntPtrInfo specializ...
Value * RHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Diagnostic information for the sample profiler.
Represents either an error or a value T.
Definition ErrorOr.h:56
Tagged union holding either a T or a Error.
Definition Error.h:485
Non-owning view of a buffer formatted as a complete binary search tree in Eytzinger (breadth-first) o...
Definition Eytzinger.h:30
GCOVBuffer - A wrapper around MemoryBuffer to provide GCOV specific read operations.
Definition GCOV.h:74
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This interface provides simple read-only access to a block of memory, and provides simple methods for...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
FunctionId operator[](size_t Idx) const override
EytzingerSampleProfileNameTable(const support::ulittle64_t *Data, size_t NumNested, size_t NumFlat, size_t NumInlinees)
EytzingerTableSpan< support::ulittle64_t > getEytzingerSpan(bool IsNested) const override
bool contains(uint64_t GUID) const override
This class represents a function that is read from a sample profile.
Definition FunctionId.h:36
Representation of the samples collected for a function.
Definition SampleProf.h:853
static LLVM_ABI std::atomic< bool > UseMD5
Whether the profile uses MD5 to represent string.
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
This class is a wrapper to associative container MapT<KeyT, ValueT> using the hash value of the origi...
Definition HashKeyMap.h:52
LazySampleProfileNameTable(const uint8_t *Start, size_t Size)
FunctionId operator[](size_t Idx) const override
bool contains(uint64_t GUID) const override
FunctionId operator[](size_t Idx) const override
MD5SampleProfileNameTable(const std::vector< FunctionId > &Vec)
MD5SampleProfileNameTable(std::vector< FunctionId > &&Vec)
std::optional< uint64_t > lookup(uint64_t GUID) const
Query the offset table for the profile offset associated with the given GUID.
SampleProfileFuncOffsetTable & operator=(SampleProfileFuncOffsetTable &&)=delete
ArrayRef< support::ulittle32_t > getFuncOffsets() const
Direct read-only array (ArrayRef) of function offsets aligned parallel to the corresponding Eytzinger...
SampleProfileFuncOffsetTable(EytzingerModeT, EytzingerTableSpan< support::ulittle64_t > NameSpan, ArrayRef< support::ulittle32_t > FuncOffsetSpan)
void insert(uint64_t GUID, uint64_t Offset)
Insert a function GUID and its profile offset into the in-memory map.
SampleProfileFuncOffsetTable(InMemoryModeT, size_t InitialCapacity=0)
SampleProfileFuncOffsetTable(const SampleProfileFuncOffsetTable &)=delete
SampleProfileFuncOffsetTable & operator=(const SampleProfileFuncOffsetTable &)=delete
SampleProfileFuncOffsetTable(SampleProfileFuncOffsetTable &&)=delete
This class provides operator overloads to the map container using MD5 as the key type,...
iterator(const SampleProfileNameTable *Table, size_t Idx)
SampleProfileNameTable(SampleProfileNameTable &&)=delete
SampleProfileNameTable(const SampleProfileNameTable &)=delete
static const SetT & getOrCreateSet(std::optional< SetT > &Set, const RangeT &Range, ProjT Proj=ProjT())
std::optional< DenseSet< uint64_t > > GUIDSet
virtual bool contains(StringRef Key) const
SampleProfileNameTable & operator=(const SampleProfileNameTable &)=delete
virtual FunctionId operator[](size_t Idx) const =0
virtual bool contains(uint64_t GUID) const
virtual EytzingerTableSpan< support::ulittle64_t > getEytzingerSpan(bool IsNested) const
SampleProfileNameTable & operator=(SampleProfileNameTable &&)=delete
const uint8_t * Data
Points to the current location in the buffer.
std::unique_ptr< SampleProfileNameTable > NameTable
Function name table.
const uint64_t * MD5SampleContextStart
The starting address of the table of MD5 values of sample contexts.
bool contains(StringRef Key) const override
std::vector< SampleContextFrameVector > CSNameTable
CSNameTable is used to save full context vectors.
bool contains(uint64_t GUID) const override
SampleProfileReaderBinary(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_None)
std::vector< uint64_t > MD5SampleContextTable
Table to cache MD5 values of sample contexts corresponding to readSampleContextFromTable(),...
llvm::iterator_range< SampleProfileNameTable::iterator > getNameTable() const override
It includes all the names that have samples either in outline instance or inline instance.
const uint8_t * End
Points to the end of the buffer.
std::error_code readNameTableSecEytzinger(bool IsMD5, bool FixedLengthMD5)
std::error_code readEytzingerFuncOffsetTable(bool IsNested)
virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry)=0
std::error_code readFuncMetadata(DenseSet< FunctionSamples * > &Profiles)
std::vector< std::pair< SampleContext, uint64_t > > FuncOffsetList
The list version of FuncOffsetTable.
DenseSet< StringRef > FuncsToUse
The set containing the functions to use when compiling a module.
std::unique_ptr< ProfileSymbolList > ProfSymList
std::optional< SampleProfileFuncOffsetTable > FuncOffsetTable
The table mapping from a function context's MD5 to the offset of its FunctionSample towards file star...
std::error_code readNameTableSec(bool IsMD5, bool FixedLengthMD5, bool IsEytzinger=false)
bool useFuncOffsetList() const
Determine which container readFuncOffsetTable() should populate, the list FuncOffsetList or the map F...
std::unique_ptr< ProfileSymbolList > getProfileSymbolList() override
virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry)
std::error_code verifySPMagic(uint64_t Magic) override=0
SampleProfileReaderExtBinaryBase(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format)
std::error_code readFuncOffsetTable(bool IsEytzinger, bool IsNested)
std::error_code readNameTableSecLegacy(bool IsMD5, bool FixedLengthMD5)
bool hasCompositeProfileSection() const override
Return whether the section table contains a composite profile section.
std::error_code readHeader() override
Read and validate the file header.
SampleProfileReaderExtBinary(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_Ext_Binary)
GCOVBuffer GcovBuffer
GCOV buffer containing the profile.
std::vector< std::string > Names
Function names in this profile.
SampleProfileReaderGCC(std::unique_ptr< MemoryBuffer > B, LLVMContext &C)
static const uint32_t GCOVTagAFDOFileNames
GCOV tags used to separate sections in the profile file.
SampleProfileReaderItaniumRemapper remaps the profile data from a sample profile data reader,...
bool exist(StringRef FunctionName)
Query whether there is equivalent in the remapper which has been inserted.
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReaderItaniumRemapper > > create(StringRef Filename, vfs::FileSystem &FS, SampleProfileReader &Reader, LLVMContext &C)
Create a remapper from the given remapping file.
LLVM_ABI void applyRemapping(LLVMContext &Ctx)
Apply remappings to the profile read by Reader.
SampleProfileReaderItaniumRemapper(std::unique_ptr< MemoryBuffer > B, std::unique_ptr< SymbolRemappingReader > SRR, SampleProfileReader &R)
void insert(StringRef FunctionName)
Insert function name into remapper.
LLVM_ABI std::optional< StringRef > lookUpNameInProfile(StringRef FunctionName)
Return the equivalent name in the profile for FunctionName if it exists.
SampleProfileReaderRawBinary(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_Binary)
SampleProfileReaderText(std::unique_ptr< MemoryBuffer > B, LLVMContext &C)
void setProfileUseMD5() override
Text format sample profile does not support MD5 for now.
std::error_code readHeader() override
Read and validate the file header.
uint32_t MaskedBitFrom
Zero out the discriminator bits higher than bit MaskedBitFrom (0 based).
bool ReadVTableProf
If true, the profile has vtable profiles and reader should decode them to parse profiles correctly.
bool ProfileIsPreInlined
Whether function profile contains ShouldBeInlined contexts.
DenseMap< uint64_t, std::pair< const uint8_t *, const uint8_t * > > FuncMetadataIndex
SampleProfileMap & getProfiles()
Return all the profiles.
uint32_t CSProfileCount
Number of context-sensitive profiles.
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReader > > create(StringRef Filename, LLVMContext &C, vfs::FileSystem &FS, FSDiscriminatorPass P=FSDiscriminatorPass::Base, StringRef RemapFilename="")
Create a sample profile reader appropriate to the file format.
bool profileIsProbeBased() const
Whether input profile is based on pseudo probes.
FunctionSamples * getSamplesFor(const Function &F)
Return the samples collected for function F.
LLVM_ABI void dump(raw_ostream &OS=dbgs())
Print all the profiles on stream OS.
std::error_code dumpProfileTypeInfo(raw_ostream &OS)
Read the profile and print the structure of composite profile blocks.
bool useMD5() const
Return whether names in the profile are all MD5 numbers.
const Module * M
The current module being compiled if SampleProfileReader is used by compiler.
std::unique_ptr< MemoryBuffer > Buffer
Memory buffer holding the profile file.
std::unique_ptr< SampleProfileReaderItaniumRemapper > Remapper
bool ProfileHasAttribute
Whether the profile has attribute metadata.
void setFuncNameToProfNameMap(const HashKeyMap< DenseMap, FunctionId, FunctionId > &FPMap)
bool SkipFlatProf
If SkipFlatProf is true, skip functions marked with !Flat in text mode or sections with SecFlagFlat f...
bool profileIsPreInlined() const
Whether input profile contains ShouldBeInlined contexts.
std::error_code read()
The interface to read sample profiles from the associated file.
bool profileIsFS() const
Whether input profile is flow-sensitive.
ProfileSectionRange ProfileSecRange
Profile section most recently selected for on-demand loading.
SampleProfileReaderItaniumRemapper * getRemapper()
bool ProfileIsCS
Whether function profiles are context-sensitive flat profiles.
std::error_code read(const DenseSet< StringRef > &FuncsToUse)
Read sample profiles for the given functions.
bool ProfileIsMD5
Whether the profile uses MD5 for Sample Contexts and function names.
virtual bool contains(StringRef Key) const
static std::unique_ptr< ProfileSummary > takeSummary(SampleProfileReader &Reader)
Take ownership of the summary of this reader.
virtual llvm::iterator_range< SampleProfileNameTable::iterator > getNameTable() const
It includes all the names that have samples either in outline instance or inline instance.
ProfileSummary & getSummary() const
Return the profile summary.
const HashKeyMap< DenseMap, FunctionId, FunctionId > * FuncNameToProfNameMap
virtual bool hasCompositeProfileSection() const
Return whether the input contains a composite profile section.
SampleProfileFormat Format
The format of sample.
SampleProfileReader(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_None)
std::unique_ptr< ProfileSummary > Summary
Profile summary information.
virtual bool hasUniqSuffix()
Return whether any name in the profile contains ".__uniq." suffix.
LLVM_ABI void computeSummary()
Compute summary for this profile.
uint32_t getDiscriminatorMask() const
Get the bitmask the discriminators: For FS profiles, return the bit mask for this pass.
uint64_t getFormatVersion() const
Return the format version of the profile. For tests only.
bool HasUnknownProfileTypes
Whether reading skipped at least one unknown composite profile block.
virtual bool dumpSectionInfo(raw_ostream &OS=dbgs())
SampleProfileFormat getFormat() const
Return the profile format.
virtual void setProfileUseMD5()
Force the profile to use MD5 in Sample contexts, even if function names are present.
void setDiscriminatorMaskedBitFrom(FSDiscriminatorPass P)
Set the bits for FS discriminators.
virtual std::error_code read(const DenseSet< StringRef > &FuncsToUse, SampleProfileMap &Profiles)
Read sample profiles for the given functions and write them to the given profile map.
bool profileIsCS() const
Whether input profile is fully context-sensitive.
bool ProfileIsFS
Whether the function profiles use FS discriminators.
virtual bool collectFuncsFromModule()
Collect functions with definitions in Module M.
FunctionSamples * getSamplesFor(StringRef Fname)
Return the samples collected for function F.
virtual bool contains(uint64_t GUID) const
LLVM_ABI void dumpJson(raw_ostream &OS=dbgs())
Print all the profiles on stream OS in the JSON format.
SampleProfileMap Profiles
Map every function to its associated profile.
uint64_t FormatVersion
Format version of the profile.
virtual std::error_code readHeader()=0
Read and validate the file header.
void setSkipFlatProf(bool Skip)
Don't read profile without context if the flag is set.
LLVM_ABI void dumpFunctionProfile(const FunctionSamples &FS, raw_ostream &OS=dbgs())
Print the profile for FunctionSamples on stream OS.
bool ProfileIsProbeBased
Whether samples are collected based on pseudo probes.
bool hasUnknownProfileTypes() const
Return whether any unknown composite profile blocks were skipped.
void reportError(int64_t LineNumber, const Twine &Msg) const
Report a parse error message.
virtual std::unique_ptr< ProfileSymbolList > getProfileSymbolList()
raw_ostream * ProfileTypeInfoOS
Optional stream for composite block structure; null disables the output.
LLVMContext & Ctx
LLVM context used to emit diagnostics.
virtual std::error_code readImpl()=0
The implementaion to read sample profiles from the associated file.
bool contains(StringRef Key) const override
StringSampleProfileNameTable(const std::vector< FunctionId > &Vec)
StringSampleProfileNameTable(std::vector< FunctionId > &&Vec)
FunctionId operator[](size_t Idx) const override
The virtual file system interface.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr EytzingerModeT EytzingerMode
constexpr InMemoryModeT InMemoryMode
SmallVector< FunctionSamples *, 10 > InlineCallStack
SortedVectorMap< FunctionId, uint64_t, 0 > TypeCountMap
Key represents type of a C++ polymorphic class type by its vtable and value represents its counter.
Definition SampleProf.h:402
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition Endian.h:53
detail::packed_endian_specific_integral< uint64_t, llvm::endianness::little, unaligned > ulittle64_t
Definition Endian.h:273
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
static unsigned getFSPassBitEnd(sampleprof::FSDiscriminatorPass P)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
static unsigned getN1Bits(int N)
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
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
Tags to select the initialization mode of SampleProfileFuncOffsetTable.
A profile section retained for loading additional functions on demand.
bool IsComposite
Whether the retained section uses composite payload encoding.
const uint8_t * Start
First byte of the retained section.
const uint8_t * End
One-past-the-end byte of the retained section.