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