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