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 /// Scale \p Other sample counts by \p Weight and add the scaled result to the
1045 /// type samples for \p Loc. Under the hoold, the caller-provided \p Loc will
1046 /// be un-drifted before the type sample lookup if possible.
1047 /// typename T is either a std::map or a DenseMap.
1048 template <typename T>
1050 const T &Other,
1051 uint64_t Weight = 1) {
1052 static_assert((std::is_same_v<typename T::key_type, StringRef> ||
1053 std::is_same_v<typename T::key_type, FunctionId>) &&
1054 std::is_same_v<typename T::mapped_type, uint64_t>,
1055 "T must be a map with StringRef or FunctionId as key and "
1056 "uint64_t as value");
1057 TypeCountMap &TypeCounts = getTypeSamplesAt(Loc);
1058 bool Overflowed = false;
1059
1060 for (const auto [Type, Count] : Other) {
1061 FunctionId TypeId(Type);
1062 bool RowOverflow = false;
1063 TypeCounts[TypeId] = SaturatingMultiplyAdd(
1064 Count, Weight, TypeCounts[TypeId], &RowOverflow);
1065 Overflowed |= RowOverflow;
1066 }
1067 return Overflowed ? sampleprof_error::counter_overflow
1069 }
1070
1071 /// Return the maximum of sample counts in a function body. When SkipCallSite
1072 /// is false, which is the default, the return count includes samples in the
1073 /// inlined functions. When SkipCallSite is true, the return count only
1074 /// considers the body samples.
1075 uint64_t getMaxCountInside(bool SkipCallSite = false) const {
1076 uint64_t MaxCount = 0;
1077 for (const auto &L : getBodySamples())
1078 MaxCount = std::max(MaxCount, L.second.getSamples());
1079 if (SkipCallSite)
1080 return MaxCount;
1081 for (const auto &C : getCallsiteSamples())
1082 for (const FunctionSamplesMap::value_type &F : C.second)
1083 MaxCount = std::max(MaxCount, F.second.getMaxCountInside());
1084 return MaxCount;
1085 }
1086
1087 /// Merge the samples in \p Other into this one.
1088 /// Optionally scale samples by \p Weight.
1091 if (!GUIDToFuncNameMap)
1092 GUIDToFuncNameMap = Other.GUIDToFuncNameMap;
1093 if (Context.getFunction().empty())
1094 Context = Other.getContext();
1095 if (FunctionHash == 0) {
1096 // Set the function hash code for the target profile.
1097 FunctionHash = Other.getFunctionHash();
1098 } else if (FunctionHash != Other.getFunctionHash()) {
1099 // The two profiles coming with different valid hash codes indicates
1100 // either:
1101 // 1. They are same-named static functions from different compilation
1102 // units (without using -unique-internal-linkage-names), or
1103 // 2. They are really the same function but from different compilations.
1104 // Let's bail out in either case for now, which means one profile is
1105 // dropped.
1107 }
1108
1109 mergeSampleProfErrors(Result,
1110 addTotalSamples(Other.getTotalSamples(), Weight));
1111 mergeSampleProfErrors(Result,
1112 addHeadSamples(Other.getHeadSamples(), Weight));
1113 for (const auto &I : Other.getBodySamples()) {
1114 const LineLocation &Loc = I.first;
1115 const SampleRecord &Rec = I.second;
1116 mergeSampleProfErrors(Result, BodySamples[Loc].merge(Rec, Weight));
1117 }
1118 for (const auto &I : Other.getCallsiteSamples()) {
1119 const LineLocation &Loc = I.first;
1121 for (const auto &Rec : I.second)
1122 mergeSampleProfErrors(Result,
1123 FSMap[Rec.first].merge(Rec.second, Weight));
1124 }
1125 for (const auto &[Loc, OtherTypeMap] : Other.getCallsiteTypeCounts())
1127 Result, addCallsiteVTableTypeProfAt(Loc, OtherTypeMap, Weight));
1128
1129 return Result;
1130 }
1131
1132 /// Recursively traverses all children, if the total sample count of the
1133 /// corresponding function is no less than \p Threshold, add its corresponding
1134 /// GUID to \p S. Also traverse the BodySamples to add hot CallTarget's GUID
1135 /// to \p S.
1137 const HashKeyMap<std::unordered_map, FunctionId,
1138 Function *> &SymbolMap,
1139 uint64_t Threshold) const {
1140 if (TotalSamples <= Threshold)
1141 return;
1142 auto IsDeclaration = [](const Function *F) {
1143 return !F || F->isDeclaration();
1144 };
1145 if (IsDeclaration(SymbolMap.lookup(getFunction()))) {
1146 // Add to the import list only when it's defined out of module.
1147 S.insert(getGUID());
1148 }
1149 // Import hot CallTargets, which may not be available in IR because full
1150 // profile annotation cannot be done until backend compilation in ThinLTO.
1151 for (const auto &BS : BodySamples)
1152 for (const auto &TS : BS.second.getCallTargets())
1153 if (TS.second > Threshold) {
1154 const Function *Callee = SymbolMap.lookup(TS.first);
1155 if (IsDeclaration(Callee))
1156 S.insert(TS.first.getHashCode());
1157 }
1158 for (const auto &CS : CallsiteSamples)
1159 for (const auto &NameFS : CS.second)
1160 NameFS.second.findInlinedFunctions(S, SymbolMap, Threshold);
1161 }
1162
1163 /// Set the name of the function.
1164 void setFunction(FunctionId NewFunctionID) {
1165 Context.setFunction(NewFunctionID);
1166 }
1167
1168 /// Return the function name.
1169 FunctionId getFunction() const { return Context.getFunction(); }
1170
1171 /// Return the original function name.
1173
1174 void setFunctionHash(uint64_t Hash) { FunctionHash = Hash; }
1175
1176 uint64_t getFunctionHash() const { return FunctionHash; }
1177
1179 assert(IRToProfileLocationMap == nullptr && "this should be set only once");
1180 IRToProfileLocationMap = LTLM;
1181 }
1182
1183 /// Return the canonical name for a function, taking into account
1184 /// suffix elision policy attributes.
1186 const char *AttrName = "sample-profile-suffix-elision-policy";
1187 auto Attr = F.getFnAttribute(AttrName).getValueAsString();
1188 return getCanonicalFnName(F.getName(), Attr);
1189 }
1190
1191 /// Name suffixes which canonicalization should handle to avoid
1192 /// profile mismatch.
1193 static constexpr const char *LLVMSuffix = ".llvm.";
1194 static constexpr const char *PartSuffix = ".part.";
1195 static constexpr const char *UniqSuffix = ".__uniq.";
1196
1198 StringRef Attr = "selected") {
1199 // Note the sequence of the suffixes in the knownSuffixes array matters.
1200 // If suffix "A" is appended after the suffix "B", "A" should be in front
1201 // of "B" in knownSuffixes.
1202 const char *KnownSuffixes[] = {LLVMSuffix, PartSuffix, UniqSuffix};
1203 if (Attr == "" || Attr == "all")
1204 return FnName.split('.').first;
1205 if (Attr == "selected") {
1206 StringRef Cand(FnName);
1207 for (const auto &Suf : KnownSuffixes) {
1208 StringRef Suffix(Suf);
1209 // If the profile contains ".__uniq." suffix, don't strip the
1210 // suffix for names in the IR.
1212 continue;
1213 auto It = Cand.rfind(Suffix);
1214 if (It == StringRef::npos)
1215 continue;
1216 auto Dit = Cand.rfind('.');
1217 if (Dit == It + Suffix.size() - 1)
1218 Cand = Cand.substr(0, It);
1219 }
1220 return Cand;
1221 }
1222 if (Attr == "none")
1223 return FnName;
1224 assert(false && "internal error: unknown suffix elision policy");
1225 return FnName;
1226 }
1227
1228 /// Translate \p Func into its original name.
1229 /// When profile doesn't use MD5, \p Func needs no translation.
1230 /// When profile uses MD5, \p Func in current FunctionSamples
1231 /// is actually GUID of the original function name. getFuncName will
1232 /// translate \p Func in current FunctionSamples into its original name
1233 /// by looking up in the function map GUIDToFuncNameMap.
1234 /// If the original name doesn't exist in the map, return empty StringRef.
1236 if (!UseMD5)
1237 return Func.stringRef();
1238
1239 assert(GUIDToFuncNameMap && "GUIDToFuncNameMap needs to be populated first");
1240 return GUIDToFuncNameMap->lookup(Func.getHashCode());
1241 }
1242
1243 /// Returns the line offset to the start line of the subprogram.
1244 /// We assume that a single function will not exceed 65535 LOC.
1245 LLVM_ABI static unsigned getOffset(const DILocation *DIL);
1246
1247 /// Returns a unique call site identifier for a given debug location of a call
1248 /// instruction. This is wrapper of two scenarios, the probe-based profile and
1249 /// regular profile, to hide implementation details from the sample loader and
1250 /// the context tracker.
1252 bool ProfileIsFS = false);
1253
1254 /// Returns a unique hash code for a combination of a callsite location and
1255 /// the callee function name.
1256 /// Guarantee MD5 and non-MD5 representation of the same function results in
1257 /// the same hash.
1259 const LineLocation &Callsite) {
1260 return SampleContextFrame(Callee, Callsite).getHashCode();
1261 }
1262
1263 /// Get the FunctionSamples of the inline instance where DIL originates
1264 /// from.
1265 ///
1266 /// The FunctionSamples of the instruction (Machine or IR) associated to
1267 /// \p DIL is the inlined instance in which that instruction is coming from.
1268 /// We traverse the inline stack of that instruction, and match it with the
1269 /// tree nodes in the profile.
1270 ///
1271 /// \returns the FunctionSamples pointer to the inlined instance.
1272 /// If \p Remapper or \p FuncNameToProfNameMap is not nullptr, it will be used
1273 /// to find matching FunctionSamples with not exactly the same but equivalent
1274 /// name.
1276 const DILocation *DIL,
1277 SampleProfileReaderItaniumRemapper *Remapper = nullptr,
1279 *FuncNameToProfNameMap = nullptr) const;
1280
1282
1284
1286
1287 SampleContext &getContext() const { return Context; }
1288
1289 void setContext(const SampleContext &FContext) { Context = FContext; }
1290
1291 /// Whether the profile uses MD5 to represent string.
1292 LLVM_ABI static bool UseMD5;
1293
1294 /// Whether the profile contains any ".__uniq." suffix in a name.
1296
1297 /// If this profile uses flow sensitive discriminators.
1299
1300 /// GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
1301 /// all the function symbols defined or declared in current module.
1303
1304 /// Return the GUID of the context's name. If the context is already using
1305 /// MD5, don't hash it again.
1307 return getFunction().getHashCode();
1308 }
1309
1310 // Find all the names in the current FunctionSamples including names in
1311 // all the inline instances and names of call targets.
1312 LLVM_ABI void findAllNames(DenseSet<FunctionId> &NameSet) const;
1313
1314 bool operator==(const FunctionSamples &Other) const {
1315 return (GUIDToFuncNameMap == Other.GUIDToFuncNameMap ||
1316 (GUIDToFuncNameMap && Other.GUIDToFuncNameMap &&
1317 *GUIDToFuncNameMap == *Other.GUIDToFuncNameMap)) &&
1318 FunctionHash == Other.FunctionHash && Context == Other.Context &&
1319 TotalSamples == Other.TotalSamples &&
1320 TotalHeadSamples == Other.TotalHeadSamples &&
1321 BodySamples == Other.BodySamples &&
1322 CallsiteSamples == Other.CallsiteSamples;
1323 }
1324
1325 bool operator!=(const FunctionSamples &Other) const {
1326 return !(*this == Other);
1327 }
1328
1329private:
1330 /// CFG hash value for the function.
1331 uint64_t FunctionHash = 0;
1332
1333 /// Calling context for function profile
1334 mutable SampleContext Context;
1335
1336 /// Total number of samples collected inside this function.
1337 ///
1338 /// Samples are cumulative, they include all the samples collected
1339 /// inside this function and all its inlined callees.
1340 uint64_t TotalSamples = 0;
1341
1342 /// Total number of samples collected at the head of the function.
1343 /// This is an approximation of the number of calls made to this function
1344 /// at runtime.
1345 uint64_t TotalHeadSamples = 0;
1346
1347 /// Map instruction locations to collected samples.
1348 ///
1349 /// Each entry in this map contains the number of samples
1350 /// collected at the corresponding line offset. All line locations
1351 /// are an offset from the start of the function.
1352 BodySampleMap BodySamples;
1353
1354 /// Map call sites to collected samples for the called function.
1355 ///
1356 /// Each entry in this map corresponds to all the samples
1357 /// collected for the inlined function call at the given
1358 /// location. For example, given:
1359 ///
1360 /// void foo() {
1361 /// 1 bar();
1362 /// ...
1363 /// 8 baz();
1364 /// }
1365 ///
1366 /// If the bar() and baz() calls were inlined inside foo(), this
1367 /// map will contain two entries. One for all the samples collected
1368 /// in the call to bar() at line offset 1, the other for all the samples
1369 /// collected in the call to baz() at line offset 8.
1370 CallsiteSampleMap CallsiteSamples;
1371
1372 /// Map a virtual callsite to the list of accessed vtables and vtable counts.
1373 /// The callsite is referenced by its source location.
1374 ///
1375 /// For example, given:
1376 ///
1377 /// void foo() {
1378 /// ...
1379 /// 5 inlined_vcall_bar();
1380 /// ...
1381 /// 5 inlined_vcall_baz();
1382 /// ...
1383 /// 200 inlined_vcall_qux();
1384 /// }
1385 /// This map will contain two entries. One with two types for line offset 5
1386 /// and one with one type for line offset 200.
1387 CallsiteTypeMap VirtualCallsiteTypeCounts;
1388
1389 /// IR to profile location map generated by stale profile matching.
1390 ///
1391 /// Each entry is a mapping from the location on current build to the matched
1392 /// location in the "stale" profile. For example:
1393 /// Profiled source code:
1394 /// void foo() {
1395 /// 1 bar();
1396 /// }
1397 ///
1398 /// Current source code:
1399 /// void foo() {
1400 /// 1 // Code change
1401 /// 2 bar();
1402 /// }
1403 /// Supposing the stale profile matching algorithm generated the mapping [2 ->
1404 /// 1], the profile query using the location of bar on the IR which is 2 will
1405 /// be remapped to 1 and find the location of bar in the profile.
1406 const LocToLocMap *IRToProfileLocationMap = nullptr;
1407};
1408
1409/// Get the proper representation of a string according to whether the
1410/// current Format uses MD5 to represent the string.
1412 if (Name.empty() || !FunctionSamples::UseMD5)
1413 return FunctionId(Name);
1415}
1416
1418
1419/// This class provides operator overloads to the map container using MD5 as the
1420/// key type, so that existing code can still work in most cases using
1421/// SampleContext as key.
1422/// Note: when populating container, make sure to assign the SampleContext to
1423/// the mapped value immediately because the key no longer holds it.
1425 : public HashKeyMap<std::unordered_map, SampleContext, FunctionSamples> {
1426public:
1427 // Convenience method because this is being used in many places. Set the
1428 // FunctionSamples' context if its newly inserted.
1430 auto Ret = try_emplace(Ctx, FunctionSamples());
1431 if (Ret.second)
1432 Ret.first->second.setContext(Ctx);
1433 return Ret.first->second;
1434 }
1435
1440
1445
1450
1451 size_t erase(const key_type &Key) { return base_type::erase(Key); }
1452
1453 iterator erase(iterator It) { return base_type::erase(It); }
1454};
1455
1456using NameFunctionSamples = std::pair<hash_code, const FunctionSamples *>;
1457
1458LLVM_ABI void
1459sortFuncProfiles(const SampleProfileMap &ProfileMap,
1460 std::vector<NameFunctionSamples> &SortedProfiles);
1461
1462/// Sort a LocationT->SampleT map by LocationT.
1463///
1464/// It produces a sorted list of <LocationT, SampleT> records by ascending
1465/// order of LocationT.
1466template <class LocationT, class SampleT> class SampleSorter {
1467public:
1468 using SamplesWithLoc = std::pair<const LocationT, SampleT>;
1470
1471 SampleSorter(const std::map<LocationT, SampleT> &Samples) {
1472 for (const auto &I : Samples)
1473 V.push_back(&I);
1474 llvm::stable_sort(V, [](const SamplesWithLoc *A, const SamplesWithLoc *B) {
1475 return A->first < B->first;
1476 });
1477 }
1478
1479 const SamplesWithLocList &get() const { return V; }
1480
1481private:
1483};
1484
1485/// SampleContextTrimmer impelements helper functions to trim, merge cold
1486/// context profiles. It also supports context profile canonicalization to make
1487/// sure ProfileMap's key is consistent with FunctionSample's name/context.
1489public:
1490 SampleContextTrimmer(SampleProfileMap &Profiles) : ProfileMap(Profiles){};
1491 // Trim and merge cold context profile when requested. TrimBaseProfileOnly
1492 // should only be effective when TrimColdContext is true. On top of
1493 // TrimColdContext, TrimBaseProfileOnly can be used to specify to trim all
1494 // cold profiles or only cold base profiles. Trimming base profiles only is
1495 // mainly to honor the preinliner decsion. Note that when MergeColdContext is
1496 // true, preinliner decsion is not honored anyway so TrimBaseProfileOnly will
1497 // be ignored.
1499 bool TrimColdContext,
1500 bool MergeColdContext,
1501 uint32_t ColdContextFrameLength,
1502 bool TrimBaseProfileOnly);
1503
1504private:
1505 SampleProfileMap &ProfileMap;
1506};
1507
1508/// Helper class for profile conversion.
1509///
1510/// It supports full context-sensitive profile to nested profile conversion,
1511/// nested profile to flatten profile conversion, etc.
1513public:
1515 // Convert a full context-sensitive flat sample profile into a nested sample
1516 // profile.
1518 struct FrameNode {
1520 FunctionSamples *FSamples = nullptr,
1521 LineLocation CallLoc = {0, 0})
1522 : FuncName(FName), FuncSamples(FSamples), CallSiteLoc(CallLoc){};
1523
1524 // Map line+discriminator location to child frame
1525 std::map<uint64_t, FrameNode> AllChildFrames;
1526 // Function name for current frame
1528 // Function Samples for current frame
1530 // Callsite location in parent context
1532
1534 FunctionId CalleeName);
1535 };
1536
1537 static void flattenProfile(SampleProfileMap &ProfileMap,
1538 bool ProfileIsCS = false) {
1539 SampleProfileMap TmpProfiles;
1540 flattenProfile(ProfileMap, TmpProfiles, ProfileIsCS);
1541 ProfileMap = std::move(TmpProfiles);
1542 }
1543
1544 static void flattenProfile(const SampleProfileMap &InputProfiles,
1545 SampleProfileMap &OutputProfiles,
1546 bool ProfileIsCS = false) {
1547 if (ProfileIsCS) {
1548 for (const auto &I : InputProfiles) {
1549 // Retain the profile name and clear the full context for each function
1550 // profile.
1551 FunctionSamples &FS = OutputProfiles.create(I.second.getFunction());
1552 FS.merge(I.second);
1553 }
1554 } else {
1555 for (const auto &I : InputProfiles)
1556 flattenNestedProfile(OutputProfiles, I.second);
1557 }
1558 }
1559
1560private:
1561 static void flattenNestedProfile(SampleProfileMap &OutputProfiles,
1562 const FunctionSamples &FS) {
1563 // To retain the context, checksum, attributes of the original profile, make
1564 // a copy of it if no profile is found.
1565 SampleContext &Context = FS.getContext();
1566 auto Ret = OutputProfiles.try_emplace(Context, FS);
1567 FunctionSamples &Profile = Ret.first->second;
1568 if (Ret.second) {
1569 // Clear nested inlinees' samples for the flattened copy. These inlinees
1570 // will have their own top-level entries after flattening.
1571 Profile.removeAllCallsiteSamples();
1572 // We recompute TotalSamples later, so here set to zero.
1573 Profile.setTotalSamples(0);
1574 } else {
1575 for (const auto &[LineLocation, SampleRecord] : FS.getBodySamples()) {
1576 Profile.addSampleRecord(LineLocation, SampleRecord);
1577 }
1578 }
1579
1580 assert(Profile.getCallsiteSamples().empty() &&
1581 "There should be no inlinees' profiles after flattening.");
1582
1583 // TotalSamples might not be equal to the sum of all samples from
1584 // BodySamples and CallsiteSamples. So here we use "TotalSamples =
1585 // Original_TotalSamples - All_of_Callsite_TotalSamples +
1586 // All_of_Callsite_HeadSamples" to compute the new TotalSamples.
1587 uint64_t TotalSamples = FS.getTotalSamples();
1588
1589 for (const auto &I : FS.getCallsiteSamples()) {
1590 for (const auto &Callee : I.second) {
1591 const auto &CalleeProfile = Callee.second;
1592 // Add body sample.
1593 Profile.addBodySamples(I.first.LineOffset, I.first.Discriminator,
1594 CalleeProfile.getHeadSamplesEstimate());
1595 // Add callsite sample.
1596 Profile.addCalledTargetSamples(
1597 I.first.LineOffset, I.first.Discriminator,
1598 CalleeProfile.getFunction(),
1599 CalleeProfile.getHeadSamplesEstimate());
1600 // Update total samples.
1601 TotalSamples = TotalSamples >= CalleeProfile.getTotalSamples()
1602 ? TotalSamples - CalleeProfile.getTotalSamples()
1603 : 0;
1604 TotalSamples += CalleeProfile.getHeadSamplesEstimate();
1605 // Recursively convert callee profile.
1606 flattenNestedProfile(OutputProfiles, CalleeProfile);
1607 }
1608 }
1609 Profile.addTotalSamples(TotalSamples);
1610
1611 Profile.setHeadSamples(Profile.getHeadSamplesEstimate());
1612 }
1613
1614 // Nest all children profiles into the profile of Node.
1615 void convertCSProfiles(FrameNode &Node);
1616 FrameNode *getOrCreateContextPath(const SampleContext &Context);
1617
1618 SampleProfileMap &ProfileMap;
1619 FrameNode RootFrame;
1620};
1621
1622/// ProfileSymbolList records the list of function symbols shown up
1623/// in the binary used to generate the profile. It is useful to
1624/// to discriminate a function being so cold as not to shown up
1625/// in the profile and a function newly added.
1627public:
1628 /// copy indicates whether we need to copy the underlying memory
1629 /// for the input Name.
1630 void add(StringRef Name, bool Copy = false) {
1631 if (!Copy) {
1632 Syms.insert(Name);
1633 return;
1634 }
1635 Syms.insert(Name.copy(Allocator));
1636 }
1637
1638 bool contains(StringRef Name) { return Syms.count(Name); }
1639
1641 for (auto Sym : List.Syms)
1642 add(Sym, true);
1643 }
1644
1645 unsigned size() { return Syms.size(); }
1646
1647 void setToCompress(bool TC) { ToCompress = TC; }
1648 bool toCompress() { return ToCompress; }
1649
1650 LLVM_ABI std::error_code read(const uint8_t *Data, uint64_t ListSize);
1651 LLVM_ABI std::error_code write(raw_ostream &OS);
1652 LLVM_ABI void dump(raw_ostream &OS = dbgs()) const;
1653
1654private:
1655 // Determine whether or not to compress the symbol list when
1656 // writing it into profile. The variable is unused when the symbol
1657 // list is read from an existing profile.
1658 bool ToCompress = false;
1661};
1662
1663} // end namespace sampleprof
1664
1665using namespace sampleprof;
1666// Provide DenseMapInfo for SampleContext.
1667template <> struct DenseMapInfo<SampleContext> {
1668 static inline SampleContext getEmptyKey() { return SampleContext(); }
1669
1671 return SampleContext(FunctionId(~1ULL));
1672 }
1673
1674 static unsigned getHashValue(const SampleContext &Val) {
1675 return Val.getHashCode();
1676 }
1677
1678 static bool isEqual(const SampleContext &LHS, const SampleContext &RHS) {
1679 return LHS == RHS;
1680 }
1681};
1682
1683// Prepend "__uniq" before the hash for tools like profilers to understand
1684// that this symbol is of internal linkage type. The "__uniq" is the
1685// pre-determined prefix that is used to tell tools that this symbol was
1686// created with -funique-internal-linkage-symbols and the tools can strip or
1687// keep the prefix as needed.
1688inline std::string getUniqueInternalLinkagePostfix(const StringRef &FName) {
1689 llvm::MD5 Md5;
1690 Md5.update(FName);
1692 Md5.final(R);
1693 SmallString<32> Str;
1695 // Convert MD5hash to Decimal. Demangler suffixes can either contain
1696 // numbers or characters but not both.
1697 llvm::APInt IntHash(128, Str.str(), 16);
1698 return toString(IntHash, /* Radix = */ 10, /* Signed = */ false)
1699 .insert(0, FunctionSamples::UniqSuffix);
1700}
1701
1702} // end namespace llvm
1703
1704#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:55
#define I(x, y, z)
Definition MD5.cpp:58
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:41
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition ArrayRef.h:224
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
Definition ArrayRef.h:206
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:187
Implements a dense probed hash-table based set.
Definition DenseSet.h:261
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:189
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:287
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:234
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:710
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:581
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:269
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:151
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:154
size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
Definition StringRef.h:353
static constexpr size_t npos
Definition StringRef.h:57
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:194
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")
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.
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
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:53
std::pair< iterator, bool > try_emplace(const key_type &Hash, const original_key_type &Key, Ts &&...Args)
Definition HashKeyMap.h:65
size_t erase(const original_key_type &Ctx)
Definition HashKeyMap.h:111
iterator find(const original_key_type &Key)
Definition HashKeyMap.h:86
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.
void stable_sort(R &&Range)
Definition STLExtras.h:2040
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:695
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
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)
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:465
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:851
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