LLVM 17.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"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/GlobalValue.h"
25#include "llvm/Support/Debug.h"
28#include <algorithm>
29#include <cstdint>
30#include <list>
31#include <map>
32#include <set>
33#include <sstream>
34#include <string>
35#include <system_error>
36#include <unordered_map>
37#include <utility>
38
39namespace llvm {
40
41class DILocation;
42class raw_ostream;
43
44const std::error_category &sampleprof_category();
45
46enum class sampleprof_error {
47 success = 0,
62};
63
64inline std::error_code make_error_code(sampleprof_error E) {
65 return std::error_code(static_cast<int>(E), sampleprof_category());
66}
67
69 sampleprof_error Result) {
70 // Prefer first error encountered as later errors may be secondary effects of
71 // the initial problem.
74 Accumulator = Result;
75 return Accumulator;
76}
77
78} // end namespace llvm
79
80namespace std {
81
82template <>
83struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
84
85} // end namespace std
86
87namespace llvm {
88namespace sampleprof {
89
92 SPF_Text = 0x1,
93 SPF_Compact_Binary = 0x2, // Deprecated
94 SPF_GCC = 0x3,
96 SPF_Binary = 0xff
97};
98
101 SPL_Nest = 0x1,
102 SPL_Flat = 0x2,
103};
104
106 return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
107 uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
108 uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
109 uint64_t('2') << (64 - 56) | uint64_t(Format);
110}
111
112/// Get the proper representation of a string according to whether the
113/// current Format uses MD5 to represent the string.
114static inline StringRef getRepInFormat(StringRef Name, bool UseMD5,
115 std::string &GUIDBuf) {
116 if (Name.empty() || !UseMD5)
117 return Name;
118 GUIDBuf = std::to_string(Function::getGUID(Name));
119 return GUIDBuf;
120}
121
122static inline uint64_t SPVersion() { return 103; }
123
124// Section Type used by SampleProfileExtBinaryBaseReader and
125// SampleProfileExtBinaryBaseWriter. Never change the existing
126// value of enum. Only append new ones.
135 // marker for the first type of profile.
139
140static inline std::string getSecName(SecType Type) {
141 switch ((int)Type) { // Avoid -Wcovered-switch-default
142 case SecInValid:
143 return "InvalidSection";
144 case SecProfSummary:
145 return "ProfileSummarySection";
146 case SecNameTable:
147 return "NameTableSection";
149 return "ProfileSymbolListSection";
151 return "FuncOffsetTableSection";
152 case SecFuncMetadata:
153 return "FunctionMetadata";
154 case SecCSNameTable:
155 return "CSNameTableSection";
156 case SecLBRProfile:
157 return "LBRProfileSection";
158 default:
159 return "UnknownSection";
160 }
161}
162
163// Entry type of section header table used by SampleProfileExtBinaryBaseReader
164// and SampleProfileExtBinaryBaseWriter.
170 // The index indicating the location of the current entry in
171 // SectionHdrLayout table.
173};
174
175// Flags common for all sections are defined here. In SecHdrTableEntry::Flags,
176// common flags will be saved in the lower 32bits and section specific flags
177// will be saved in the higher 32 bits.
179 SecFlagInValid = 0,
180 SecFlagCompress = (1 << 0),
181 // Indicate the section contains only profile without context.
182 SecFlagFlat = (1 << 1)
183};
184
185// Section specific flags are defined here.
186// !!!Note: Everytime a new enum class is created here, please add
187// a new check in verifySecFlag.
189 SecFlagInValid = 0,
190 SecFlagMD5Name = (1 << 0),
191 // Store MD5 in fixed length instead of ULEB128 so NameTable can be
192 // accessed like an array.
193 SecFlagFixedLengthMD5 = (1 << 1),
194 // Profile contains ".__uniq." suffix name. Compiler shouldn't strip
195 // the suffix when doing profile matching when seeing the flag.
196 SecFlagUniqSuffix = (1 << 2)
197};
199 SecFlagInValid = 0,
200 /// SecFlagPartial means the profile is for common/shared code.
201 /// The common profile is usually merged from profiles collected
202 /// from running other targets.
203 SecFlagPartial = (1 << 0),
204 /// SecFlagContext means this is context-sensitive flat profile for
205 /// CSSPGO
206 SecFlagFullContext = (1 << 1),
207 /// SecFlagFSDiscriminator means this profile uses flow-sensitive
208 /// discriminators.
209 SecFlagFSDiscriminator = (1 << 2),
210 /// SecFlagIsPreInlined means this profile contains ShouldBeInlined
211 /// contexts thus this is CS preinliner computed.
212 SecFlagIsPreInlined = (1 << 4),
213};
214
216 SecFlagInvalid = 0,
217 SecFlagIsProbeBased = (1 << 0),
218 SecFlagHasAttribute = (1 << 1),
219};
220
222 SecFlagInvalid = 0,
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 void print(raw_ostream &OS) const;
293 void dump() const;
294
295 bool operator<(const LineLocation &O) const {
296 return LineOffset < O.LineOffset ||
297 (LineOffset == O.LineOffset && Discriminator < O.Discriminator);
298 }
299
300 bool operator==(const LineLocation &O) const {
301 return LineOffset == O.LineOffset && Discriminator == O.Discriminator;
302 }
303
304 bool operator!=(const LineLocation &O) const {
305 return LineOffset != O.LineOffset || Discriminator != O.Discriminator;
306 }
307
310};
311
313 uint64_t operator()(const LineLocation &Loc) const {
314 return std::hash<std::uint64_t>{}((((uint64_t)Loc.LineOffset) << 32) |
315 Loc.Discriminator);
316 }
317};
318
320
321/// Representation of a single sample record.
322///
323/// A sample record is represented by a positive integer value, which
324/// indicates how frequently was the associated line location executed.
325///
326/// Additionally, if the associated location contains a function call,
327/// the record will hold a list of all the possible called targets. For
328/// direct calls, this will be the exact function being invoked. For
329/// indirect calls (function pointers, virtual table dispatch), this
330/// will be a list of one or more functions.
332public:
333 using CallTarget = std::pair<StringRef, uint64_t>;
335 bool operator()(const CallTarget &LHS, const CallTarget &RHS) const {
336 if (LHS.second != RHS.second)
337 return LHS.second > RHS.second;
338
339 return LHS.first < RHS.first;
340 }
341 };
342
343 using SortedCallTargetSet = std::set<CallTarget, CallTargetComparator>;
345 SampleRecord() = default;
346
347 /// Increment the number of samples for this record by \p S.
348 /// Optionally scale sample count \p S by \p Weight.
349 ///
350 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
351 /// around unsigned integers.
353 bool Overflowed;
354 NumSamples = SaturatingMultiplyAdd(S, Weight, NumSamples, &Overflowed);
355 return Overflowed ? sampleprof_error::counter_overflow
357 }
358
359 /// Decrease the number of samples for this record by \p S. Return the amout
360 /// of samples actually decreased.
362 if (S > NumSamples)
363 S = NumSamples;
364 NumSamples -= S;
365 return S;
366 }
367
368 /// Add called function \p F with samples \p S.
369 /// Optionally scale sample count \p S by \p Weight.
370 ///
371 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
372 /// around unsigned integers.
374 uint64_t Weight = 1) {
375 uint64_t &TargetSamples = CallTargets[F];
376 bool Overflowed;
377 TargetSamples =
378 SaturatingMultiplyAdd(S, Weight, TargetSamples, &Overflowed);
379 return Overflowed ? sampleprof_error::counter_overflow
381 }
382
383 /// Remove called function from the call target map. Return the target sample
384 /// count of the called function.
386 uint64_t Count = 0;
387 auto I = CallTargets.find(F);
388 if (I != CallTargets.end()) {
389 Count = I->second;
390 CallTargets.erase(I);
391 }
392 return Count;
393 }
394
395 /// Return true if this sample record contains function calls.
396 bool hasCalls() const { return !CallTargets.empty(); }
397
398 uint64_t getSamples() const { return NumSamples; }
399 const CallTargetMap &getCallTargets() const { return CallTargets; }
401 return SortCallTargets(CallTargets);
402 }
403
405 uint64_t Sum = 0;
406 for (const auto &I : CallTargets)
407 Sum += I.second;
408 return Sum;
409 }
410
411 /// Sort call targets in descending order of call frequency.
413 SortedCallTargetSet SortedTargets;
414 for (const auto &[Target, Frequency] : Targets) {
415 SortedTargets.emplace(Target, Frequency);
416 }
417 return SortedTargets;
418 }
419
420 /// Prorate call targets by a distribution factor.
422 float DistributionFactor) {
423 CallTargetMap AdjustedTargets;
424 for (const auto &[Target, Frequency] : Targets) {
425 AdjustedTargets[Target] = Frequency * DistributionFactor;
426 }
427 return AdjustedTargets;
428 }
429
430 /// Merge the samples in \p Other into this record.
431 /// Optionally scale sample counts by \p Weight.
433 void print(raw_ostream &OS, unsigned Indent) const;
434 void dump() const;
435
436 bool operator==(const SampleRecord &Other) const {
437 return NumSamples == Other.NumSamples && CallTargets == Other.CallTargets;
438 }
439
440 bool operator!=(const SampleRecord &Other) const {
441 return !(*this == Other);
442 }
443
444private:
445 uint64_t NumSamples = 0;
446 CallTargetMap CallTargets;
447};
448
450
451// State of context associated with FunctionSamples
453 UnknownContext = 0x0, // Profile without context
454 RawContext = 0x1, // Full context profile from input profile
455 SyntheticContext = 0x2, // Synthetic context created for context promotion
456 InlinedContext = 0x4, // Profile for context that is inlined into caller
457 MergedContext = 0x8 // Profile for context merged into base profile
459
460// Attribute of context associated with FunctionSamples
463 ContextWasInlined = 0x1, // Leaf of context was inlined in previous build
464 ContextShouldBeInlined = 0x2, // Leaf of context should be inlined
466 0x4, // Leaf of context is duplicated into the base profile
467};
468
469// Represents a context frame with function name and line location
473
475
478
479 bool operator==(const SampleContextFrame &That) const {
480 return Location == That.Location && FuncName == That.FuncName;
481 }
482
483 bool operator!=(const SampleContextFrame &That) const {
484 return !(*this == That);
485 }
486
487 std::string toString(bool OutputLineLocation) const {
488 std::ostringstream OContextStr;
489 OContextStr << FuncName.str();
490 if (OutputLineLocation) {
491 OContextStr << ":" << Location.LineOffset;
493 OContextStr << "." << Location.Discriminator;
494 }
495 return OContextStr.str();
496 }
497};
498
499static inline hash_code hash_value(const SampleContextFrame &arg) {
502}
503
506
509 return hash_combine_range(S.begin(), S.end());
510 }
511};
512
513// Sample context for FunctionSamples. It consists of the calling context,
514// the function name and context state. Internally sample context is represented
515// using ArrayRef, which is also the input for constructing a `SampleContext`.
516// It can accept and represent both full context string as well as context-less
517// function name.
518// For a CS profile, a full context vector can look like:
519// `main:3 _Z5funcAi:1 _Z8funcLeafi`
520// For a base CS profile without calling context, the context vector should only
521// contain the leaf frame name.
522// For a non-CS profile, the context vector should be empty.
524public:
525 SampleContext() : State(UnknownContext), Attributes(ContextNone) {}
526
528 : Name(Name), State(UnknownContext), Attributes(ContextNone) {}
529
532 : Attributes(ContextNone) {
533 assert(!Context.empty() && "Context is empty");
534 setContext(Context, CState);
535 }
536
537 // Give a context string, decode and populate internal states like
538 // Function name, Calling context and context state. Example of input
539 // `ContextStr`: `[main:3 @ _Z5funcAi:1 @ _Z8funcLeafi]`
541 std::list<SampleContextFrameVector> &CSNameTable,
543 : Attributes(ContextNone) {
544 assert(!ContextStr.empty());
545 // Note that `[]` wrapped input indicates a full context string, otherwise
546 // it's treated as context-less function name only.
547 bool HasContext = ContextStr.startswith("[");
548 if (!HasContext) {
549 State = UnknownContext;
550 Name = ContextStr;
551 } else {
552 CSNameTable.emplace_back();
553 SampleContextFrameVector &Context = CSNameTable.back();
554 createCtxVectorFromStr(ContextStr, Context);
555 setContext(Context, CState);
556 }
557 }
558
559 /// Create a context vector from a given context string and save it in
560 /// `Context`.
561 static void createCtxVectorFromStr(StringRef ContextStr,
562 SampleContextFrameVector &Context) {
563 // Remove encapsulating '[' and ']' if any
564 ContextStr = ContextStr.substr(1, ContextStr.size() - 2);
565 StringRef ContextRemain = ContextStr;
566 StringRef ChildContext;
567 StringRef CalleeName;
568 while (!ContextRemain.empty()) {
569 auto ContextSplit = ContextRemain.split(" @ ");
570 ChildContext = ContextSplit.first;
571 ContextRemain = ContextSplit.second;
572 LineLocation CallSiteLoc(0, 0);
573 decodeContextString(ChildContext, CalleeName, CallSiteLoc);
574 Context.emplace_back(CalleeName, CallSiteLoc);
575 }
576 }
577
578 // Decode context string for a frame to get function name and location.
579 // `ContextStr` is in the form of `FuncName:StartLine.Discriminator`.
580 static void decodeContextString(StringRef ContextStr, StringRef &FName,
581 LineLocation &LineLoc) {
582 // Get function name
583 auto EntrySplit = ContextStr.split(':');
584 FName = EntrySplit.first;
585
586 LineLoc = {0, 0};
587 if (!EntrySplit.second.empty()) {
588 // Get line offset, use signed int for getAsInteger so string will
589 // be parsed as signed.
590 int LineOffset = 0;
591 auto LocSplit = EntrySplit.second.split('.');
592 LocSplit.first.getAsInteger(10, LineOffset);
593 LineLoc.LineOffset = LineOffset;
594
595 // Get discriminator
596 if (!LocSplit.second.empty())
597 LocSplit.second.getAsInteger(10, LineLoc.Discriminator);
598 }
599 }
600
601 operator SampleContextFrames() const { return FullContext; }
602 bool hasAttribute(ContextAttributeMask A) { return Attributes & (uint32_t)A; }
603 void setAttribute(ContextAttributeMask A) { Attributes |= (uint32_t)A; }
604 uint32_t getAllAttributes() { return Attributes; }
605 void setAllAttributes(uint32_t A) { Attributes = A; }
606 bool hasState(ContextStateMask S) { return State & (uint32_t)S; }
607 void setState(ContextStateMask S) { State |= (uint32_t)S; }
608 void clearState(ContextStateMask S) { State &= (uint32_t)~S; }
609 bool hasContext() const { return State != UnknownContext; }
610 bool isBaseContext() const { return FullContext.size() == 1; }
611 StringRef getName() const { return Name; }
612 SampleContextFrames getContextFrames() const { return FullContext; }
613
614 static std::string getContextString(SampleContextFrames Context,
615 bool IncludeLeafLineLocation = false) {
616 std::ostringstream OContextStr;
617 for (uint32_t I = 0; I < Context.size(); I++) {
618 if (OContextStr.str().size()) {
619 OContextStr << " @ ";
620 }
621 OContextStr << Context[I].toString(I != Context.size() - 1 ||
622 IncludeLeafLineLocation);
623 }
624 return OContextStr.str();
625 }
626
627 std::string toString() const {
628 if (!hasContext())
629 return Name.str();
630 return getContextString(FullContext, false);
631 }
632
635 : hash_value(getName());
636 }
637
638 /// Set the name of the function and clear the current context.
639 void setName(StringRef FunctionName) {
640 Name = FunctionName;
641 FullContext = SampleContextFrames();
642 State = UnknownContext;
643 }
644
646 ContextStateMask CState = RawContext) {
647 assert(CState != UnknownContext);
648 FullContext = Context;
649 Name = Context.back().FuncName;
650 State = CState;
651 }
652
653 bool operator==(const SampleContext &That) const {
654 return State == That.State && Name == That.Name &&
655 FullContext == That.FullContext;
656 }
657
658 bool operator!=(const SampleContext &That) const { return !(*this == That); }
659
660 bool operator<(const SampleContext &That) const {
661 if (State != That.State)
662 return State < That.State;
663
664 if (!hasContext()) {
665 return Name < That.Name;
666 }
667
668 uint64_t I = 0;
669 while (I < std::min(FullContext.size(), That.FullContext.size())) {
670 auto &Context1 = FullContext[I];
671 auto &Context2 = That.FullContext[I];
672 auto V = Context1.FuncName.compare(Context2.FuncName);
673 if (V)
674 return V < 0;
675 if (Context1.Location != Context2.Location)
676 return Context1.Location < Context2.Location;
677 I++;
678 }
679
680 return FullContext.size() < That.FullContext.size();
681 }
682
683 struct Hash {
684 uint64_t operator()(const SampleContext &Context) const {
685 return Context.getHashCode();
686 }
687 };
688
689 bool IsPrefixOf(const SampleContext &That) const {
690 auto ThisContext = FullContext;
691 auto ThatContext = That.FullContext;
692 if (ThatContext.size() < ThisContext.size())
693 return false;
694 ThatContext = ThatContext.take_front(ThisContext.size());
695 // Compare Leaf frame first
696 if (ThisContext.back().FuncName != ThatContext.back().FuncName)
697 return false;
698 // Compare leading context
699 return ThisContext.drop_back() == ThatContext.drop_back();
700 }
701
702private:
703 /// Mangled name of the function.
704 StringRef Name;
705 // Full context including calling context and leaf function name
706 SampleContextFrames FullContext;
707 // State of the associated sample profile
708 uint32_t State;
709 // Attribute of the associated sample profile
710 uint32_t Attributes;
711};
712
713static inline hash_code hash_value(const SampleContext &arg) {
714 return arg.hasContext() ? hash_value(arg.getContextFrames())
715 : hash_value(arg.getName());
716}
717
718class FunctionSamples;
720
721using BodySampleMap = std::map<LineLocation, SampleRecord>;
722// NOTE: Using a StringMap here makes parsed profiles consume around 17% more
723// memory, which is *very* significant for large profiles.
724using FunctionSamplesMap = std::map<std::string, FunctionSamples, std::less<>>;
725using CallsiteSampleMap = std::map<LineLocation, FunctionSamplesMap>;
727 std::unordered_map<LineLocation, LineLocation, LineLocationHash>;
728
729/// Representation of the samples collected for a function.
730///
731/// This data structure contains all the collected samples for the body
732/// of a function. Each sample corresponds to a LineLocation instance
733/// within the body of the function.
735public:
736 FunctionSamples() = default;
737
738 void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
739 void dump() const;
740
742 bool Overflowed;
743 TotalSamples =
744 SaturatingMultiplyAdd(Num, Weight, TotalSamples, &Overflowed);
745 return Overflowed ? sampleprof_error::counter_overflow
747 }
748
750 if (TotalSamples < Num)
751 TotalSamples = 0;
752 else
753 TotalSamples -= Num;
754 }
755
756 void setTotalSamples(uint64_t Num) { TotalSamples = Num; }
757
758 void setHeadSamples(uint64_t Num) { TotalHeadSamples = Num; }
759
761 bool Overflowed;
762 TotalHeadSamples =
763 SaturatingMultiplyAdd(Num, Weight, TotalHeadSamples, &Overflowed);
764 return Overflowed ? sampleprof_error::counter_overflow
766 }
767
769 uint64_t Num, uint64_t Weight = 1) {
770 return BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(
771 Num, Weight);
772 }
773
775 uint32_t Discriminator,
776 StringRef FName, uint64_t Num,
777 uint64_t Weight = 1) {
778 return BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(
779 FName, Num, Weight);
780 }
781
783 const SampleRecord &SampleRecord, uint64_t Weight = 1) {
784 return BodySamples[Location].merge(SampleRecord, Weight);
785 }
786
787 // Remove a call target and decrease the body sample correspondingly. Return
788 // the number of body samples actually decreased.
790 uint32_t Discriminator,
791 StringRef FName) {
792 uint64_t Count = 0;
793 auto I = BodySamples.find(LineLocation(LineOffset, Discriminator));
794 if (I != BodySamples.end()) {
795 Count = I->second.removeCalledTarget(FName);
796 Count = I->second.removeSamples(Count);
797 if (!I->second.getSamples())
798 BodySamples.erase(I);
799 }
800 return Count;
801 }
802
803 // Accumulate all call target samples to update the body samples.
805 for (auto &I : BodySamples) {
806 uint64_t TargetSamples = I.second.getCallTargetSum();
807 // It's possible that the body sample count can be greater than the call
808 // target sum. E.g, if some call targets are external targets, they won't
809 // be considered valid call targets, but the body sample count which is
810 // from lbr ranges can actually include them.
811 if (TargetSamples > I.second.getSamples())
812 I.second.addSamples(TargetSamples - I.second.getSamples());
813 }
814 }
815
816 // Accumulate all body samples to set total samples.
819 for (const auto &I : BodySamples)
820 addTotalSamples(I.second.getSamples());
821
822 for (auto &I : CallsiteSamples) {
823 for (auto &CS : I.second) {
824 CS.second.updateTotalSamples();
825 addTotalSamples(CS.second.getTotalSamples());
826 }
827 }
828 }
829
830 // Set current context and all callee contexts to be synthetic.
832 Context.setState(SyntheticContext);
833 for (auto &I : CallsiteSamples) {
834 for (auto &CS : I.second) {
835 CS.second.SetContextSynthetic();
836 }
837 }
838 }
839
840 // Query the stale profile matching results and remap the location.
841 const LineLocation &mapIRLocToProfileLoc(const LineLocation &IRLoc) const {
842 // There is no remapping if the profile is not stale or the matching gives
843 // the same location.
844 if (!IRToProfileLocationMap)
845 return IRLoc;
846 const auto &ProfileLoc = IRToProfileLocationMap->find(IRLoc);
847 if (ProfileLoc != IRToProfileLocationMap->end())
848 return ProfileLoc->second;
849 else
850 return IRLoc;
851 }
852
853 /// Return the number of samples collected at the given location.
854 /// Each location is specified by \p LineOffset and \p Discriminator.
855 /// If the location is not found in profile, return error.
857 uint32_t Discriminator) const {
858 const auto &ret = BodySamples.find(
859 mapIRLocToProfileLoc(LineLocation(LineOffset, Discriminator)));
860 if (ret == BodySamples.end())
861 return std::error_code();
862 return ret->second.getSamples();
863 }
864
865 /// Returns the call target map collected at a given location.
866 /// Each location is specified by \p LineOffset and \p Discriminator.
867 /// If the location is not found in profile, return error.
869 findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const {
870 const auto &ret = BodySamples.find(
871 mapIRLocToProfileLoc(LineLocation(LineOffset, Discriminator)));
872 if (ret == BodySamples.end())
873 return std::error_code();
874 return ret->second.getCallTargets();
875 }
876
877 /// Returns the call target map collected at a given location specified by \p
878 /// CallSite. If the location is not found in profile, return error.
880 findCallTargetMapAt(const LineLocation &CallSite) const {
881 const auto &Ret = BodySamples.find(mapIRLocToProfileLoc(CallSite));
882 if (Ret == BodySamples.end())
883 return std::error_code();
884 return Ret->second.getCallTargets();
885 }
886
887 /// Return the function samples at the given callsite location.
889 return CallsiteSamples[mapIRLocToProfileLoc(Loc)];
890 }
891
892 /// Returns the FunctionSamplesMap at the given \p Loc.
893 const FunctionSamplesMap *
895 auto iter = CallsiteSamples.find(mapIRLocToProfileLoc(Loc));
896 if (iter == CallsiteSamples.end())
897 return nullptr;
898 return &iter->second;
899 }
900
901 /// Returns a pointer to FunctionSamples at the given callsite location
902 /// \p Loc with callee \p CalleeName. If no callsite can be found, relax
903 /// the restriction to return the FunctionSamples at callsite location
904 /// \p Loc with the maximum total sample count. If \p Remapper is not
905 /// nullptr, use \p Remapper to find FunctionSamples with equivalent name
906 /// as \p CalleeName.
907 const FunctionSamples *
908 findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName,
909 SampleProfileReaderItaniumRemapper *Remapper) const;
910
911 bool empty() const { return TotalSamples == 0; }
912
913 /// Return the total number of samples collected inside the function.
914 uint64_t getTotalSamples() const { return TotalSamples; }
915
916 /// For top-level functions, return the total number of branch samples that
917 /// have the function as the branch target (or 0 otherwise). This is the raw
918 /// data fetched from the profile. This should be equivalent to the sample of
919 /// the first instruction of the symbol. But as we directly get this info for
920 /// raw profile without referring to potentially inaccurate debug info, this
921 /// gives more accurate profile data and is preferred for standalone symbols.
922 uint64_t getHeadSamples() const { return TotalHeadSamples; }
923
924 /// Return an estimate of the sample count of the function entry basic block.
925 /// The function can be either a standalone symbol or an inlined function.
926 /// For Context-Sensitive profiles, this will prefer returning the head
927 /// samples (i.e. getHeadSamples()), if non-zero. Otherwise it estimates from
928 /// the function body's samples or callsite samples.
931 // For CS profile, if we already have more accurate head samples
932 // counted by branch sample from caller, use them as entry samples.
933 return getHeadSamples();
934 }
935 uint64_t Count = 0;
936 // Use either BodySamples or CallsiteSamples which ever has the smaller
937 // lineno.
938 if (!BodySamples.empty() &&
939 (CallsiteSamples.empty() ||
940 BodySamples.begin()->first < CallsiteSamples.begin()->first))
941 Count = BodySamples.begin()->second.getSamples();
942 else if (!CallsiteSamples.empty()) {
943 // An indirect callsite may be promoted to several inlined direct calls.
944 // We need to get the sum of them.
945 for (const auto &N_FS : CallsiteSamples.begin()->second)
946 Count += N_FS.second.getHeadSamplesEstimate();
947 }
948 // Return at least 1 if total sample is not 0.
949 return Count ? Count : TotalSamples > 0;
950 }
951
952 /// Return all the samples collected in the body of the function.
953 const BodySampleMap &getBodySamples() const { return BodySamples; }
954
955 /// Return all the callsite samples collected in the body of the function.
957 return CallsiteSamples;
958 }
959
960 CallsiteSampleMap &getCallsiteSamples() { return CallsiteSamples; }
961
962 /// Return the maximum of sample counts in a function body. When SkipCallSite
963 /// is false, which is the default, the return count includes samples in the
964 /// inlined functions. When SkipCallSite is true, the return count only
965 /// considers the body samples.
966 uint64_t getMaxCountInside(bool SkipCallSite = false) const {
967 uint64_t MaxCount = 0;
968 for (const auto &L : getBodySamples())
969 MaxCount = std::max(MaxCount, L.second.getSamples());
970 if (SkipCallSite)
971 return MaxCount;
972 for (const auto &C : getCallsiteSamples())
973 for (const FunctionSamplesMap::value_type &F : C.second)
974 MaxCount = std::max(MaxCount, F.second.getMaxCountInside());
975 return MaxCount;
976 }
977
978 /// Merge the samples in \p Other into this one.
979 /// Optionally scale samples by \p Weight.
983 GUIDToFuncNameMap = Other.GUIDToFuncNameMap;
984 if (Context.getName().empty())
985 Context = Other.getContext();
986 if (FunctionHash == 0) {
987 // Set the function hash code for the target profile.
988 FunctionHash = Other.getFunctionHash();
989 } else if (FunctionHash != Other.getFunctionHash()) {
990 // The two profiles coming with different valid hash codes indicates
991 // either:
992 // 1. They are same-named static functions from different compilation
993 // units (without using -unique-internal-linkage-names), or
994 // 2. They are really the same function but from different compilations.
995 // Let's bail out in either case for now, which means one profile is
996 // dropped.
998 }
999
1000 MergeResult(Result, addTotalSamples(Other.getTotalSamples(), Weight));
1001 MergeResult(Result, addHeadSamples(Other.getHeadSamples(), Weight));
1002 for (const auto &I : Other.getBodySamples()) {
1003 const LineLocation &Loc = I.first;
1004 const SampleRecord &Rec = I.second;
1005 MergeResult(Result, BodySamples[Loc].merge(Rec, Weight));
1006 }
1007 for (const auto &I : Other.getCallsiteSamples()) {
1008 const LineLocation &Loc = I.first;
1010 for (const auto &Rec : I.second)
1011 MergeResult(Result, FSMap[Rec.first].merge(Rec.second, Weight));
1012 }
1013 return Result;
1014 }
1015
1016 /// Recursively traverses all children, if the total sample count of the
1017 /// corresponding function is no less than \p Threshold, add its corresponding
1018 /// GUID to \p S. Also traverse the BodySamples to add hot CallTarget's GUID
1019 /// to \p S.
1021 const StringMap<Function *> &SymbolMap,
1022 uint64_t Threshold) const {
1023 if (TotalSamples <= Threshold)
1024 return;
1025 auto isDeclaration = [](const Function *F) {
1026 return !F || F->isDeclaration();
1027 };
1028 if (isDeclaration(SymbolMap.lookup(getFuncName()))) {
1029 // Add to the import list only when it's defined out of module.
1030 S.insert(getGUID(getName()));
1031 }
1032 // Import hot CallTargets, which may not be available in IR because full
1033 // profile annotation cannot be done until backend compilation in ThinLTO.
1034 for (const auto &BS : BodySamples)
1035 for (const auto &TS : BS.second.getCallTargets())
1036 if (TS.getValue() > Threshold) {
1037 const Function *Callee = SymbolMap.lookup(getFuncName(TS.getKey()));
1038 if (isDeclaration(Callee))
1039 S.insert(getGUID(TS.getKey()));
1040 }
1041 for (const auto &CS : CallsiteSamples)
1042 for (const auto &NameFS : CS.second)
1043 NameFS.second.findInlinedFunctions(S, SymbolMap, Threshold);
1044 }
1045
1046 /// Set the name of the function.
1047 void setName(StringRef FunctionName) { Context.setName(FunctionName); }
1048
1049 /// Return the function name.
1050 StringRef getName() const { return Context.getName(); }
1051
1052 /// Return the original function name.
1054
1055 void setFunctionHash(uint64_t Hash) { FunctionHash = Hash; }
1056
1057 uint64_t getFunctionHash() const { return FunctionHash; }
1058
1060 assert(IRToProfileLocationMap == nullptr && "this should be set only once");
1061 IRToProfileLocationMap = LTLM;
1062 }
1063
1064 /// Return the canonical name for a function, taking into account
1065 /// suffix elision policy attributes.
1067 auto AttrName = "sample-profile-suffix-elision-policy";
1068 auto Attr = F.getFnAttribute(AttrName).getValueAsString();
1069 return getCanonicalFnName(F.getName(), Attr);
1070 }
1071
1072 /// Name suffixes which canonicalization should handle to avoid
1073 /// profile mismatch.
1074 static constexpr const char *LLVMSuffix = ".llvm.";
1075 static constexpr const char *PartSuffix = ".part.";
1076 static constexpr const char *UniqSuffix = ".__uniq.";
1077
1079 StringRef Attr = "selected") {
1080 // Note the sequence of the suffixes in the knownSuffixes array matters.
1081 // If suffix "A" is appended after the suffix "B", "A" should be in front
1082 // of "B" in knownSuffixes.
1083 const char *knownSuffixes[] = {LLVMSuffix, PartSuffix, UniqSuffix};
1084 if (Attr == "" || Attr == "all") {
1085 return FnName.split('.').first;
1086 } else if (Attr == "selected") {
1087 StringRef Cand(FnName);
1088 for (const auto &Suf : knownSuffixes) {
1089 StringRef Suffix(Suf);
1090 // If the profile contains ".__uniq." suffix, don't strip the
1091 // suffix for names in the IR.
1093 continue;
1094 auto It = Cand.rfind(Suffix);
1095 if (It == StringRef::npos)
1096 continue;
1097 auto Dit = Cand.rfind('.');
1098 if (Dit == It + Suffix.size() - 1)
1099 Cand = Cand.substr(0, It);
1100 }
1101 return Cand;
1102 } else if (Attr == "none") {
1103 return FnName;
1104 } else {
1105 assert(false && "internal error: unknown suffix elision policy");
1106 }
1107 return FnName;
1108 }
1109
1110 /// Translate \p Name into its original name.
1111 /// When profile doesn't use MD5, \p Name needs no translation.
1112 /// When profile uses MD5, \p Name in current FunctionSamples
1113 /// is actually GUID of the original function name. getFuncName will
1114 /// translate \p Name in current FunctionSamples into its original name
1115 /// by looking up in the function map GUIDToFuncNameMap.
1116 /// If the original name doesn't exist in the map, return empty StringRef.
1118 if (!UseMD5)
1119 return Name;
1120
1121 assert(GUIDToFuncNameMap && "GUIDToFuncNameMap needs to be populated first");
1122 return GUIDToFuncNameMap->lookup(std::stoull(Name.data()));
1123 }
1124
1125 /// Returns the line offset to the start line of the subprogram.
1126 /// We assume that a single function will not exceed 65535 LOC.
1127 static unsigned getOffset(const DILocation *DIL);
1128
1129 /// Returns a unique call site identifier for a given debug location of a call
1130 /// instruction. This is wrapper of two scenarios, the probe-based profile and
1131 /// regular profile, to hide implementation details from the sample loader and
1132 /// the context tracker.
1134 bool ProfileIsFS = false);
1135
1136 /// Returns a unique hash code for a combination of a callsite location and
1137 /// the callee function name.
1138 static uint64_t getCallSiteHash(StringRef CalleeName,
1139 const LineLocation &Callsite);
1140
1141 /// Get the FunctionSamples of the inline instance where DIL originates
1142 /// from.
1143 ///
1144 /// The FunctionSamples of the instruction (Machine or IR) associated to
1145 /// \p DIL is the inlined instance in which that instruction is coming from.
1146 /// We traverse the inline stack of that instruction, and match it with the
1147 /// tree nodes in the profile.
1148 ///
1149 /// \returns the FunctionSamples pointer to the inlined instance.
1150 /// If \p Remapper is not nullptr, it will be used to find matching
1151 /// FunctionSamples with not exactly the same but equivalent name.
1153 const DILocation *DIL,
1154 SampleProfileReaderItaniumRemapper *Remapper = nullptr) const;
1155
1157
1158 static bool ProfileIsCS;
1159
1161
1162 SampleContext &getContext() const { return Context; }
1163
1164 void setContext(const SampleContext &FContext) { Context = FContext; }
1165
1166 /// Whether the profile uses MD5 to represent string.
1167 static bool UseMD5;
1168
1169 /// Whether the profile contains any ".__uniq." suffix in a name.
1170 static bool HasUniqSuffix;
1171
1172 /// If this profile uses flow sensitive discriminators.
1173 static bool ProfileIsFS;
1174
1175 /// GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
1176 /// all the function symbols defined or declared in current module.
1178
1179 // Assume the input \p Name is a name coming from FunctionSamples itself.
1180 // If UseMD5 is true, the name is already a GUID and we
1181 // don't want to return the GUID of GUID.
1183 return UseMD5 ? std::stoull(Name.data()) : Function::getGUID(Name);
1184 }
1185
1186 // Find all the names in the current FunctionSamples including names in
1187 // all the inline instances and names of call targets.
1188 void findAllNames(DenseSet<StringRef> &NameSet) const;
1189
1190 bool operator==(const FunctionSamples &Other) const {
1191 return (GUIDToFuncNameMap == Other.GUIDToFuncNameMap ||
1192 (GUIDToFuncNameMap && Other.GUIDToFuncNameMap &&
1193 *GUIDToFuncNameMap == *Other.GUIDToFuncNameMap)) &&
1194 FunctionHash == Other.FunctionHash && Context == Other.Context &&
1195 TotalSamples == Other.TotalSamples &&
1196 TotalHeadSamples == Other.TotalHeadSamples &&
1197 BodySamples == Other.BodySamples &&
1198 CallsiteSamples == Other.CallsiteSamples;
1199 }
1200
1201 bool operator!=(const FunctionSamples &Other) const {
1202 return !(*this == Other);
1203 }
1204
1205private:
1206 /// CFG hash value for the function.
1207 uint64_t FunctionHash = 0;
1208
1209 /// Calling context for function profile
1210 mutable SampleContext Context;
1211
1212 /// Total number of samples collected inside this function.
1213 ///
1214 /// Samples are cumulative, they include all the samples collected
1215 /// inside this function and all its inlined callees.
1216 uint64_t TotalSamples = 0;
1217
1218 /// Total number of samples collected at the head of the function.
1219 /// This is an approximation of the number of calls made to this function
1220 /// at runtime.
1221 uint64_t TotalHeadSamples = 0;
1222
1223 /// Map instruction locations to collected samples.
1224 ///
1225 /// Each entry in this map contains the number of samples
1226 /// collected at the corresponding line offset. All line locations
1227 /// are an offset from the start of the function.
1228 BodySampleMap BodySamples;
1229
1230 /// Map call sites to collected samples for the called function.
1231 ///
1232 /// Each entry in this map corresponds to all the samples
1233 /// collected for the inlined function call at the given
1234 /// location. For example, given:
1235 ///
1236 /// void foo() {
1237 /// 1 bar();
1238 /// ...
1239 /// 8 baz();
1240 /// }
1241 ///
1242 /// If the bar() and baz() calls were inlined inside foo(), this
1243 /// map will contain two entries. One for all the samples collected
1244 /// in the call to bar() at line offset 1, the other for all the samples
1245 /// collected in the call to baz() at line offset 8.
1246 CallsiteSampleMap CallsiteSamples;
1247
1248 /// IR to profile location map generated by stale profile matching.
1249 ///
1250 /// Each entry is a mapping from the location on current build to the matched
1251 /// location in the "stale" profile. For example:
1252 /// Profiled source code:
1253 /// void foo() {
1254 /// 1 bar();
1255 /// }
1256 ///
1257 /// Current source code:
1258 /// void foo() {
1259 /// 1 // Code change
1260 /// 2 bar();
1261 /// }
1262 /// Supposing the stale profile matching algorithm generated the mapping [2 ->
1263 /// 1], the profile query using the location of bar on the IR which is 2 will
1264 /// be remapped to 1 and find the location of bar in the profile.
1265 const LocToLocMap *IRToProfileLocationMap = nullptr;
1266};
1267
1269
1271 std::unordered_map<SampleContext, FunctionSamples, SampleContext::Hash>;
1272
1273using NameFunctionSamples = std::pair<SampleContext, const FunctionSamples *>;
1274
1275void sortFuncProfiles(const SampleProfileMap &ProfileMap,
1276 std::vector<NameFunctionSamples> &SortedProfiles);
1277
1278/// Sort a LocationT->SampleT map by LocationT.
1279///
1280/// It produces a sorted list of <LocationT, SampleT> records by ascending
1281/// order of LocationT.
1282template <class LocationT, class SampleT> class SampleSorter {
1283public:
1284 using SamplesWithLoc = std::pair<const LocationT, SampleT>;
1286
1287 SampleSorter(const std::map<LocationT, SampleT> &Samples) {
1288 for (const auto &I : Samples)
1289 V.push_back(&I);
1290 llvm::stable_sort(V, [](const SamplesWithLoc *A, const SamplesWithLoc *B) {
1291 return A->first < B->first;
1292 });
1293 }
1294
1295 const SamplesWithLocList &get() const { return V; }
1296
1297private:
1299};
1300
1301/// SampleContextTrimmer impelements helper functions to trim, merge cold
1302/// context profiles. It also supports context profile canonicalization to make
1303/// sure ProfileMap's key is consistent with FunctionSample's name/context.
1305public:
1306 SampleContextTrimmer(SampleProfileMap &Profiles) : ProfileMap(Profiles){};
1307 // Trim and merge cold context profile when requested. TrimBaseProfileOnly
1308 // should only be effective when TrimColdContext is true. On top of
1309 // TrimColdContext, TrimBaseProfileOnly can be used to specify to trim all
1310 // cold profiles or only cold base profiles. Trimming base profiles only is
1311 // mainly to honor the preinliner decsion. Note that when MergeColdContext is
1312 // true, preinliner decsion is not honored anyway so TrimBaseProfileOnly will
1313 // be ignored.
1315 bool TrimColdContext,
1316 bool MergeColdContext,
1317 uint32_t ColdContextFrameLength,
1318 bool TrimBaseProfileOnly);
1319 // Canonicalize context profile name and attributes.
1321
1322private:
1323 SampleProfileMap &ProfileMap;
1324};
1325
1326/// Helper class for profile conversion.
1327///
1328/// It supports full context-sensitive profile to nested profile conversion,
1329/// nested profile to flatten profile conversion, etc.
1331public:
1333 // Convert a full context-sensitive flat sample profile into a nested sample
1334 // profile.
1335 void convertCSProfiles();
1336 struct FrameNode {
1338 FunctionSamples *FSamples = nullptr,
1339 LineLocation CallLoc = {0, 0})
1340 : FuncName(FName), FuncSamples(FSamples), CallSiteLoc(CallLoc){};
1341
1342 // Map line+discriminator location to child frame
1343 std::map<uint64_t, FrameNode> AllChildFrames;
1344 // Function name for current frame
1346 // Function Samples for current frame
1348 // Callsite location in parent context
1350
1352 StringRef CalleeName);
1353 };
1354
1355 static void flattenProfile(SampleProfileMap &ProfileMap,
1356 bool ProfileIsCS = false) {
1357 SampleProfileMap TmpProfiles;
1358 flattenProfile(ProfileMap, TmpProfiles, ProfileIsCS);
1359 ProfileMap = std::move(TmpProfiles);
1360 }
1361
1362 static void flattenProfile(const SampleProfileMap &InputProfiles,
1363 SampleProfileMap &OutputProfiles,
1364 bool ProfileIsCS = false) {
1365 if (ProfileIsCS) {
1366 for (const auto &I : InputProfiles)
1367 OutputProfiles[I.second.getName()].merge(I.second);
1368 // Retain the profile name and clear the full context for each function
1369 // profile.
1370 for (auto &I : OutputProfiles)
1371 I.second.setContext(SampleContext(I.first));
1372 } else {
1373 for (const auto &I : InputProfiles)
1374 flattenNestedProfile(OutputProfiles, I.second);
1375 }
1376 }
1377
1378private:
1379 static void flattenNestedProfile(SampleProfileMap &OutputProfiles,
1380 const FunctionSamples &FS) {
1381 // To retain the context, checksum, attributes of the original profile, make
1382 // a copy of it if no profile is found.
1383 SampleContext &Context = FS.getContext();
1384 auto Ret = OutputProfiles.try_emplace(Context, FS);
1385 FunctionSamples &Profile = Ret.first->second;
1386 if (Ret.second) {
1387 // When it's the copy of the old profile, just clear all the inlinees'
1388 // samples.
1389 Profile.getCallsiteSamples().clear();
1390 // We recompute TotalSamples later, so here set to zero.
1391 Profile.setTotalSamples(0);
1392 } else {
1393 for (const auto &[LineLocation, SampleRecord] : FS.getBodySamples()) {
1394 Profile.addSampleRecord(LineLocation, SampleRecord);
1395 }
1396 }
1397
1398 assert(Profile.getCallsiteSamples().empty() &&
1399 "There should be no inlinees' profiles after flattening.");
1400
1401 // TotalSamples might not be equal to the sum of all samples from
1402 // BodySamples and CallsiteSamples. So here we use "TotalSamples =
1403 // Original_TotalSamples - All_of_Callsite_TotalSamples +
1404 // All_of_Callsite_HeadSamples" to compute the new TotalSamples.
1405 uint64_t TotalSamples = FS.getTotalSamples();
1406
1407 for (const auto &I : FS.getCallsiteSamples()) {
1408 for (const auto &Callee : I.second) {
1409 const auto &CalleeProfile = Callee.second;
1410 // Add body sample.
1411 Profile.addBodySamples(I.first.LineOffset, I.first.Discriminator,
1412 CalleeProfile.getHeadSamplesEstimate());
1413 // Add callsite sample.
1414 Profile.addCalledTargetSamples(
1415 I.first.LineOffset, I.first.Discriminator, CalleeProfile.getName(),
1416 CalleeProfile.getHeadSamplesEstimate());
1417 // Update total samples.
1418 TotalSamples = TotalSamples >= CalleeProfile.getTotalSamples()
1419 ? TotalSamples - CalleeProfile.getTotalSamples()
1420 : 0;
1421 TotalSamples += CalleeProfile.getHeadSamplesEstimate();
1422 // Recursively convert callee profile.
1423 flattenNestedProfile(OutputProfiles, CalleeProfile);
1424 }
1425 }
1426 Profile.addTotalSamples(TotalSamples);
1427
1428 Profile.setHeadSamples(Profile.getHeadSamplesEstimate());
1429 }
1430
1431 // Nest all children profiles into the profile of Node.
1432 void convertCSProfiles(FrameNode &Node);
1433 FrameNode *getOrCreateContextPath(const SampleContext &Context);
1434
1435 SampleProfileMap &ProfileMap;
1436 FrameNode RootFrame;
1437};
1438
1439/// ProfileSymbolList records the list of function symbols shown up
1440/// in the binary used to generate the profile. It is useful to
1441/// to discriminate a function being so cold as not to shown up
1442/// in the profile and a function newly added.
1444public:
1445 /// copy indicates whether we need to copy the underlying memory
1446 /// for the input Name.
1447 void add(StringRef Name, bool copy = false) {
1448 if (!copy) {
1449 Syms.insert(Name);
1450 return;
1451 }
1452 Syms.insert(Name.copy(Allocator));
1453 }
1454
1455 bool contains(StringRef Name) { return Syms.count(Name); }
1456
1458 for (auto Sym : List.Syms)
1459 add(Sym, true);
1460 }
1461
1462 unsigned size() { return Syms.size(); }
1463
1464 void setToCompress(bool TC) { ToCompress = TC; }
1465 bool toCompress() { return ToCompress; }
1466
1467 std::error_code read(const uint8_t *Data, uint64_t ListSize);
1468 std::error_code write(raw_ostream &OS);
1469 void dump(raw_ostream &OS = dbgs()) const;
1470
1471private:
1472 // Determine whether or not to compress the symbol list when
1473 // writing it into profile. The variable is unused when the symbol
1474 // list is read from an existing profile.
1475 bool ToCompress = false;
1477 BumpPtrAllocator Allocator;
1478};
1479
1480} // end namespace sampleprof
1481
1482using namespace sampleprof;
1483// Provide DenseMapInfo for SampleContext.
1484template <> struct DenseMapInfo<SampleContext> {
1485 static inline SampleContext getEmptyKey() { return SampleContext(); }
1486
1487 static inline SampleContext getTombstoneKey() { return SampleContext("@"); }
1488
1489 static unsigned getHashValue(const SampleContext &Val) {
1490 return Val.getHashCode();
1491 }
1492
1493 static bool isEqual(const SampleContext &LHS, const SampleContext &RHS) {
1494 return LHS == RHS;
1495 }
1496};
1497
1498// Prepend "__uniq" before the hash for tools like profilers to understand
1499// that this symbol is of internal linkage type. The "__uniq" is the
1500// pre-determined prefix that is used to tell tools that this symbol was
1501// created with -funique-internal-linakge-symbols and the tools can strip or
1502// keep the prefix as needed.
1503inline std::string getUniqueInternalLinkagePostfix(const StringRef &FName) {
1504 llvm::MD5 Md5;
1505 Md5.update(FName);
1507 Md5.final(R);
1508 SmallString<32> Str;
1510 // Convert MD5hash to Decimal. Demangler suffixes can either contain
1511 // numbers or characters but not both.
1512 llvm::APInt IntHash(128, Str.str(), 16);
1513 return toString(IntHash, /* Radix = */ 10, /* Signed = */ false)
1514 .insert(0, FunctionSamples::UniqSuffix);
1515}
1516
1517} // end namespace llvm
1518
1519#endif // LLVM_PROFILEDATA_SAMPLEPROF_H
This file defines the StringMap class.
amdgpu Simplify well known AMD library false FunctionCallee Callee
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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")
This file defines the DenseSet and SmallDenseSet classes.
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:463
Provides ErrorOr<T> smart pointer.
#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)
LLVMContext & Context
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
@ Targets
Definition: TextStubV5.cpp:90
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:75
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition: ArrayRef.h:226
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
Definition: ArrayRef.h:208
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
Debug location.
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:202
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
Represents either an error or a value T.
Definition: ErrorOr.h:56
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:591
Definition: MD5.h:41
void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition: MD5.cpp:189
static 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
void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition: MD5.cpp:234
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
bool empty() const
Definition: StringMap.h:94
iterator end()
Definition: StringMap.h:204
iterator find(StringRef Key)
Definition: StringMap.h:217
void erase(iterator I)
Definition: StringMap.h:381
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:704
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:575
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
bool startswith(StringRef Prefix) const
Definition: StringRef.h:261
size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
Definition: StringRef.h:351
static constexpr size_t npos
Definition: StringRef.h:52
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:206
An opaque object representing a hash code.
Definition: Hashing.h:74
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
Representation of the samples collected for a function.
Definition: SampleProf.h:734
void setTotalSamples(uint64_t Num)
Definition: SampleProf.h:756
void setName(StringRef FunctionName)
Set the name of the function.
Definition: SampleProf.h:1047
bool operator!=(const FunctionSamples &Other) const
Definition: SampleProf.h:1201
void setHeadSamples(uint64_t Num)
Definition: SampleProf.h:758
sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:741
static uint64_t getGUID(StringRef Name)
Definition: SampleProf.h:1182
static constexpr const char * UniqSuffix
Definition: SampleProf.h:1076
static StringRef getCanonicalFnName(StringRef FnName, StringRef Attr="selected")
Definition: SampleProf.h:1078
ErrorOr< SampleRecord::CallTargetMap > findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const
Returns the call target map collected at a given location.
Definition: SampleProf.h:869
bool operator==(const FunctionSamples &Other) const
Definition: SampleProf.h:1190
static constexpr const char * PartSuffix
Definition: SampleProf.h:1075
const FunctionSamplesMap * findFunctionSamplesMapAt(const LineLocation &Loc) const
Returns the FunctionSamplesMap at the given Loc.
Definition: SampleProf.h:894
void findInlinedFunctions(DenseSet< GlobalValue::GUID > &S, const StringMap< Function * > &SymbolMap, uint64_t Threshold) const
Recursively traverses all children, if the total sample count of the corresponding function is no les...
Definition: SampleProf.h:1020
uint64_t getMaxCountInside(bool SkipCallSite=false) const
Return the maximum of sample counts in a function body.
Definition: SampleProf.h:966
void removeTotalSamples(uint64_t Num)
Definition: SampleProf.h:749
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:922
ErrorOr< uint64_t > findSamplesAt(uint32_t LineOffset, uint32_t Discriminator) const
Return the number of samples collected at the given location.
Definition: SampleProf.h:856
ErrorOr< SampleRecord::CallTargetMap > findCallTargetMapAt(const LineLocation &CallSite) const
Returns the call target map collected at a given location specified by CallSite.
Definition: SampleProf.h:880
const LineLocation & mapIRLocToProfileLoc(const LineLocation &IRLoc) const
Definition: SampleProf.h:841
static constexpr const char * LLVMSuffix
Name suffixes which canonicalization should handle to avoid profile mismatch.
Definition: SampleProf.h:1074
void findAllNames(DenseSet< StringRef > &NameSet) const
Definition: SampleProf.cpp:272
StringRef getFuncName(StringRef Name) const
Translate Name into its original name.
Definition: SampleProf.h:1117
sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:760
sampleprof_error addSampleRecord(LineLocation Location, const SampleRecord &SampleRecord, uint64_t Weight=1)
Definition: SampleProf.h:782
const FunctionSamples * findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName, SampleProfileReaderItaniumRemapper *Remapper) const
Returns a pointer to FunctionSamples at the given callsite location Loc with callee CalleeName.
Definition: SampleProf.cpp:286
DenseMap< uint64_t, StringRef > * GUIDToFuncNameMap
GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for all the function symbols define...
Definition: SampleProf.h:1177
FunctionSamplesMap & functionSamplesAt(const LineLocation &Loc)
Return the function samples at the given callsite location.
Definition: SampleProf.h:888
CallsiteSampleMap & getCallsiteSamples()
Definition: SampleProf.h:960
void setIRToProfileLocationMap(const LocToLocMap *LTLM)
Definition: SampleProf.h:1059
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
Definition: SampleProf.h:1066
StringRef getFuncName() const
Return the original function name.
Definition: SampleProf.h:1053
static uint64_t getCallSiteHash(StringRef CalleeName, const LineLocation &Callsite)
Returns a unique hash code for a combination of a callsite location and the callee function name.
Definition: SampleProf.cpp:238
sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator, uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:768
static unsigned getOffset(const DILocation *DIL)
Returns the line offset to the start line of the subprogram.
Definition: SampleProf.cpp:216
void setFunctionHash(uint64_t Hash)
Definition: SampleProf.h:1055
uint64_t removeCalledTargetAndBodySample(uint32_t LineOffset, uint32_t Discriminator, StringRef FName)
Definition: SampleProf.h:789
static bool ProfileIsFS
If this profile uses flow sensitive discriminators.
Definition: SampleProf.h:1173
sampleprof_error addCalledTargetSamples(uint32_t LineOffset, uint32_t Discriminator, StringRef FName, uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:774
SampleContext & getContext() const
Definition: SampleProf.h:1162
static bool HasUniqSuffix
Whether the profile contains any ".__uniq." suffix in a name.
Definition: SampleProf.h:1170
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
Definition: SampleProf.h:914
void print(raw_ostream &OS=dbgs(), unsigned Indent=0) const
Print the samples collected for a function on stream OS.
Definition: SampleProf.cpp:155
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
Definition: SampleProf.h:980
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
Definition: SampleProf.h:956
void setContext(const SampleContext &FContext)
Definition: SampleProf.h:1164
static LineLocation getCallSiteIdentifier(const DILocation *DIL, bool ProfileIsFS=false)
Returns a unique call site identifier for a given debug location of a call instruction.
Definition: SampleProf.cpp:221
uint64_t getHeadSamplesEstimate() const
Return an estimate of the sample count of the function entry basic block.
Definition: SampleProf.h:929
const FunctionSamples * findFunctionSamples(const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper=nullptr) const
Get the FunctionSamples of the inline instance where DIL originates from.
Definition: SampleProf.cpp:246
StringRef getName() const
Return the function name.
Definition: SampleProf.h:1050
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
Definition: SampleProf.h:953
static bool UseMD5
Whether the profile uses MD5 to represent string.
Definition: SampleProf.h:1167
Helper class for profile conversion.
Definition: SampleProf.h:1330
static void flattenProfile(SampleProfileMap &ProfileMap, bool ProfileIsCS=false)
Definition: SampleProf.h:1355
static void flattenProfile(const SampleProfileMap &InputProfiles, SampleProfileMap &OutputProfiles, bool ProfileIsCS=false)
Definition: SampleProf.h:1362
ProfileSymbolList records the list of function symbols shown up in the binary used to generate the pr...
Definition: SampleProf.h:1443
std::error_code write(raw_ostream &OS)
Definition: SampleProf.cpp:439
void dump(raw_ostream &OS=dbgs()) const
Definition: SampleProf.cpp:455
void merge(const ProfileSymbolList &List)
Definition: SampleProf.h:1457
void add(StringRef Name, bool copy=false)
copy indicates whether we need to copy the underlying memory for the input Name.
Definition: SampleProf.h:1447
std::error_code read(const uint8_t *Data, uint64_t ListSize)
Definition: SampleProf.cpp:326
SampleContextTrimmer impelements helper functions to trim, merge cold context profiles.
Definition: SampleProf.h:1304
SampleContextTrimmer(SampleProfileMap &Profiles)
Definition: SampleProf.h:1306
void trimAndMergeColdContextProfiles(uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext, uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly)
Definition: SampleProf.cpp:342
static void createCtxVectorFromStr(StringRef ContextStr, SampleContextFrameVector &Context)
Create a context vector from a given context string and save it in Context.
Definition: SampleProf.h:561
bool operator==(const SampleContext &That) const
Definition: SampleProf.h:653
SampleContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
Definition: SampleProf.h:530
bool operator<(const SampleContext &That) const
Definition: SampleProf.h:660
SampleContext(StringRef ContextStr, std::list< SampleContextFrameVector > &CSNameTable, ContextStateMask CState=RawContext)
Definition: SampleProf.h:540
bool hasState(ContextStateMask S)
Definition: SampleProf.h:606
void clearState(ContextStateMask S)
Definition: SampleProf.h:608
void setName(StringRef FunctionName)
Set the name of the function and clear the current context.
Definition: SampleProf.h:639
SampleContextFrames getContextFrames() const
Definition: SampleProf.h:612
static std::string getContextString(SampleContextFrames Context, bool IncludeLeafLineLocation=false)
Definition: SampleProf.h:614
bool operator!=(const SampleContext &That) const
Definition: SampleProf.h:658
void setState(ContextStateMask S)
Definition: SampleProf.h:607
void setAllAttributes(uint32_t A)
Definition: SampleProf.h:605
uint64_t getHashCode() const
Definition: SampleProf.h:633
void setContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
Definition: SampleProf.h:645
static void decodeContextString(StringRef ContextStr, StringRef &FName, LineLocation &LineLoc)
Definition: SampleProf.h:580
void setAttribute(ContextAttributeMask A)
Definition: SampleProf.h:603
bool IsPrefixOf(const SampleContext &That) const
Definition: SampleProf.h:689
bool hasAttribute(ContextAttributeMask A)
Definition: SampleProf.h:602
std::string toString() const
Definition: SampleProf.h:627
SampleProfileReaderItaniumRemapper remaps the profile data from a sample profile data reader,...
Representation of a single sample record.
Definition: SampleProf.h:331
bool hasCalls() const
Return true if this sample record contains function calls.
Definition: SampleProf.h:396
sampleprof_error merge(const SampleRecord &Other, uint64_t Weight=1)
Merge the samples in Other into this record.
Definition: SampleProf.cpp:119
const CallTargetMap & getCallTargets() const
Definition: SampleProf.h:399
std::set< CallTarget, CallTargetComparator > SortedCallTargetSet
Definition: SampleProf.h:343
uint64_t getSamples() const
Definition: SampleProf.h:398
uint64_t getCallTargetSum() const
Definition: SampleProf.h:404
uint64_t removeSamples(uint64_t S)
Decrease the number of samples for this record by S.
Definition: SampleProf.h:361
sampleprof_error addSamples(uint64_t S, uint64_t Weight=1)
Increment the number of samples for this record by S.
Definition: SampleProf.h:352
sampleprof_error addCalledTarget(StringRef F, uint64_t S, uint64_t Weight=1)
Add called function F with samples S.
Definition: SampleProf.h:373
std::pair< StringRef, uint64_t > CallTarget
Definition: SampleProf.h:333
StringMap< uint64_t > CallTargetMap
Definition: SampleProf.h:344
static const SortedCallTargetSet SortCallTargets(const CallTargetMap &Targets)
Sort call targets in descending order of call frequency.
Definition: SampleProf.h:412
const SortedCallTargetSet getSortedCallTargets() const
Definition: SampleProf.h:400
static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets, float DistributionFactor)
Prorate call targets by a distribution factor.
Definition: SampleProf.h:421
bool operator!=(const SampleRecord &Other) const
Definition: SampleProf.h:440
bool operator==(const SampleRecord &Other) const
Definition: SampleProf.h:436
uint64_t removeCalledTarget(StringRef F)
Remove called function from the call target map.
Definition: SampleProf.h:385
void print(raw_ostream &OS, unsigned Indent) const
Print the sample record to the stream OS indented by Indent.
Definition: SampleProf.cpp:134
Sort a LocationT->SampleT map by LocationT.
Definition: SampleProf.h:1282
std::pair< const LocationT, SampleT > SamplesWithLoc
Definition: SampleProf.h:1284
SampleSorter(const std::map< LocationT, SampleT > &Samples)
Definition: SampleProf.h:1287
const SamplesWithLocList & get() const
Definition: SampleProf.h:1295
SmallVector< const SamplesWithLoc *, 20 > SamplesWithLocList
Definition: SampleProf.h:1285
#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
@ FS
Definition: X86.h:208
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
static void verifySecFlag(SecType Type, SecFlagType Flag)
Definition: SampleProf.h:230
ArrayRef< SampleContextFrame > SampleContextFrames
Definition: SampleProf.h:505
void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
Definition: SampleProf.cpp:201
std::unordered_map< SampleContext, FunctionSamples, SampleContext::Hash > SampleProfileMap
Definition: SampleProf.h:1271
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
Definition: SampleProf.h:105
std::unordered_map< LineLocation, LineLocation, LineLocationHash > LocToLocMap
Definition: SampleProf.h:727
std::pair< SampleContext, const FunctionSamples * > NameFunctionSamples
Definition: SampleProf.h:1273
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition: SampleProf.h:257
raw_ostream & operator<<(raw_ostream &OS, const LineLocation &Loc)
Definition: SampleProf.cpp:111
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition: SampleProf.h:273
std::map< LineLocation, FunctionSamplesMap > CallsiteSampleMap
Definition: SampleProf.h:725
static StringRef getRepInFormat(StringRef Name, bool UseMD5, std::string &GUIDBuf)
Get the proper representation of a string according to whether the current Format uses MD5 to represe...
Definition: SampleProf.h:114
std::map< LineLocation, SampleRecord > BodySampleMap
Definition: SampleProf.h:721
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
@ SecFlagPartial
SecFlagPartial means the profile is for common/shared code.
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
static void removeSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition: SampleProf.h:265
static hash_code hash_value(const SampleContextFrame &arg)
Definition: SampleProf.h:499
static std::string getSecName(SecType Type)
Definition: SampleProf.h:140
std::map< std::string, FunctionSamples, std::less<> > FunctionSamplesMap
Definition: SampleProf.h:724
static uint64_t SPVersion()
Definition: SampleProf.h:122
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void stable_sort(R &&Range)
Definition: STLExtras.h:2063
std::error_code make_error_code(BitcodeError E)
sampleprof_error
Definition: SampleProf.h:46
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
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:619
const std::error_category & sampleprof_category()
Definition: SampleProf.cpp:100
std::string getUniqueInternalLinkagePostfix(const StringRef &FName)
Definition: SampleProf.h:1503
sampleprof_error MergeResult(sampleprof_error &Accumulator, sampleprof_error Result)
Definition: SampleProf.h:68
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1921
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition: Hashing.h:613
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:491
Definition: BitVector.h:858
static unsigned getHashValue(const SampleContext &Val)
Definition: SampleProf.h:1489
static SampleContext getTombstoneKey()
Definition: SampleProf.h:1487
static SampleContext getEmptyKey()
Definition: SampleProf.h:1485
static bool isEqual(const SampleContext &LHS, const SampleContext &RHS)
Definition: SampleProf.h:1493
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:51
uint64_t operator()(const LineLocation &Loc) const
Definition: SampleProf.h:313
Represents the relative location of an instruction.
Definition: SampleProf.h:289
void print(raw_ostream &OS) const
Definition: SampleProf.cpp:105
LineLocation(uint32_t L, uint32_t D)
Definition: SampleProf.h:290
bool operator!=(const LineLocation &O) const
Definition: SampleProf.h:304
bool operator<(const LineLocation &O) const
Definition: SampleProf.h:295
bool operator==(const LineLocation &O) const
Definition: SampleProf.h:300
FrameNode * getOrCreateChildFrame(const LineLocation &CallSite, StringRef CalleeName)
Definition: SampleProf.cpp:465
FrameNode(StringRef FName=StringRef(), FunctionSamples *FSamples=nullptr, LineLocation CallLoc={0, 0})
Definition: SampleProf.h:1337
std::map< uint64_t, FrameNode > AllChildFrames
Definition: SampleProf.h:1343
uint64_t operator()(const SampleContextFrameVector &S) const
Definition: SampleProf.h:508
bool operator==(const SampleContextFrame &That) const
Definition: SampleProf.h:479
bool operator!=(const SampleContextFrame &That) const
Definition: SampleProf.h:483
std::string toString(bool OutputLineLocation) const
Definition: SampleProf.h:487
SampleContextFrame(StringRef FuncName, LineLocation Location)
Definition: SampleProf.h:476
uint64_t operator()(const SampleContext &Context) const
Definition: SampleProf.h:684
bool operator()(const CallTarget &LHS, const CallTarget &RHS) const
Definition: SampleProf.h:335