LLVM 24.0.0git
SampleProf.h
Go to the documentation of this file.
1//===- SampleProf.h - Sampling profiling format support ---------*- 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 common definitions used in the reading and writing of
10// sample profile data.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_PROFILEDATA_SAMPLEPROF_H
15#define LLVM_PROFILEDATA_SAMPLEPROF_H
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/Eytzinger.h"
20#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/IR/Function.h"
25#include "llvm/IR/GlobalValue.h"
30#include "llvm/Support/Debug.h"
33#include <algorithm>
34#include <cstdint>
35#include <list>
36#include <map>
37#include <sstream>
38#include <string>
39#include <system_error>
40#include <unordered_map>
41#include <utility>
42
43namespace llvm {
44
45class DILocation;
46class raw_ostream;
47
48LLVM_ABI const std::error_category &sampleprof_category();
49
68
69inline std::error_code make_error_code(sampleprof_error E) {
70 return std::error_code(static_cast<int>(E), sampleprof_category());
71}
72
74 sampleprof_error Result) {
75 // Prefer first error encountered as later errors may be secondary effects of
76 // the initial problem.
79 Accumulator = Result;
80 return Accumulator;
81}
82
83} // end namespace llvm
84
85namespace std {
86
87template <>
88struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
89
90} // end namespace std
91
92namespace llvm {
93namespace sampleprof {
94
95constexpr char kVTableProfPrefix[] = "vtables ";
96
99 SPF_Text = 0x1,
100 SPF_Compact_Binary = 0x2, // Deprecated
101 SPF_GCC = 0x3,
104};
105
111
113 return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
114 uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
115 uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
116 uint64_t('2') << (64 - 56) | uint64_t(Format);
117}
118
119// The oldest version of the extensible binary format we support.
120static constexpr uint64_t MinSupportedVersion = 103;
121
122// The default version of the extensible binary profile format written by the
123// compiler. We default to v103 as v104 is work in progress.
124static constexpr uint64_t DefaultVersion = 103;
125
126// The latest supported version of the extensible binary profile format.
127static constexpr uint64_t LatestVersion = 104;
128
129// Query if a given format version is supported by this compiler.
133
134// Unused. Retained for downstream uses only.
135LLVM_DEPRECATED("Use DefaultVersion or LatestVersion instead", "DefaultVersion")
136static inline uint64_t SPVersion() { return 103; }
137
138// Section Type used by SampleProfileExtBinaryBaseReader and
139// SampleProfileExtBinaryBaseWriter. Never change the existing
140// value of enum. Only append new ones.
153
154static inline std::string getSecName(SecType Type) {
155 switch (static_cast<int>(Type)) { // Avoid -Wcovered-switch-default
156 case SecInValid:
157 return "InvalidSection";
158 case SecProfSummary:
159 return "ProfileSummarySection";
160 case SecNameTable:
161 return "NameTableSection";
163 return "ProfileSymbolListSection";
165 return "FuncOffsetTableSection";
166 case SecFuncMetadata:
167 return "FunctionMetadata";
168 case SecCSNameTable:
169 return "CSNameTableSection";
170 case SecLBRProfile:
171 return "LBRProfileSection";
172 default:
173 return "UnknownSection";
174 }
175}
176
177// Entry type of section header table used by SampleProfileExtBinaryBaseReader
178// and SampleProfileExtBinaryBaseWriter.
184 // The index indicating the location of the current entry in
185 // SectionHdrLayout table.
187};
188
189// Flags common for all sections are defined here. In SecHdrTableEntry::Flags,
190// common flags will be saved in the lower 32bits and section specific flags
191// will be saved in the higher 32 bits.
194 SecFlagCompress = (1 << 0),
195 // Indicate the section contains only profile without context.
196 SecFlagFlat = (1 << 1)
197};
198
199// Section specific flags are defined here.
200// !!!Note: Everytime a new enum class is created here, please add
201// a new check in verifySecFlag.
204 SecFlagMD5Name = (1 << 0),
205 // Store MD5 in fixed length instead of ULEB128 so NameTable can be
206 // accessed like an array.
208 // Profile contains ".__uniq." suffix name. Compiler shouldn't strip
209 // the suffix when doing profile matching when seeing the flag.
211 // Name table is stored in 3-span Eytzinger layout (CS, Flat, Inlinees).
213};
214
215enum class EytzingerSpan : size_t { CS, Flat, Inlinee, NumSpans };
216
223 /// SecFlagPartial means the profile is for common/shared code.
224 /// The common profile is usually merged from profiles collected
225 /// from running other targets.
226 SecFlagPartial = (1 << 0),
227 /// SecFlagContext means this is context-sensitive flat profile for
228 /// CSSPGO
230 /// SecFlagFSDiscriminator means this profile uses flow-sensitive
231 /// discriminators.
233 /// SecFlagIsPreInlined means this profile contains ShouldBeInlined
234 /// contexts thus this is CS preinliner computed.
236
237 /// SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
239};
240
246
249 // Store function offsets in an order of contexts. The order ensures that
250 // callee contexts of a given context laid out next to it.
251 SecFlagOrdered = (1 << 0),
252};
253
254// Verify section specific flag is used for the correct section.
255template <class SecFlagType>
256static inline void verifySecFlag(SecType Type, SecFlagType Flag) {
257 // No verification is needed for common flags.
258 if (std::is_same<SecCommonFlags, SecFlagType>())
259 return;
260
261 // Verification starts here for section specific flag.
262 bool IsFlagLegal = false;
263 switch (Type) {
264 case SecNameTable:
265 IsFlagLegal = std::is_same<SecNameTableFlags, SecFlagType>();
266 break;
268 IsFlagLegal = std::is_same<SecProfileSymbolListFlags, SecFlagType>();
269 break;
270 case SecProfSummary:
271 IsFlagLegal = std::is_same<SecProfSummaryFlags, SecFlagType>();
272 break;
273 case SecFuncMetadata:
274 IsFlagLegal = std::is_same<SecFuncMetadataFlags, SecFlagType>();
275 break;
276 default:
278 IsFlagLegal = std::is_same<SecFuncOffsetFlags, SecFlagType>();
279 break;
280 }
281 if (!IsFlagLegal)
282 llvm_unreachable("Misuse of a flag in an incompatible section");
283}
284
285template <class SecFlagType>
286static inline void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
287 verifySecFlag(Entry.Type, Flag);
288 auto FVal = static_cast<uint64_t>(Flag);
289 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
290 Entry.Flags |= IsCommon ? FVal : (FVal << 32);
291}
292
293template <class SecFlagType>
294static inline void removeSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
295 verifySecFlag(Entry.Type, Flag);
296 auto FVal = static_cast<uint64_t>(Flag);
297 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
298 Entry.Flags &= ~(IsCommon ? FVal : (FVal << 32));
299}
300
301template <class SecFlagType>
302static inline bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag) {
303 verifySecFlag(Entry.Type, Flag);
304 auto FVal = static_cast<uint64_t>(Flag);
305 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
306 return Entry.Flags & (IsCommon ? FVal : (FVal << 32));
307}
308
309/// Represents the relative location of an instruction.
310///
311/// Instruction locations are specified by the line offset from the
312/// beginning of the function (marked by the line where the function
313/// header is) and the discriminator value within that line.
314///
315/// The discriminator value is useful to distinguish instructions
316/// that are on the same line but belong to different basic blocks
317/// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
320
321 LLVM_ABI void print(raw_ostream &OS) const;
322 LLVM_ABI void dump() const;
323
324 // Serialize the line location to the output stream using ULEB128 encoding.
325 LLVM_ABI void serialize(raw_ostream &OS) const;
326
327 bool operator<(const LineLocation &O) const {
328 return std::tie(LineOffset, Discriminator) <
329 std::tie(O.LineOffset, O.Discriminator);
330 }
331
332 bool operator==(const LineLocation &O) const {
333 return LineOffset == O.LineOffset && Discriminator == O.Discriminator;
334 }
335
336 bool operator!=(const LineLocation &O) const {
337 return LineOffset != O.LineOffset || Discriminator != O.Discriminator;
338 }
339
341 return ((uint64_t)Discriminator << 32) | LineOffset;
342 }
343
346};
347
349
350} // end namespace sampleprof
351
353 static unsigned getHashValue(const sampleprof::LineLocation &Val) {
355 }
356
359 return LHS == RHS;
360 }
361};
362
363namespace sampleprof {
364
365/// Key represents type of a C++ polymorphic class type by its vtable and value
366/// represents its counter.
367/// TODO: The class name FunctionId should be renamed to SymbolId in a refactor
368/// change.
369using TypeCountMap = std::map<FunctionId, uint64_t>;
370
371/// Write \p Map to the output stream. Keys are linearized using \p NameTable
372/// and written as ULEB128. Values are written as ULEB128 as well.
373LLVM_ABI std::error_code
375 const MapVector<FunctionId, uint32_t> &NameTable,
376 raw_ostream &OS);
377
378/// Representation of a single sample record.
379///
380/// A sample record is represented by a positive integer value, which
381/// indicates how frequently was the associated line location executed.
382///
383/// Additionally, if the associated location contains a function call,
384/// the record will hold a list of all the possible called targets and the types
385/// for virtual table dispatches. For direct calls, this will be the exact
386/// function being invoked. For indirect calls (function pointers, virtual table
387/// dispatch), this will be a list of one or more functions. For virtual table
388/// dispatches, this record will also hold the type of the object.
390public:
391 using CallTarget = std::pair<FunctionId, uint64_t>;
393 bool operator()(const CallTarget &LHS, const CallTarget &RHS) const {
394 if (LHS.second != RHS.second)
395 return LHS.second > RHS.second;
396
397 return LHS.first < RHS.first;
398 }
399 };
400
403 SampleRecord() = default;
404
405 /// Increment the number of samples for this record by \p S.
406 /// Optionally scale sample count \p S by \p Weight.
407 ///
408 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
409 /// around unsigned integers.
411 bool Overflowed;
412 NumSamples = SaturatingMultiplyAdd(S, Weight, NumSamples, &Overflowed);
413 return Overflowed ? sampleprof_error::counter_overflow
415 }
416
417 /// Decrease the number of samples for this record by \p S. Return the amout
418 /// of samples actually decreased.
420 if (S > NumSamples)
421 S = NumSamples;
422 NumSamples -= S;
423 return S;
424 }
425
426 /// Add called function \p F with samples \p S.
427 /// Optionally scale sample count \p S by \p Weight.
428 ///
429 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
430 /// around unsigned integers.
432 uint64_t Weight = 1) {
433 uint64_t &TargetSamples = CallTargets[F];
434 bool Overflowed;
435 TargetSamples =
436 SaturatingMultiplyAdd(S, Weight, TargetSamples, &Overflowed);
437 return Overflowed ? sampleprof_error::counter_overflow
439 }
440
441 /// Remove called function from the call target map. Return the target sample
442 /// count of the called function.
444 uint64_t Count = 0;
445 auto I = CallTargets.find(F);
446 if (I != CallTargets.end()) {
447 Count = I->second;
448 CallTargets.erase(I);
449 }
450 return Count;
451 }
452
453 /// Return true if this sample record contains function calls.
454 bool hasCalls() const { return !CallTargets.empty(); }
455
456 uint64_t getSamples() const { return NumSamples; }
457 const CallTargetMap &getCallTargets() const { return CallTargets; }
459 return sortCallTargets(CallTargets);
460 }
461
463 uint64_t Sum = 0;
464 for (const auto &I : CallTargets)
465 Sum += I.second;
466 return Sum;
467 }
468
469 /// Sort call targets in descending order of call frequency.
471 auto SortedTargets = llvm::to_vector_of<CallTarget>(Targets);
472 llvm::sort(SortedTargets, CallTargetComparator());
473 return SortedTargets;
474 }
475
476 /// Prorate call targets by a distribution factor.
477 static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets,
478 float DistributionFactor) {
479 CallTargetMap AdjustedTargets;
480 for (const auto &[Target, Frequency] : Targets) {
481 AdjustedTargets[Target] = Frequency * DistributionFactor;
482 }
483 return AdjustedTargets;
484 }
485
486 /// Merge the samples in \p Other into this record.
487 /// Optionally scale sample counts by \p Weight.
489 uint64_t Weight = 1);
490 LLVM_ABI void print(raw_ostream &OS, unsigned Indent) const;
491 LLVM_ABI void dump() const;
492 /// Serialize the sample record to the output stream using ULEB128 encoding.
493 /// The \p NameTable is used to map function names to their IDs.
494 LLVM_ABI std::error_code
496 const MapVector<FunctionId, uint32_t> &NameTable) const;
497
498 bool operator==(const SampleRecord &Other) const {
499 return NumSamples == Other.NumSamples && CallTargets == Other.CallTargets;
500 }
501
502 bool operator!=(const SampleRecord &Other) const { return !(*this == Other); }
503
504private:
505 uint64_t NumSamples = 0;
506 CallTargetMap CallTargets;
507};
508
510
511// State of context associated with FunctionSamples
513 UnknownContext = 0x0, // Profile without context
514 RawContext = 0x1, // Full context profile from input profile
515 SyntheticContext = 0x2, // Synthetic context created for context promotion
516 InlinedContext = 0x4, // Profile for context that is inlined into caller
517 MergedContext = 0x8 // Profile for context merged into base profile
518};
519
520// Attribute of context associated with FunctionSamples
523 ContextWasInlined = 0x1, // Leaf of context was inlined in previous build
524 ContextShouldBeInlined = 0x2, // Leaf of context should be inlined
526 0x4, // Leaf of context is duplicated into the base profile
527};
528
529// Represents a context frame with profile function and line location
533
535
538
539 bool operator==(const SampleContextFrame &That) const {
540 return Location == That.Location && Func == That.Func;
541 }
542
543 bool operator!=(const SampleContextFrame &That) const {
544 return !(*this == That);
545 }
546
547 std::string toString(bool OutputLineLocation) const {
548 std::ostringstream OContextStr;
549 OContextStr << Func.str();
550 if (OutputLineLocation) {
551 OContextStr << ":" << Location.LineOffset;
552 if (Location.Discriminator)
553 OContextStr << "." << Location.Discriminator;
554 }
555 return OContextStr.str();
556 }
557
559 // Context frame hash is heavily used in llvm-profgen context-sensitive
560 // pre-inliner. Use a lightweight hashing here to avoid speed regression.
561 uint64_t NameHash = 0;
562 if (Func.isStringRef())
563 NameHash = std::hash<std::string>{}(Func.str());
564 else
565 NameHash = Func.getHashCode();
566 uint64_t LocId = Location.getHashCode();
567 return NameHash + (LocId << 5) + LocId;
568 }
569};
570
571static inline hash_code hash_value(const SampleContextFrame &arg) {
572 return arg.getHashCode();
573}
574
577
583
584// Sample context for FunctionSamples. It consists of the calling context,
585// the function name and context state. Internally sample context is represented
586// using ArrayRef, which is also the input for constructing a `SampleContext`.
587// It can accept and represent both full context string as well as context-less
588// function name.
589// For a CS profile, a full context vector can look like:
590// `main:3 _Z5funcAi:1 _Z8funcLeafi`
591// For a base CS profile without calling context, the context vector should only
592// contain the leaf frame name.
593// For a non-CS profile, the context vector should be empty.
595public:
596 SampleContext() : State(UnknownContext), Attributes(ContextNone) {}
597
599 : Func(Name), State(UnknownContext), Attributes(ContextNone) {
600 assert(!Name.empty() && "Name is empty");
601 }
602
604 : Func(Func), State(UnknownContext), Attributes(ContextNone) {}
605
608 : Attributes(ContextNone) {
609 assert(!Context.empty() && "Context is empty");
610 setContext(Context, CState);
611 }
612
613 // Give a context string, decode and populate internal states like
614 // Function name, Calling context and context state. Example of input
615 // `ContextStr`: `[main:3 @ _Z5funcAi:1 @ _Z8funcLeafi]`
617 std::list<SampleContextFrameVector> &CSNameTable,
619 : Attributes(ContextNone) {
620 assert(!ContextStr.empty());
621 // Note that `[]` wrapped input indicates a full context string, otherwise
622 // it's treated as context-less function name only.
623 bool HasContext = ContextStr.starts_with("[");
624 if (!HasContext) {
625 State = UnknownContext;
626 Func = FunctionId(ContextStr);
627 } else {
628 CSNameTable.emplace_back();
629 SampleContextFrameVector &Context = CSNameTable.back();
630 createCtxVectorFromStr(ContextStr, Context);
631 setContext(Context, CState);
632 }
633 }
634
635 /// Create a context vector from a given context string and save it in
636 /// `Context`.
637 static void createCtxVectorFromStr(StringRef ContextStr,
638 SampleContextFrameVector &Context) {
639 // Remove encapsulating '[' and ']' if any
640 ContextStr = ContextStr.substr(1, ContextStr.size() - 2);
641 StringRef ContextRemain = ContextStr;
642 StringRef ChildContext;
643 FunctionId Callee;
644 while (!ContextRemain.empty()) {
645 auto ContextSplit = ContextRemain.split(" @ ");
646 ChildContext = ContextSplit.first;
647 ContextRemain = ContextSplit.second;
648 LineLocation CallSiteLoc(0, 0);
649 decodeContextString(ChildContext, Callee, CallSiteLoc);
650 Context.emplace_back(Callee, CallSiteLoc);
651 }
652 }
653
654 // Decode context string for a frame to get function name and location.
655 // `ContextStr` is in the form of `FuncName:StartLine.Discriminator`.
656 static void decodeContextString(StringRef ContextStr, FunctionId &Func,
657 LineLocation &LineLoc) {
658 // Get function name
659 auto EntrySplit = ContextStr.split(':');
660 Func = FunctionId(EntrySplit.first);
661
662 LineLoc = {0, 0};
663 if (!EntrySplit.second.empty()) {
664 // Get line offset, use signed int for getAsInteger so string will
665 // be parsed as signed.
666 int LineOffset = 0;
667 auto LocSplit = EntrySplit.second.split('.');
668 LocSplit.first.getAsInteger(10, LineOffset);
669 LineLoc.LineOffset = LineOffset;
670
671 // Get discriminator
672 if (!LocSplit.second.empty())
673 LocSplit.second.getAsInteger(10, LineLoc.Discriminator);
674 }
675 }
676
677 operator SampleContextFrames() const { return FullContext; }
678 bool hasAttribute(ContextAttributeMask A) { return Attributes & (uint32_t)A; }
679 void setAttribute(ContextAttributeMask A) { Attributes |= (uint32_t)A; }
680 uint32_t getAllAttributes() { return Attributes; }
681 void setAllAttributes(uint32_t A) { Attributes = A; }
682 bool hasState(ContextStateMask S) { return State & (uint32_t)S; }
683 void setState(ContextStateMask S) { State |= (uint32_t)S; }
684 void clearState(ContextStateMask S) { State &= (uint32_t)~S; }
685 bool hasContext() const { return State != UnknownContext; }
686 bool isBaseContext() const { return FullContext.size() == 1; }
687 FunctionId getFunction() const { return Func; }
688 SampleContextFrames getContextFrames() const { return FullContext; }
689
690 static std::string getContextString(SampleContextFrames Context,
691 bool IncludeLeafLineLocation = false) {
692 std::ostringstream OContextStr;
693 for (uint32_t I = 0; I < Context.size(); I++) {
694 if (OContextStr.str().size()) {
695 OContextStr << " @ ";
696 }
697 OContextStr << Context[I].toString(I != Context.size() - 1 ||
698 IncludeLeafLineLocation);
699 }
700 return OContextStr.str();
701 }
702
703 std::string toString() const {
704 if (!hasContext())
705 return Func.str();
706 return getContextString(FullContext, false);
707 }
708
710 if (hasContext())
712 return getFunction().getHashCode();
713 }
714
715 /// Set the name of the function and clear the current context.
716 void setFunction(FunctionId NewFunctionID) {
717 Func = NewFunctionID;
718 FullContext = SampleContextFrames();
719 State = UnknownContext;
720 }
721
723 ContextStateMask CState = RawContext) {
724 assert(CState != UnknownContext);
725 FullContext = Context;
726 Func = Context.back().Func;
727 State = CState;
728 }
729
730 bool operator==(const SampleContext &That) const {
731 return State == That.State && Func == That.Func &&
732 FullContext == That.FullContext;
733 }
734
735 bool operator!=(const SampleContext &That) const { return !(*this == That); }
736
737 bool operator<(const SampleContext &That) const {
738 if (State != That.State)
739 return State < That.State;
740
741 if (!hasContext()) {
742 return Func < That.Func;
743 }
744
745 uint64_t I = 0;
746 while (I < std::min(FullContext.size(), That.FullContext.size())) {
747 auto &Context1 = FullContext[I];
748 auto &Context2 = That.FullContext[I];
749 auto V = Context1.Func.compare(Context2.Func);
750 if (V)
751 return V < 0;
752 if (Context1.Location != Context2.Location)
753 return Context1.Location < Context2.Location;
754 I++;
755 }
756
757 return FullContext.size() < That.FullContext.size();
758 }
759
760 struct Hash {
761 uint64_t operator()(const SampleContext &Context) const {
762 return Context.getHashCode();
763 }
764 };
765
766 bool isPrefixOf(const SampleContext &That) const {
767 auto ThisContext = FullContext;
768 auto ThatContext = That.FullContext;
769 if (ThatContext.size() < ThisContext.size())
770 return false;
771 ThatContext = ThatContext.take_front(ThisContext.size());
772 // Compare Leaf frame first
773 if (ThisContext.back().Func != ThatContext.back().Func)
774 return false;
775 // Compare leading context
776 return ThisContext.drop_back() == ThatContext.drop_back();
777 }
778
779private:
780 // The function associated with this context. If CS profile, this is the leaf
781 // function.
782 FunctionId Func;
783 // Full context including calling context and leaf function name
784 SampleContextFrames FullContext;
785 // State of the associated sample profile
786 uint32_t State;
787 // Attribute of the associated sample profile
788 uint32_t Attributes;
789};
790
791static inline hash_code hash_value(const SampleContext &Context) {
792 return Context.getHashCode();
793}
794
795inline raw_ostream &operator<<(raw_ostream &OS, const SampleContext &Context) {
796 return OS << Context.toString();
797}
798
799class FunctionSamples;
801
802using BodySampleMap = std::map<LineLocation, SampleRecord>;
803// NOTE: Using a StringMap here makes parsed profiles consume around 17% more
804// memory, which is *very* significant for large profiles.
805using FunctionSamplesMap = std::map<FunctionId, FunctionSamples>;
806using CallsiteSampleMap = std::map<LineLocation, FunctionSamplesMap>;
807using CallsiteTypeMap = std::map<LineLocation, TypeCountMap>;
809
810/// Representation of the samples collected for a function.
811///
812/// This data structure contains all the collected samples for the body
813/// of a function. Each sample corresponds to a LineLocation instance
814/// within the body of the function.
816public:
817 FunctionSamples() = default;
818
819 LLVM_ABI void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
820 LLVM_ABI void dump() const;
821
823 bool Overflowed;
824 TotalSamples =
825 SaturatingMultiplyAdd(Num, Weight, TotalSamples, &Overflowed);
826 return Overflowed ? sampleprof_error::counter_overflow
828 }
829
831 if (TotalSamples < Num)
832 TotalSamples = 0;
833 else
834 TotalSamples -= Num;
835 }
836
837 void setTotalSamples(uint64_t Num) { TotalSamples = Num; }
838
839 void setHeadSamples(uint64_t Num) { TotalHeadSamples = Num; }
840
842 bool Overflowed;
843 TotalHeadSamples =
844 SaturatingMultiplyAdd(Num, Weight, TotalHeadSamples, &Overflowed);
845 return Overflowed ? sampleprof_error::counter_overflow
847 }
848
850 uint64_t Num, uint64_t Weight = 1) {
851 return BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(
852 Num, Weight);
853 }
854
856 uint32_t Discriminator,
857 FunctionId Func, uint64_t Num,
858 uint64_t Weight = 1) {
859 return BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(
860 Func, Num, Weight);
861 }
862
865 uint64_t Weight = 1) {
866 return BodySamples[Location].merge(SampleRecord, Weight);
867 }
868
869 // Remove a call target and decrease the body sample correspondingly. Return
870 // the number of body samples actually decreased.
872 uint32_t Discriminator,
873 FunctionId Func) {
874 uint64_t Count = 0;
875 auto I = BodySamples.find(LineLocation(LineOffset, Discriminator));
876 if (I != BodySamples.end()) {
877 Count = I->second.removeCalledTarget(Func);
878 Count = I->second.removeSamples(Count);
879 if (!I->second.getSamples())
880 BodySamples.erase(I);
881 }
882 return Count;
883 }
884
885 // Remove all call site samples for inlinees. This is needed when flattening
886 // a nested profile.
887 void removeAllCallsiteSamples() { CallsiteSamples.clear(); }
888
889 // Accumulate all call target samples to update the body samples.
891 for (auto &I : BodySamples) {
892 uint64_t TargetSamples = I.second.getCallTargetSum();
893 // It's possible that the body sample count can be greater than the call
894 // target sum. E.g, if some call targets are external targets, they won't
895 // be considered valid call targets, but the body sample count which is
896 // from lbr ranges can actually include them.
897 if (TargetSamples > I.second.getSamples())
898 I.second.addSamples(TargetSamples - I.second.getSamples());
899 }
900 }
901
902 // Accumulate all body samples to set total samples.
905 for (const auto &I : BodySamples)
906 addTotalSamples(I.second.getSamples());
907
908 for (auto &I : CallsiteSamples) {
909 for (auto &CS : I.second) {
910 CS.second.updateTotalSamples();
911 addTotalSamples(CS.second.getTotalSamples());
912 }
913 }
914 }
915
916 // Set current context and all callee contexts to be synthetic.
918 Context.setState(SyntheticContext);
919 for (auto &I : CallsiteSamples) {
920 for (auto &CS : I.second) {
921 CS.second.setContextSynthetic();
922 }
923 }
924 }
925
926 // Propagate the given attribute to this profile context and all callee
927 // contexts.
929 Context.setAttribute(Attr);
930 for (auto &I : CallsiteSamples) {
931 for (auto &CS : I.second) {
932 CS.second.setContextAttribute(Attr);
933 }
934 }
935 }
936
937 // Query the stale profile matching results and remap the location.
938 const LineLocation &mapIRLocToProfileLoc(const LineLocation &IRLoc) const {
939 // There is no remapping if the profile is not stale or the matching gives
940 // the same location.
941 if (!IRToProfileLocationMap)
942 return IRLoc;
943 const auto &ProfileLoc = IRToProfileLocationMap->find(IRLoc);
944 if (ProfileLoc != IRToProfileLocationMap->end())
945 return ProfileLoc->second;
946 return IRLoc;
947 }
948
949 /// Return the number of samples collected at the given location.
950 /// Each location is specified by \p LineOffset and \p Discriminator.
951 /// If the location is not found in profile, return error.
953 uint32_t Discriminator) const {
954 const auto &Ret = BodySamples.find(
955 mapIRLocToProfileLoc(LineLocation(LineOffset, Discriminator)));
956 if (Ret == BodySamples.end())
957 return std::error_code();
958 return Ret->second.getSamples();
959 }
960
961 /// Returns the call target map collected at a given location.
962 /// Each location is specified by \p LineOffset and \p Discriminator.
963 /// If the location is not found in profile, return error.
965 findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const {
966 const auto &Ret = BodySamples.find(
967 mapIRLocToProfileLoc(LineLocation(LineOffset, Discriminator)));
968 if (Ret == BodySamples.end())
969 return std::error_code();
970 return Ret->second.getCallTargets();
971 }
972
973 /// Returns the call target map collected at a given location specified by \p
974 /// CallSite. If the location is not found in profile, return error.
976 findCallTargetMapAt(const LineLocation &CallSite) const {
977 const auto &Ret = BodySamples.find(mapIRLocToProfileLoc(CallSite));
978 if (Ret == BodySamples.end())
979 return std::error_code();
980 return Ret->second.getCallTargets();
981 }
982
983 /// Return the function samples at the given callsite location.
985 return CallsiteSamples[mapIRLocToProfileLoc(Loc)];
986 }
987
988 /// Returns the FunctionSamplesMap at the given \p Loc.
989 const FunctionSamplesMap *
991 auto Iter = CallsiteSamples.find(mapIRLocToProfileLoc(Loc));
992 if (Iter == CallsiteSamples.end())
993 return nullptr;
994 return &Iter->second;
995 }
996
997 /// Returns the TypeCountMap for inlined callsites at the given \p Loc.
999 auto Iter = VirtualCallsiteTypeCounts.find(mapIRLocToProfileLoc(Loc));
1000 if (Iter == VirtualCallsiteTypeCounts.end())
1001 return nullptr;
1002 return &Iter->second;
1003 }
1004
1005 /// Returns a pointer to FunctionSamples at the given callsite location
1006 /// \p Loc with callee \p CalleeName. If no callsite can be found, relax
1007 /// the restriction to return the FunctionSamples at callsite location
1008 /// \p Loc with the maximum total sample count. If \p Remapper or \p
1009 /// FuncNameToProfNameMap is not nullptr, use them to find FunctionSamples
1010 /// with equivalent name as \p CalleeName.
1015 *FuncNameToProfNameMap = nullptr) const;
1016
1017 bool empty() const { return TotalSamples == 0; }
1018
1019 /// Return the total number of samples collected inside the function.
1020 uint64_t getTotalSamples() const { return TotalSamples; }
1021
1022 /// For top-level functions, return the total number of branch samples that
1023 /// have the function as the branch target (or 0 otherwise). This is the raw
1024 /// data fetched from the profile. This should be equivalent to the sample of
1025 /// the first instruction of the symbol. But as we directly get this info for
1026 /// raw profile without referring to potentially inaccurate debug info, this
1027 /// gives more accurate profile data and is preferred for standalone symbols.
1028 uint64_t getHeadSamples() const { return TotalHeadSamples; }
1029
1030 /// Return an estimate of the sample count of the function entry basic block.
1031 /// The function can be either a standalone symbol or an inlined function.
1032 /// For Context-Sensitive profiles, this will prefer returning the head
1033 /// samples (i.e. getHeadSamples()), if non-zero. Otherwise it estimates from
1034 /// the function body's samples or callsite samples.
1037 // For CS profile, if we already have more accurate head samples
1038 // counted by branch sample from caller, use them as entry samples.
1039 return getHeadSamples();
1040 }
1041 uint64_t Count = 0;
1042 // Use either BodySamples or CallsiteSamples which ever has the smaller
1043 // lineno.
1044 if (!BodySamples.empty() &&
1045 (CallsiteSamples.empty() ||
1046 BodySamples.begin()->first < CallsiteSamples.begin()->first))
1047 Count = BodySamples.begin()->second.getSamples();
1048 else if (!CallsiteSamples.empty()) {
1049 // An indirect callsite may be promoted to several inlined direct calls.
1050 // We need to get the sum of them.
1051 for (const auto &FuncSamples : CallsiteSamples.begin()->second)
1052 Count += FuncSamples.second.getHeadSamplesEstimate();
1053 }
1054 // Return at least 1 if total sample is not 0.
1055 return Count ? Count : TotalSamples > 0;
1056 }
1057
1058 /// Return all the samples collected in the body of the function.
1059 const BodySampleMap &getBodySamples() const { return BodySamples; }
1060
1061 /// Return all the callsite samples collected in the body of the function.
1063 return CallsiteSamples;
1064 }
1065
1066 /// Returns vtable access samples for the C++ types collected in this
1067 /// function.
1069 return VirtualCallsiteTypeCounts;
1070 }
1071
1072 /// Returns the vtable access samples for the C++ types for \p Loc.
1073 /// Under the hood, the caller-specified \p Loc will be un-drifted before the
1074 /// type sample lookup if possible.
1076 return VirtualCallsiteTypeCounts[mapIRLocToProfileLoc(Loc)];
1077 }
1078
1079 /// At location \p Loc, add a type sample for the given \p Type with
1080 /// \p Count. This function uses saturating add which clamp the result to
1081 /// maximum uint64_t (the counter type), and inserts the saturating add result
1082 /// to map. Returns counter_overflow to caller if the actual result is larger
1083 /// than maximum uint64_t.
1085 uint64_t Count) {
1086 auto &TypeCounts = getTypeSamplesAt(Loc);
1087 bool Overflowed = false;
1088 TypeCounts[Type] = SaturatingMultiplyAdd(Count, /* Weight= */ (uint64_t)1,
1089 TypeCounts[Type], &Overflowed);
1090 return Overflowed ? sampleprof_error::counter_overflow
1092 }
1093
1094 /// Scale \p Other sample counts by \p Weight and add the scaled result to the
1095 /// type samples for \p Loc. Under the hoold, the caller-provided \p Loc will
1096 /// be un-drifted before the type sample lookup if possible.
1097 /// typename T is either a std::map or a DenseMap.
1098 template <typename T>
1100 const T &Other,
1101 uint64_t Weight = 1) {
1102 static_assert((std::is_same_v<typename T::key_type, StringRef> ||
1103 std::is_same_v<typename T::key_type, FunctionId>) &&
1104 std::is_same_v<typename T::mapped_type, uint64_t>,
1105 "T must be a map with StringRef or FunctionId as key and "
1106 "uint64_t as value");
1107 TypeCountMap &TypeCounts = getTypeSamplesAt(Loc);
1108 bool Overflowed = false;
1109
1110 for (const auto &[Type, Count] : Other) {
1111 FunctionId TypeId(Type);
1112 bool RowOverflow = false;
1113 TypeCounts[TypeId] = SaturatingMultiplyAdd(
1114 Count, Weight, TypeCounts[TypeId], &RowOverflow);
1115 Overflowed |= RowOverflow;
1116 }
1117 return Overflowed ? sampleprof_error::counter_overflow
1119 }
1120
1121 /// Return the maximum of sample counts in a function body. When SkipCallSite
1122 /// is false, which is the default, the return count includes samples in the
1123 /// inlined functions. When SkipCallSite is true, the return count only
1124 /// considers the body samples.
1125 uint64_t getMaxCountInside(bool SkipCallSite = false) const {
1126 uint64_t MaxCount = 0;
1127 for (const auto &L : getBodySamples())
1128 MaxCount = std::max(MaxCount, L.second.getSamples());
1129 if (SkipCallSite)
1130 return MaxCount;
1131 for (const auto &C : getCallsiteSamples())
1132 for (const FunctionSamplesMap::value_type &F : C.second)
1133 MaxCount = std::max(MaxCount, F.second.getMaxCountInside());
1134 return MaxCount;
1135 }
1136
1137 /// Merge the samples in \p Other into this one.
1138 /// Optionally scale samples by \p Weight.
1141 if (!GUIDToFuncNameMap)
1142 GUIDToFuncNameMap = Other.GUIDToFuncNameMap;
1143 if (Context.getFunction().empty())
1144 Context = Other.getContext();
1145 if (FunctionHash == 0) {
1146 // Set the function hash code for the target profile.
1147 FunctionHash = Other.getFunctionHash();
1148 } else if (FunctionHash != Other.getFunctionHash()) {
1149 // The two profiles coming with different valid hash codes indicates
1150 // either:
1151 // 1. They are same-named static functions from different compilation
1152 // units (without using -unique-internal-linkage-names), or
1153 // 2. They are really the same function but from different compilations.
1154 // Let's bail out in either case for now, which means one profile is
1155 // dropped.
1157 }
1158
1159 mergeSampleProfErrors(Result,
1160 addTotalSamples(Other.getTotalSamples(), Weight));
1161 mergeSampleProfErrors(Result,
1162 addHeadSamples(Other.getHeadSamples(), Weight));
1163 for (const auto &I : Other.getBodySamples()) {
1164 const LineLocation &Loc = I.first;
1165 const SampleRecord &Rec = I.second;
1166 mergeSampleProfErrors(Result, BodySamples[Loc].merge(Rec, Weight));
1167 }
1168 for (const auto &I : Other.getCallsiteSamples()) {
1169 const LineLocation &Loc = I.first;
1171 for (const auto &Rec : I.second)
1172 mergeSampleProfErrors(Result,
1173 FSMap[Rec.first].merge(Rec.second, Weight));
1174 }
1175 for (const auto &[Loc, OtherTypeMap] : Other.getCallsiteTypeCounts())
1177 Result, addCallsiteVTableTypeProfAt(Loc, OtherTypeMap, Weight));
1178
1179 return Result;
1180 }
1181
1182 /// Recursively traverses all children, if the total sample count of the
1183 /// corresponding function is no less than \p Threshold, add its corresponding
1184 /// GUID to \p S. Also traverse the BodySamples to add hot CallTarget's GUID
1185 /// to \p S.
1189 uint64_t Threshold) const {
1190 if (TotalSamples <= Threshold)
1191 return;
1192 auto IsDeclaration = [](const Function *F) {
1193 return !F || F->isDeclaration();
1194 };
1195 if (IsDeclaration(SymbolMap.lookup(getFunction()))) {
1196 // Add to the import list only when it's defined out of module.
1197 S.insert(getGUID());
1198 }
1199 // Import hot CallTargets, which may not be available in IR because full
1200 // profile annotation cannot be done until backend compilation in ThinLTO.
1201 for (const auto &BS : BodySamples)
1202 for (const auto &TS : BS.second.getCallTargets())
1203 if (TS.second > Threshold) {
1204 const Function *Callee = SymbolMap.lookup(TS.first);
1205 if (IsDeclaration(Callee))
1206 S.insert(TS.first.getHashCode());
1207 }
1208 for (const auto &CS : CallsiteSamples)
1209 for (const auto &NameFS : CS.second)
1210 NameFS.second.findInlinedFunctions(S, SymbolMap, Threshold);
1211 }
1212
1213 /// Set the name of the function.
1214 void setFunction(FunctionId NewFunctionID) {
1215 Context.setFunction(NewFunctionID);
1216 }
1217
1218 /// Return the function name.
1219 FunctionId getFunction() const { return Context.getFunction(); }
1220
1221 /// Return the original function name.
1223
1224 void setFunctionHash(uint64_t Hash) { FunctionHash = Hash; }
1225
1226 uint64_t getFunctionHash() const { return FunctionHash; }
1227
1229 assert(IRToProfileLocationMap == nullptr && "this should be set only once");
1230 IRToProfileLocationMap = LTLM;
1231 }
1232
1233 /// Return the canonical name for a function, taking into account
1234 /// suffix elision policy attributes.
1236 const char *AttrName = "sample-profile-suffix-elision-policy";
1237 auto Attr = F.getFnAttribute(AttrName).getValueAsString();
1238 return getCanonicalFnName(F.getName(), Attr);
1239 }
1240
1241 /// Name suffixes which canonicalization should handle to avoid
1242 /// profile mismatch.
1243 static constexpr const char *LLVMSuffix = ".llvm.";
1244 static constexpr const char *PartSuffix = ".part.";
1245 static constexpr const char *UniqSuffix = ".__uniq.";
1246
1248 StringRef Attr = "selected") {
1249 // Note the sequence of the suffixes in the knownSuffixes array matters.
1250 // If suffix "A" is appended after the suffix "B", "A" should be in front
1251 // of "B" in knownSuffixes.
1252 const SmallVector<StringRef> KnownSuffixes{LLVMSuffix, PartSuffix,
1253 UniqSuffix};
1254 return getCanonicalFnName(FnName, KnownSuffixes, Attr);
1255 }
1256
1258 StringRef Attr = "selected") {
1259 // A local coroutine function from another CU can be promoted to a global
1260 // function during ThinLTO import. This will create a linkage name like
1261 // "_Zfoo.llvm.xxxx.cleanup". Remove the ".llvm." suffix after stripping all
1262 // the coroutine suffixes to avoid pseudo probe mismatch.
1263 const SmallVector<StringRef, 3> CoroSuffixes{".cleanup", ".destroy",
1264 ".resume", LLVMSuffix};
1265 return getCanonicalFnName(FnName, CoroSuffixes, Attr);
1266 }
1267
1269 ArrayRef<StringRef> Suffixes,
1270 StringRef Attr = "selected") {
1271 if (Attr == "" || Attr == "all")
1272 return FnName.split('.').first;
1273 if (Attr == "selected") {
1274 StringRef Cand(FnName);
1275 for (const auto Suffix : Suffixes) {
1276 // If the profile contains ".__uniq." suffix, don't strip the
1277 // suffix for names in the IR.
1279 continue;
1280 auto It = Cand.rfind(Suffix);
1281 if (It == StringRef::npos)
1282 continue;
1283 auto Dit = Cand.rfind('.');
1284 if (Dit == It || Dit == It + Suffix.size() - 1)
1285 Cand = Cand.substr(0, It);
1286 }
1287 return Cand;
1288 }
1289 if (Attr == "none")
1290 return FnName;
1291 assert(false && "internal error: unknown suffix elision policy");
1292 return FnName;
1293 }
1294
1295 /// Translate \p Func into its original name.
1296 /// When profile doesn't use MD5, \p Func needs no translation.
1297 /// When profile uses MD5, \p Func in current FunctionSamples
1298 /// is actually GUID of the original function name. getFuncName will
1299 /// translate \p Func in current FunctionSamples into its original name
1300 /// by looking up in the function map GUIDToFuncNameMap.
1301 /// If the original name doesn't exist in the map, return empty StringRef.
1303 if (!UseMD5)
1304 return Func.stringRef();
1305
1307 "GUIDToFuncNameMap needs to be populated first");
1308 return GUIDToFuncNameMap->lookup(Func.getHashCode());
1309 }
1310
1311 /// Returns the line offset to the start line of the subprogram.
1312 /// We assume that a single function will not exceed 65535 LOC.
1313 LLVM_ABI static unsigned getOffset(const DILocation *DIL);
1314
1315 /// Returns a unique call site identifier for a given debug location of a call
1316 /// instruction. This is wrapper of two scenarios, the probe-based profile and
1317 /// regular profile, to hide implementation details from the sample loader and
1318 /// the context tracker.
1320 bool ProfileIsFS = false);
1321
1322 /// Returns a unique hash code for a combination of a callsite location and
1323 /// the callee function name.
1324 /// Guarantee MD5 and non-MD5 representation of the same function results in
1325 /// the same hash.
1327 const LineLocation &Callsite) {
1328 return SampleContextFrame(Callee, Callsite).getHashCode();
1329 }
1330
1331 /// Get the FunctionSamples of the inline instance where DIL originates
1332 /// from.
1333 ///
1334 /// The FunctionSamples of the instruction (Machine or IR) associated to
1335 /// \p DIL is the inlined instance in which that instruction is coming from.
1336 /// We traverse the inline stack of that instruction, and match it with the
1337 /// tree nodes in the profile.
1338 ///
1339 /// \returns the FunctionSamples pointer to the inlined instance.
1340 /// If \p Remapper or \p FuncNameToProfNameMap is not nullptr, it will be used
1341 /// to find matching FunctionSamples with not exactly the same but equivalent
1342 /// name.
1345 SampleProfileReaderItaniumRemapper *Remapper = nullptr,
1347 *FuncNameToProfNameMap = nullptr) const;
1348
1350
1352
1354
1355 SampleContext &getContext() const { return Context; }
1356
1357 void setContext(const SampleContext &FContext) { Context = FContext; }
1358
1359 /// Whether the profile uses MD5 to represent string.
1360 LLVM_ABI static bool UseMD5;
1361
1362 /// Whether the profile contains any ".__uniq." suffix in a name.
1364
1365 /// If this profile uses flow sensitive discriminators.
1367
1368 /// GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
1369 /// all the function symbols defined or declared in current module.
1371
1372 /// Return the GUID of the context's name. If the context is already using
1373 /// MD5, don't hash it again.
1374 uint64_t getGUID() const { return getFunction().getHashCode(); }
1375
1376 // Find all the names in the current FunctionSamples including names in
1377 // all the inline instances and names of call targets.
1378 LLVM_ABI void findAllNames(DenseSet<FunctionId> &NameSet) const;
1379
1380 bool operator==(const FunctionSamples &Other) const {
1381 return (GUIDToFuncNameMap == Other.GUIDToFuncNameMap ||
1382 (GUIDToFuncNameMap && Other.GUIDToFuncNameMap &&
1383 *GUIDToFuncNameMap == *Other.GUIDToFuncNameMap)) &&
1384 FunctionHash == Other.FunctionHash && Context == Other.Context &&
1385 TotalSamples == Other.TotalSamples &&
1386 TotalHeadSamples == Other.TotalHeadSamples &&
1387 BodySamples == Other.BodySamples &&
1388 CallsiteSamples == Other.CallsiteSamples;
1389 }
1390
1391 bool operator!=(const FunctionSamples &Other) const {
1392 return !(*this == Other);
1393 }
1394
1395private:
1396 /// CFG hash value for the function.
1397 uint64_t FunctionHash = 0;
1398
1399 /// Calling context for function profile
1400 mutable SampleContext Context;
1401
1402 /// Total number of samples collected inside this function.
1403 ///
1404 /// Samples are cumulative, they include all the samples collected
1405 /// inside this function and all its inlined callees.
1406 uint64_t TotalSamples = 0;
1407
1408 /// Total number of samples collected at the head of the function.
1409 /// This is an approximation of the number of calls made to this function
1410 /// at runtime.
1411 uint64_t TotalHeadSamples = 0;
1412
1413 /// Map instruction locations to collected samples.
1414 ///
1415 /// Each entry in this map contains the number of samples
1416 /// collected at the corresponding line offset. All line locations
1417 /// are an offset from the start of the function.
1418 BodySampleMap BodySamples;
1419
1420 /// Map call sites to collected samples for the called function.
1421 ///
1422 /// Each entry in this map corresponds to all the samples
1423 /// collected for the inlined function call at the given
1424 /// location. For example, given:
1425 ///
1426 /// void foo() {
1427 /// 1 bar();
1428 /// ...
1429 /// 8 baz();
1430 /// }
1431 ///
1432 /// If the bar() and baz() calls were inlined inside foo(), this
1433 /// map will contain two entries. One for all the samples collected
1434 /// in the call to bar() at line offset 1, the other for all the samples
1435 /// collected in the call to baz() at line offset 8.
1436 CallsiteSampleMap CallsiteSamples;
1437
1438 /// Map a virtual callsite to the list of accessed vtables and vtable counts.
1439 /// The callsite is referenced by its source location.
1440 ///
1441 /// For example, given:
1442 ///
1443 /// void foo() {
1444 /// ...
1445 /// 5 inlined_vcall_bar();
1446 /// ...
1447 /// 5 inlined_vcall_baz();
1448 /// ...
1449 /// 200 inlined_vcall_qux();
1450 /// }
1451 /// This map will contain two entries. One with two types for line offset 5
1452 /// and one with one type for line offset 200.
1453 CallsiteTypeMap VirtualCallsiteTypeCounts;
1454
1455 /// IR to profile location map generated by stale profile matching.
1456 ///
1457 /// Each entry is a mapping from the location on current build to the matched
1458 /// location in the "stale" profile. For example:
1459 /// Profiled source code:
1460 /// void foo() {
1461 /// 1 bar();
1462 /// }
1463 ///
1464 /// Current source code:
1465 /// void foo() {
1466 /// 1 // Code change
1467 /// 2 bar();
1468 /// }
1469 /// Supposing the stale profile matching algorithm generated the mapping [2 ->
1470 /// 1], the profile query using the location of bar on the IR which is 2 will
1471 /// be remapped to 1 and find the location of bar in the profile.
1472 const LocToLocMap *IRToProfileLocationMap = nullptr;
1473};
1474
1475/// Get the proper representation of a string according to whether the
1476/// current Format uses MD5 to represent the string.
1478 if (Name.empty() || !FunctionSamples::UseMD5)
1479 return FunctionId(Name);
1481}
1482
1484
1485/// This class provides operator overloads to the map container using MD5 as the
1486/// key type, so that existing code can still work in most cases using
1487/// SampleContext as key.
1488/// Note: when populating container, make sure to assign the SampleContext to
1489/// the mapped value immediately because the key no longer holds it.
1491 : public HashKeyMap<std::unordered_map, SampleContext, FunctionSamples> {
1492public:
1493 // Convenience method because this is being used in many places. Set the
1494 // FunctionSamples' context if its newly inserted.
1496 auto Ret = try_emplace(Ctx, FunctionSamples());
1497 if (Ret.second)
1498 Ret.first->second.setContext(Ctx);
1499 return Ret.first->second;
1500 }
1501
1506
1511
1512 size_t erase(const SampleContext &Ctx) {
1513 return HashKeyMap<std::unordered_map, SampleContext,
1515 }
1516
1517 size_t erase(const key_type &Key) { return base_type::erase(Key); }
1518
1519 iterator erase(iterator It) { return base_type::erase(It); }
1520};
1521
1522using NameFunctionSamples = std::pair<hash_code, const FunctionSamples *>;
1523
1524LLVM_ABI void
1525sortFuncProfiles(const SampleProfileMap &ProfileMap,
1526 std::vector<NameFunctionSamples> &SortedProfiles);
1527
1528/// Sort a LocationT->SampleT map by LocationT.
1529///
1530/// It produces a sorted list of <LocationT, SampleT> records by ascending
1531/// order of LocationT.
1532template <class LocationT, class SampleT> class SampleSorter {
1533public:
1534 using SamplesWithLoc = std::pair<const LocationT, SampleT>;
1536
1537 SampleSorter(const std::map<LocationT, SampleT> &Samples) {
1538 for (const auto &I : Samples)
1539 V.push_back(&I);
1540 llvm::stable_sort(V, [](const SamplesWithLoc *A, const SamplesWithLoc *B) {
1541 return A->first < B->first;
1542 });
1543 }
1544
1545 const SamplesWithLocList &get() const { return V; }
1546
1547private:
1549};
1550
1551/// SampleContextTrimmer impelements helper functions to trim, merge cold
1552/// context profiles. It also supports context profile canonicalization to make
1553/// sure ProfileMap's key is consistent with FunctionSample's name/context.
1555public:
1556 SampleContextTrimmer(SampleProfileMap &Profiles) : ProfileMap(Profiles) {};
1557 // Trim and merge cold context profile when requested. TrimBaseProfileOnly
1558 // should only be effective when TrimColdContext is true. On top of
1559 // TrimColdContext, TrimBaseProfileOnly can be used to specify to trim all
1560 // cold profiles or only cold base profiles. Trimming base profiles only is
1561 // mainly to honor the preinliner decsion. Note that when MergeColdContext is
1562 // true, preinliner decsion is not honored anyway so TrimBaseProfileOnly will
1563 // be ignored.
1565 bool TrimColdContext,
1566 bool MergeColdContext,
1567 uint32_t ColdContextFrameLength,
1568 bool TrimBaseProfileOnly);
1569
1570private:
1571 SampleProfileMap &ProfileMap;
1572};
1573
1574/// Helper class for profile conversion.
1575///
1576/// It supports full context-sensitive profile to nested profile conversion,
1577/// nested profile to flatten profile conversion, etc.
1579public:
1581 // Convert a full context-sensitive flat sample profile into a nested sample
1582 // profile.
1584 struct FrameNode {
1586 FunctionSamples *FSamples = nullptr,
1587 LineLocation CallLoc = {0, 0})
1588 : FuncName(FName), FuncSamples(FSamples), CallSiteLoc(CallLoc) {};
1589
1590 // Map line+discriminator location to child frame
1591 std::map<uint64_t, FrameNode> AllChildFrames;
1592 // Function name for current frame
1594 // Function Samples for current frame
1596 // Callsite location in parent context
1598
1600 FunctionId CalleeName);
1601 };
1602
1603 static void flattenProfile(SampleProfileMap &ProfileMap,
1604 bool ProfileIsCS = false) {
1605 SampleProfileMap TmpProfiles;
1606 flattenProfile(ProfileMap, TmpProfiles, ProfileIsCS);
1607 ProfileMap = std::move(TmpProfiles);
1608 }
1609
1610 static void flattenProfile(const SampleProfileMap &InputProfiles,
1611 SampleProfileMap &OutputProfiles,
1612 bool ProfileIsCS = false) {
1613 if (ProfileIsCS) {
1614 for (const auto &I : InputProfiles) {
1615 // Retain the profile name and clear the full context for each function
1616 // profile.
1617 FunctionSamples &FS = OutputProfiles.create(I.second.getFunction());
1618 FS.merge(I.second);
1619 }
1620 } else {
1621 for (const auto &I : InputProfiles)
1622 flattenNestedProfile(OutputProfiles, I.second);
1623 }
1624 }
1625
1626private:
1627 static void flattenNestedProfile(SampleProfileMap &OutputProfiles,
1628 const FunctionSamples &FS) {
1629 // To retain the context, checksum, attributes of the original profile, make
1630 // a copy of it if no profile is found.
1631 SampleContext &Context = FS.getContext();
1632 auto Ret = OutputProfiles.try_emplace(Context, FS);
1633 FunctionSamples &Profile = Ret.first->second;
1634 if (Ret.second) {
1635 // Clear nested inlinees' samples for the flattened copy. These inlinees
1636 // will have their own top-level entries after flattening.
1637 Profile.removeAllCallsiteSamples();
1638 // We recompute TotalSamples later, so here set to zero.
1639 Profile.setTotalSamples(0);
1640 } else {
1641 for (const auto &[LineLocation, SampleRecord] : FS.getBodySamples()) {
1642 Profile.addSampleRecord(LineLocation, SampleRecord);
1643 }
1644 }
1645
1646 assert(Profile.getCallsiteSamples().empty() &&
1647 "There should be no inlinees' profiles after flattening.");
1648
1649 // TotalSamples might not be equal to the sum of all samples from
1650 // BodySamples and CallsiteSamples. So here we use "TotalSamples =
1651 // Original_TotalSamples - All_of_Callsite_TotalSamples +
1652 // All_of_Callsite_HeadSamples" to compute the new TotalSamples.
1653 uint64_t TotalSamples = FS.getTotalSamples();
1654
1655 for (const auto &I : FS.getCallsiteSamples()) {
1656 for (const auto &Callee : I.second) {
1657 const auto &CalleeProfile = Callee.second;
1658 // Add body sample.
1659 Profile.addBodySamples(I.first.LineOffset, I.first.Discriminator,
1660 CalleeProfile.getHeadSamplesEstimate());
1661 // Add callsite sample.
1662 Profile.addCalledTargetSamples(I.first.LineOffset,
1663 I.first.Discriminator,
1664 CalleeProfile.getFunction(),
1665 CalleeProfile.getHeadSamplesEstimate());
1666 // Update total samples.
1667 TotalSamples = TotalSamples >= CalleeProfile.getTotalSamples()
1668 ? TotalSamples - CalleeProfile.getTotalSamples()
1669 : 0;
1670 TotalSamples += CalleeProfile.getHeadSamplesEstimate();
1671 // Recursively convert callee profile.
1672 flattenNestedProfile(OutputProfiles, CalleeProfile);
1673 }
1674 }
1675 Profile.addTotalSamples(TotalSamples);
1676
1677 Profile.setHeadSamples(Profile.getHeadSamplesEstimate());
1678 }
1679
1680 // Nest all children profiles into the profile of Node.
1681 void convertCSProfiles(FrameNode &Node);
1682 FrameNode *getOrCreateContextPath(const SampleContext &Context);
1683
1684 SampleProfileMap &ProfileMap;
1685 FrameNode RootFrame;
1686};
1687
1688/// ProfileSymbolList records the list of function symbols shown up
1689/// in the binary used to generate the profile. It is useful to
1690/// to discriminate a function being so cold as not to shown up
1691/// in the profile and a function newly added.
1693public:
1694 /// copy indicates whether we need to copy the underlying memory
1695 /// for the input Name.
1696 void add(StringRef Name, bool Copy = false) {
1697 if (!Copy) {
1698 Syms.insert(Name);
1699 return;
1700 }
1701 Syms.insert(Name.copy(Allocator));
1702 }
1703
1704 bool contains(StringRef Name) const {
1705 return IsMD5 ? ColdGUIDTable.contains(llvm::MD5Hash(Name))
1706 : Syms.count(Name);
1707 }
1708
1710 assert(!List.IsMD5 &&
1711 "Merging pre-hashed MD5 ProfileSymbolList not yet implemented");
1712 for (auto Sym : List.Syms)
1713 add(Sym, true);
1714 }
1715
1716 unsigned size() const { return IsMD5 ? ColdGUIDTable.size() : Syms.size(); }
1717 void reserve(size_t Size) { Syms.reserve(Size); }
1718
1719 void setToCompress(bool TC) { ToCompress = TC; }
1720 bool toCompress() { return ToCompress; }
1721
1722 std::vector<uint64_t> collectGUIDs() const {
1723 assert(!IsMD5 &&
1724 "Collecting GUIDs from existing MD5 table not yet implemented");
1725 std::vector<uint64_t> Keys;
1726 Keys.reserve(Syms.size());
1728 llvm::sort(Keys);
1729 Keys.erase(llvm::unique(Keys), Keys.end());
1730 return Keys;
1731 }
1732
1734 assert(Syms.empty() &&
1735 "Setting ColdGUIDTable shadows existing strings in Syms");
1736 ColdGUIDTable = Table;
1737 IsMD5 = true;
1738 }
1740 assert(IsMD5 && "Retrieving ColdGUIDTable from non-MD5 ProfileSymbolList");
1741 return ColdGUIDTable;
1742 }
1743 bool isMD5() const { return IsMD5; }
1744
1745 LLVM_ABI std::error_code read(const uint8_t *Data, uint64_t ListSize);
1746 LLVM_ABI std::error_code write(raw_ostream &OS);
1747 LLVM_ABI void dump(raw_ostream &OS = dbgs()) const;
1748
1749private:
1750 bool IsMD5 = false;
1751 // Determine whether or not to compress the symbol list when
1752 // writing it into profile. The variable is unused when the symbol
1753 // list is read from an existing profile.
1754 bool ToCompress = false;
1758};
1759
1760} // end namespace sampleprof
1761
1762using namespace sampleprof;
1763// Provide DenseMapInfo for SampleContext.
1764template <> struct DenseMapInfo<SampleContext> {
1765 static unsigned getHashValue(const SampleContext &Val) {
1766 return Val.getHashCode();
1767 }
1768
1769 static bool isEqual(const SampleContext &LHS, const SampleContext &RHS) {
1770 return LHS == RHS;
1771 }
1772};
1773
1774// Prepend "__uniq" before the hash for tools like profilers to understand
1775// that this symbol is of internal linkage type. The "__uniq" is the
1776// pre-determined prefix that is used to tell tools that this symbol was
1777// created with -funique-internal-linkage-symbols and the tools can strip or
1778// keep the prefix as needed.
1779inline std::string getUniqueInternalLinkagePostfix(const StringRef &FName) {
1780 llvm::MD5 Md5;
1781 Md5.update(FName);
1783 Md5.final(R);
1784 SmallString<32> Str;
1786 // Convert MD5hash to Decimal. Demangler suffixes can either contain
1787 // numbers or characters but not both.
1788 llvm::APInt IntHash(128, Str.str(), 16);
1789 return toString(IntHash, /* Radix = */ 10, /* Signed = */ false)
1790 .insert(0, FunctionSamples::UniqSuffix);
1791}
1792
1793} // end namespace llvm
1794
1795#endif // LLVM_PROFILEDATA_SAMPLEPROF_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
always inline
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DEPRECATED(MSG, FIX)
Definition Compiler.h:254
#define LLVM_ABI
Definition Compiler.h:215
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Provides ErrorOr<T> smart pointer.
This file defines the EytzingerTableSpan class, a non-owning view of a buffer formatted as a complete...
Defines HashKeyMap template.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Load MIR Sample Profile
static cl::opt< unsigned > ColdCountThreshold("mfs-count-threshold", cl::desc("Minimum number of times a block must be executed to be retained."), cl::init(1), cl::Hidden)
This file implements a map that provides insertion order iteration.
#define T
Defines FunctionId class.
Basic Register Allocator
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition ArrayRef.h:218
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
Definition ArrayRef.h:200
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Represents either an error or a value T.
Definition ErrorOr.h:56
Non-owning view of a buffer formatted as a complete binary search tree in Eytzinger (breadth-first) o...
Definition Eytzinger.h:30
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
static LLVM_ABI void stringifyResult(MD5Result &Result, SmallVectorImpl< char > &Str)
Translates the bytes in Res to a hex string that is deposited into Str.
Definition MD5.cpp:286
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:233
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
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
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
static constexpr size_t npos
Definition StringRef.h:58
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
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
Definition StringRef.h:365
Target - Wrapper for Target specific information.
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
An opaque object representing a hash code.
Definition Hashing.h:77
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This class represents a function that is read from a sample profile.
Definition FunctionId.h:36
uint64_t getHashCode() const
Get hash code of this object.
Definition FunctionId.h:123
Representation of the samples collected for a function.
Definition SampleProf.h:815
void setTotalSamples(uint64_t Num)
Definition SampleProf.h:837
static LLVM_ABI bool ProfileIsPreInlined
void setContextAttribute(ContextAttributeMask Attr)
Definition SampleProf.h:928
LLVM_ABI const FunctionSamples * findFunctionSamples(const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper=nullptr, const HashKeyMap< DenseMap, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const
Get the FunctionSamples of the inline instance where DIL originates from.
bool operator!=(const FunctionSamples &Other) const
void setHeadSamples(uint64_t Num)
Definition SampleProf.h:839
sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:822
static constexpr const char * UniqSuffix
static StringRef getCanonicalFnName(StringRef FnName, StringRef Attr="selected")
sampleprof_error addTypeSamplesAt(const LineLocation &Loc, FunctionId Type, uint64_t Count)
At location Loc, add a type sample for the given Type with Count.
LLVM_ABI const FunctionSamples * findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName, SampleProfileReaderItaniumRemapper *Remapper, const HashKeyMap< DenseMap, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const
Returns a pointer to FunctionSamples at the given callsite location Loc with callee CalleeName.
bool operator==(const FunctionSamples &Other) const
static constexpr const char * PartSuffix
static uint64_t getCallSiteHash(FunctionId Callee, const LineLocation &Callsite)
Returns a unique hash code for a combination of a callsite location and the callee function name.
static StringRef getCanonicalCoroFnName(StringRef FnName, StringRef Attr="selected")
const FunctionSamplesMap * findFunctionSamplesMapAt(const LineLocation &Loc) const
Returns the FunctionSamplesMap at the given Loc.
Definition SampleProf.h:990
uint64_t getMaxCountInside(bool SkipCallSite=false) const
Return the maximum of sample counts in a function body.
void removeTotalSamples(uint64_t Num)
Definition SampleProf.h:830
uint64_t getHeadSamples() const
For top-level functions, return the total number of branch samples that have the function as the bran...
void setFunction(FunctionId NewFunctionID)
Set the name of the function.
ErrorOr< uint64_t > findSamplesAt(uint32_t LineOffset, uint32_t Discriminator) const
Return the number of samples collected at the given location.
Definition SampleProf.h:952
static LLVM_ABI bool ProfileIsCS
ErrorOr< const SampleRecord::CallTargetMap & > findCallTargetMapAt(const LineLocation &CallSite) const
Returns the call target map collected at a given location specified by CallSite.
Definition SampleProf.h:976
const LineLocation & mapIRLocToProfileLoc(const LineLocation &IRLoc) const
Definition SampleProf.h:938
static StringRef getCanonicalFnName(StringRef FnName, ArrayRef< StringRef > Suffixes, StringRef Attr="selected")
FunctionId getFunction() const
Return the function name.
const CallsiteTypeMap & getCallsiteTypeCounts() const
Returns vtable access samples for the C++ types collected in this function.
sampleprof_error addCallsiteVTableTypeProfAt(const LineLocation &Loc, const T &Other, uint64_t Weight=1)
Scale Other sample counts by Weight and add the scaled result to the type samples for Loc.
static constexpr const char * LLVMSuffix
Name suffixes which canonicalization should handle to avoid profile mismatch.
StringRef getFuncName(FunctionId Func) const
Translate Func into its original name.
const TypeCountMap * findCallsiteTypeSamplesAt(const LineLocation &Loc) const
Returns the TypeCountMap for inlined callsites at the given Loc.
Definition SampleProf.h:998
sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:841
sampleprof_error addSampleRecord(LineLocation Location, const SampleRecord &SampleRecord, uint64_t Weight=1)
Definition SampleProf.h:863
uint64_t removeCalledTargetAndBodySample(uint32_t LineOffset, uint32_t Discriminator, FunctionId Func)
Definition SampleProf.h:871
DenseMap< uint64_t, StringRef > * GUIDToFuncNameMap
GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for all the function symbols define...
sampleprof_error addCalledTargetSamples(uint32_t LineOffset, uint32_t Discriminator, FunctionId Func, uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:855
FunctionSamplesMap & functionSamplesAt(const LineLocation &Loc)
Return the function samples at the given callsite location.
Definition SampleProf.h:984
static LLVM_ABI bool ProfileIsProbeBased
void setIRToProfileLocationMap(const LocToLocMap *LTLM)
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
StringRef getFuncName() const
Return the original function name.
LLVM_ABI void findAllNames(DenseSet< FunctionId > &NameSet) const
sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator, uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:849
static LLVM_ABI unsigned getOffset(const DILocation *DIL)
Returns the line offset to the start line of the subprogram.
void setFunctionHash(uint64_t Hash)
static LLVM_ABI bool ProfileIsFS
If this profile uses flow sensitive discriminators.
ErrorOr< const SampleRecord::CallTargetMap & > findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const
Returns the call target map collected at a given location.
Definition SampleProf.h:965
SampleContext & getContext() const
static LLVM_ABI bool HasUniqSuffix
Whether the profile contains any ".__uniq." suffix in a name.
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
LLVM_ABI void print(raw_ostream &OS=dbgs(), unsigned Indent=0) const
Print the samples collected for a function on stream OS.
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
void setContext(const SampleContext &FContext)
static LLVM_ABI LineLocation getCallSiteIdentifier(const DILocation *DIL, bool ProfileIsFS=false)
Returns a unique call site identifier for a given debug location of a call instruction.
void findInlinedFunctions(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, uint64_t Threshold) const
Recursively traverses all children, if the total sample count of the corresponding function is no les...
uint64_t getHeadSamplesEstimate() const
Return an estimate of the sample count of the function entry basic block.
uint64_t getGUID() const
Return the GUID of the context's name.
TypeCountMap & getTypeSamplesAt(const LineLocation &Loc)
Returns the vtable access samples for the C++ types for Loc.
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
static LLVM_ABI bool UseMD5
Whether the profile uses MD5 to represent string.
This class is a wrapper to associative container MapT<KeyT, ValueT> using the hash value of the origi...
Definition HashKeyMap.h:52
std::pair< iterator, bool > try_emplace(const key_type &Hash, const original_key_type &Key, Ts &&...Args)
Definition HashKeyMap.h:64
iterator find(const original_key_type &Key)
Definition HashKeyMap.h:85
LLVM_ABI ProfileConverter(SampleProfileMap &Profiles)
static void flattenProfile(SampleProfileMap &ProfileMap, bool ProfileIsCS=false)
static void flattenProfile(const SampleProfileMap &InputProfiles, SampleProfileMap &OutputProfiles, bool ProfileIsCS=false)
ProfileSymbolList records the list of function symbols shown up in the binary used to generate the pr...
void add(StringRef Name, bool Copy=false)
copy indicates whether we need to copy the underlying memory for the input Name.
LLVM_ABI std::error_code write(raw_ostream &OS)
bool contains(StringRef Name) const
LLVM_ABI void dump(raw_ostream &OS=dbgs()) const
void setColdGUIDTable(EytzingerTableSpan< support::ulittle64_t > Table)
std::vector< uint64_t > collectGUIDs() const
void merge(const ProfileSymbolList &List)
EytzingerTableSpan< support::ulittle64_t > getColdGUIDTable() const
LLVM_ABI std::error_code read(const uint8_t *Data, uint64_t ListSize)
SampleContextTrimmer(SampleProfileMap &Profiles)
LLVM_ABI void trimAndMergeColdContextProfiles(uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext, uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly)
static void createCtxVectorFromStr(StringRef ContextStr, SampleContextFrameVector &Context)
Create a context vector from a given context string and save it in Context.
Definition SampleProf.h:637
bool operator==(const SampleContext &That) const
Definition SampleProf.h:730
void setFunction(FunctionId NewFunctionID)
Set the name of the function and clear the current context.
Definition SampleProf.h:716
SampleContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
Definition SampleProf.h:606
bool operator<(const SampleContext &That) const
Definition SampleProf.h:737
SampleContext(StringRef ContextStr, std::list< SampleContextFrameVector > &CSNameTable, ContextStateMask CState=RawContext)
Definition SampleProf.h:616
bool hasState(ContextStateMask S)
Definition SampleProf.h:682
void clearState(ContextStateMask S)
Definition SampleProf.h:684
SampleContextFrames getContextFrames() const
Definition SampleProf.h:688
static void decodeContextString(StringRef ContextStr, FunctionId &Func, LineLocation &LineLoc)
Definition SampleProf.h:656
static std::string getContextString(SampleContextFrames Context, bool IncludeLeafLineLocation=false)
Definition SampleProf.h:690
bool operator!=(const SampleContext &That) const
Definition SampleProf.h:735
void setState(ContextStateMask S)
Definition SampleProf.h:683
void setAllAttributes(uint32_t A)
Definition SampleProf.h:681
void setContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
Definition SampleProf.h:722
FunctionId getFunction() const
Definition SampleProf.h:687
void setAttribute(ContextAttributeMask A)
Definition SampleProf.h:679
bool hasAttribute(ContextAttributeMask A)
Definition SampleProf.h:678
std::string toString() const
Definition SampleProf.h:703
bool isPrefixOf(const SampleContext &That) const
Definition SampleProf.h:766
This class provides operator overloads to the map container using MD5 as the key type,...
iterator find(const SampleContext &Ctx)
mapped_type & create(const SampleContext &Ctx)
size_t erase(const key_type &Key)
const_iterator find(const SampleContext &Ctx) const
size_t erase(const SampleContext &Ctx)
SampleProfileReaderItaniumRemapper remaps the profile data from a sample profile data reader,...
Representation of a single sample record.
Definition SampleProf.h:389
DenseMap< FunctionId, uint64_t > CallTargetMap
Definition SampleProf.h:402
static SortedCallTargetSet sortCallTargets(const CallTargetMap &Targets)
Sort call targets in descending order of call frequency.
Definition SampleProf.h:470
LLVM_ABI std::error_code serialize(raw_ostream &OS, const MapVector< FunctionId, uint32_t > &NameTable) const
Serialize the sample record to the output stream using ULEB128 encoding.
LLVM_ABI void dump() const
bool hasCalls() const
Return true if this sample record contains function calls.
Definition SampleProf.h:454
LLVM_ABI sampleprof_error merge(const SampleRecord &Other, uint64_t Weight=1)
Merge the samples in Other into this record.
const CallTargetMap & getCallTargets() const
Definition SampleProf.h:457
SortedCallTargetSet getSortedCallTargets() const
Definition SampleProf.h:458
uint64_t getCallTargetSum() const
Definition SampleProf.h:462
uint64_t removeSamples(uint64_t S)
Decrease the number of samples for this record by S.
Definition SampleProf.h:419
sampleprof_error addSamples(uint64_t S, uint64_t Weight=1)
Increment the number of samples for this record by S.
Definition SampleProf.h:410
uint64_t removeCalledTarget(FunctionId F)
Remove called function from the call target map.
Definition SampleProf.h:443
static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets, float DistributionFactor)
Prorate call targets by a distribution factor.
Definition SampleProf.h:477
std::pair< FunctionId, uint64_t > CallTarget
Definition SampleProf.h:391
bool operator!=(const SampleRecord &Other) const
Definition SampleProf.h:502
SmallVector< CallTarget > SortedCallTargetSet
Definition SampleProf.h:401
bool operator==(const SampleRecord &Other) const
Definition SampleProf.h:498
LLVM_ABI void print(raw_ostream &OS, unsigned Indent) const
Print the sample record to the stream OS indented by Indent.
sampleprof_error addCalledTarget(FunctionId F, uint64_t S, uint64_t Weight=1)
Add called function F with samples S.
Definition SampleProf.h:431
std::pair< const LocationT, SampleT > SamplesWithLoc
SampleSorter(const std::map< LocationT, SampleT > &Samples)
const SamplesWithLocList & get() const
SmallVector< const SamplesWithLoc *, 20 > SamplesWithLocList
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
static FunctionId getRepInFormat(StringRef Name)
Get the proper representation of a string according to whether the current Format uses MD5 to represe...
static void verifySecFlag(SecType Type, SecFlagType Flag)
Definition SampleProf.h:256
LLVM_ABI void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
Definition SampleProf.h:112
static bool formatVersionIsSupported(uint64_t Version)
Definition SampleProf.h:130
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:286
std::map< LineLocation, FunctionSamplesMap > CallsiteSampleMap
Definition SampleProf.h:806
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:302
static constexpr uint64_t LatestVersion
Definition SampleProf.h:127
ArrayRef< SampleContextFrame > SampleContextFrames
Definition SampleProf.h:576
std::pair< hash_code, const FunctionSamples * > NameFunctionSamples
uint64_t MD5Hash(const FunctionId &Obj)
Definition FunctionId.h:167
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
Definition SampleProf.h:235
@ SecFlagHasVTableTypeProf
SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
Definition SampleProf.h:238
@ SecFlagPartial
SecFlagPartial means the profile is for common/shared code.
Definition SampleProf.h:226
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
Definition SampleProf.h:232
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
Definition SampleProf.h:229
static void removeSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:294
DenseMap< LineLocation, LineLocation > LocToLocMap
Definition SampleProf.h:808
SmallVector< SampleContextFrame, 1 > SampleContextFrameVector
Definition SampleProf.h:575
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
Definition SampleProf.h:805
static constexpr uint64_t MinSupportedVersion
Definition SampleProf.h:120
raw_ostream & operator<<(raw_ostream &OS, const FunctionId &Obj)
Definition FunctionId.h:159
static constexpr uint64_t DefaultVersion
Definition SampleProf.h:124
std::map< FunctionId, uint64_t > TypeCountMap
Key represents type of a C++ polymorphic class type by its vtable and value represents its counter.
Definition SampleProf.h:369
static std::string getSecName(SecType Type)
Definition SampleProf.h:154
constexpr char kVTableProfPrefix[]
Definition SampleProf.h:95
uint64_t hash_value(const FunctionId &Obj)
Definition FunctionId.h:171
LLVM_ABI std::error_code serializeTypeMap(const TypeCountMap &Map, const MapVector< FunctionId, uint32_t > &NameTable, raw_ostream &OS)
Write Map to the output stream.
static uint64_t SPVersion()
Definition SampleProf.h:136
std::map< LineLocation, TypeCountMap > CallsiteTypeMap
Definition SampleProf.h:807
std::map< LineLocation, SampleRecord > BodySampleMap
Definition SampleProf.h:802
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
Definition STLExtras.h:2116
std::error_code make_error_code(BitcodeError E)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:365
sampleprof_error mergeSampleProfErrors(sampleprof_error &Accumulator, sampleprof_error Result)
Definition SampleProf.h:73
sampleprof_error
Definition SampleProf.h:50
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition MathExtras.h:685
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI const std::error_category & sampleprof_category()
std::string getUniqueInternalLinkagePostfix(const StringRef &FName)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
LogicalResult success(bool IsSuccess=true)
Utility function to generate a LogicalResult.
SmallVector< Out, Size > to_vector_of(R &&Range)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:285
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
static unsigned getHashValue(const SampleContext &Val)
static bool isEqual(const SampleContext &LHS, const SampleContext &RHS)
static unsigned getHashValue(const sampleprof::LineLocation &Val)
Definition SampleProf.h:353
static bool isEqual(const sampleprof::LineLocation &LHS, const sampleprof::LineLocation &RHS)
Definition SampleProf.h:357
An information struct used to provide DenseMap with the various necessary components for a given valu...
Represents the relative location of an instruction.
Definition SampleProf.h:318
LLVM_ABI void serialize(raw_ostream &OS) const
LLVM_ABI void print(raw_ostream &OS) const
LineLocation(uint32_t L, uint32_t D)
Definition SampleProf.h:319
bool operator!=(const LineLocation &O) const
Definition SampleProf.h:336
bool operator<(const LineLocation &O) const
Definition SampleProf.h:327
bool operator==(const LineLocation &O) const
Definition SampleProf.h:332
LLVM_ABI void dump() const
FrameNode(FunctionId FName=FunctionId(), FunctionSamples *FSamples=nullptr, LineLocation CallLoc={0, 0})
LLVM_ABI FrameNode * getOrCreateChildFrame(const LineLocation &CallSite, FunctionId CalleeName)
std::map< uint64_t, FrameNode > AllChildFrames
uint64_t operator()(const SampleContextFrameVector &S) const
Definition SampleProf.h:579
bool operator==(const SampleContextFrame &That) const
Definition SampleProf.h:539
SampleContextFrame(FunctionId Func, LineLocation Location)
Definition SampleProf.h:536
bool operator!=(const SampleContextFrame &That) const
Definition SampleProf.h:543
std::string toString(bool OutputLineLocation) const
Definition SampleProf.h:547
uint64_t operator()(const SampleContext &Context) const
Definition SampleProf.h:761
bool operator()(const CallTarget &LHS, const CallTarget &RHS) const
Definition SampleProf.h:393