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