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