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,
94 SPF_GCC = 0x3,
96 SPF_Binary = 0xff
97};
98
100 return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
101 uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
102 uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
103 uint64_t('2') << (64 - 56) | uint64_t(Format);
104}
105
106/// Get the proper representation of a string according to whether the
107/// current Format uses MD5 to represent the string.
108static inline StringRef getRepInFormat(StringRef Name, bool UseMD5,
109 std::string &GUIDBuf) {
110 if (Name.empty() || !UseMD5)
111 return Name;
112 GUIDBuf = std::to_string(Function::getGUID(Name));
113 return GUIDBuf;
114}
115
116static inline uint64_t SPVersion() { return 103; }
117
118// Section Type used by SampleProfileExtBinaryBaseReader and
119// SampleProfileExtBinaryBaseWriter. Never change the existing
120// value of enum. Only append new ones.
129 // marker for the first type of profile.
133
134static inline std::string getSecName(SecType Type) {
135 switch ((int)Type) { // Avoid -Wcovered-switch-default
136 case SecInValid:
137 return "InvalidSection";
138 case SecProfSummary:
139 return "ProfileSummarySection";
140 case SecNameTable:
141 return "NameTableSection";
143 return "ProfileSymbolListSection";
145 return "FuncOffsetTableSection";
146 case SecFuncMetadata:
147 return "FunctionMetadata";
148 case SecCSNameTable:
149 return "CSNameTableSection";
150 case SecLBRProfile:
151 return "LBRProfileSection";
152 default:
153 return "UnknownSection";
154 }
155}
156
157// Entry type of section header table used by SampleProfileExtBinaryBaseReader
158// and SampleProfileExtBinaryBaseWriter.
164 // The index indicating the location of the current entry in
165 // SectionHdrLayout table.
167};
168
169// Flags common for all sections are defined here. In SecHdrTableEntry::Flags,
170// common flags will be saved in the lower 32bits and section specific flags
171// will be saved in the higher 32 bits.
173 SecFlagInValid = 0,
174 SecFlagCompress = (1 << 0),
175 // Indicate the section contains only profile without context.
176 SecFlagFlat = (1 << 1)
177};
178
179// Section specific flags are defined here.
180// !!!Note: Everytime a new enum class is created here, please add
181// a new check in verifySecFlag.
183 SecFlagInValid = 0,
184 SecFlagMD5Name = (1 << 0),
185 // Store MD5 in fixed length instead of ULEB128 so NameTable can be
186 // accessed like an array.
187 SecFlagFixedLengthMD5 = (1 << 1),
188 // Profile contains ".__uniq." suffix name. Compiler shouldn't strip
189 // the suffix when doing profile matching when seeing the flag.
190 SecFlagUniqSuffix = (1 << 2)
191};
193 SecFlagInValid = 0,
194 /// SecFlagPartial means the profile is for common/shared code.
195 /// The common profile is usually merged from profiles collected
196 /// from running other targets.
197 SecFlagPartial = (1 << 0),
198 /// SecFlagContext means this is context-sensitive flat profile for
199 /// CSSPGO
200 SecFlagFullContext = (1 << 1),
201 /// SecFlagFSDiscriminator means this profile uses flow-sensitive
202 /// discriminators.
203 SecFlagFSDiscriminator = (1 << 2),
204 /// SecFlagIsPreInlined means this profile contains ShouldBeInlined
205 /// contexts thus this is CS preinliner computed.
206 SecFlagIsPreInlined = (1 << 4),
207};
208
210 SecFlagInvalid = 0,
211 SecFlagIsProbeBased = (1 << 0),
212 SecFlagHasAttribute = (1 << 1),
213};
214
216 SecFlagInvalid = 0,
217 // Store function offsets in an order of contexts. The order ensures that
218 // callee contexts of a given context laid out next to it.
219 SecFlagOrdered = (1 << 0),
220};
221
222// Verify section specific flag is used for the correct section.
223template <class SecFlagType>
224static inline void verifySecFlag(SecType Type, SecFlagType Flag) {
225 // No verification is needed for common flags.
226 if (std::is_same<SecCommonFlags, SecFlagType>())
227 return;
228
229 // Verification starts here for section specific flag.
230 bool IsFlagLegal = false;
231 switch (Type) {
232 case SecNameTable:
233 IsFlagLegal = std::is_same<SecNameTableFlags, SecFlagType>();
234 break;
235 case SecProfSummary:
236 IsFlagLegal = std::is_same<SecProfSummaryFlags, SecFlagType>();
237 break;
238 case SecFuncMetadata:
239 IsFlagLegal = std::is_same<SecFuncMetadataFlags, SecFlagType>();
240 break;
241 default:
243 IsFlagLegal = std::is_same<SecFuncOffsetFlags, SecFlagType>();
244 break;
245 }
246 if (!IsFlagLegal)
247 llvm_unreachable("Misuse of a flag in an incompatible section");
248}
249
250template <class SecFlagType>
251static inline void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
252 verifySecFlag(Entry.Type, Flag);
253 auto FVal = static_cast<uint64_t>(Flag);
254 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
255 Entry.Flags |= IsCommon ? FVal : (FVal << 32);
256}
257
258template <class SecFlagType>
259static inline void removeSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
260 verifySecFlag(Entry.Type, Flag);
261 auto FVal = static_cast<uint64_t>(Flag);
262 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
263 Entry.Flags &= ~(IsCommon ? FVal : (FVal << 32));
264}
265
266template <class SecFlagType>
267static inline bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag) {
268 verifySecFlag(Entry.Type, Flag);
269 auto FVal = static_cast<uint64_t>(Flag);
270 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
271 return Entry.Flags & (IsCommon ? FVal : (FVal << 32));
272}
273
274/// Represents the relative location of an instruction.
275///
276/// Instruction locations are specified by the line offset from the
277/// beginning of the function (marked by the line where the function
278/// header is) and the discriminator value within that line.
279///
280/// The discriminator value is useful to distinguish instructions
281/// that are on the same line but belong to different basic blocks
282/// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
285
286 void print(raw_ostream &OS) const;
287 void dump() const;
288
289 bool operator<(const LineLocation &O) const {
290 return LineOffset < O.LineOffset ||
291 (LineOffset == O.LineOffset && Discriminator < O.Discriminator);
292 }
293
294 bool operator==(const LineLocation &O) const {
295 return LineOffset == O.LineOffset && Discriminator == O.Discriminator;
296 }
297
298 bool operator!=(const LineLocation &O) const {
299 return LineOffset != O.LineOffset || Discriminator != O.Discriminator;
300 }
301
304};
305
307 uint64_t operator()(const LineLocation &Loc) const {
308 return std::hash<std::uint64_t>{}((((uint64_t)Loc.LineOffset) << 32) |
309 Loc.Discriminator);
310 }
311};
312
314
315/// Representation of a single sample record.
316///
317/// A sample record is represented by a positive integer value, which
318/// indicates how frequently was the associated line location executed.
319///
320/// Additionally, if the associated location contains a function call,
321/// the record will hold a list of all the possible called targets. For
322/// direct calls, this will be the exact function being invoked. For
323/// indirect calls (function pointers, virtual table dispatch), this
324/// will be a list of one or more functions.
326public:
327 using CallTarget = std::pair<StringRef, uint64_t>;
329 bool operator()(const CallTarget &LHS, const CallTarget &RHS) const {
330 if (LHS.second != RHS.second)
331 return LHS.second > RHS.second;
332
333 return LHS.first < RHS.first;
334 }
335 };
336
337 using SortedCallTargetSet = std::set<CallTarget, CallTargetComparator>;
339 SampleRecord() = default;
340
341 /// Increment the number of samples for this record by \p S.
342 /// Optionally scale sample count \p S by \p Weight.
343 ///
344 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
345 /// around unsigned integers.
347 bool Overflowed;
348 NumSamples = SaturatingMultiplyAdd(S, Weight, NumSamples, &Overflowed);
349 return Overflowed ? sampleprof_error::counter_overflow
351 }
352
353 /// Decrease the number of samples for this record by \p S. Return the amout
354 /// of samples actually decreased.
356 if (S > NumSamples)
357 S = NumSamples;
358 NumSamples -= S;
359 return S;
360 }
361
362 /// Add called function \p F with samples \p S.
363 /// Optionally scale sample count \p S by \p Weight.
364 ///
365 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
366 /// around unsigned integers.
368 uint64_t Weight = 1) {
369 uint64_t &TargetSamples = CallTargets[F];
370 bool Overflowed;
371 TargetSamples =
372 SaturatingMultiplyAdd(S, Weight, TargetSamples, &Overflowed);
373 return Overflowed ? sampleprof_error::counter_overflow
375 }
376
377 /// Remove called function from the call target map. Return the target sample
378 /// count of the called function.
380 uint64_t Count = 0;
381 auto I = CallTargets.find(F);
382 if (I != CallTargets.end()) {
383 Count = I->second;
384 CallTargets.erase(I);
385 }
386 return Count;
387 }
388
389 /// Return true if this sample record contains function calls.
390 bool hasCalls() const { return !CallTargets.empty(); }
391
392 uint64_t getSamples() const { return NumSamples; }
393 const CallTargetMap &getCallTargets() const { return CallTargets; }
395 return SortCallTargets(CallTargets);
396 }
397
399 uint64_t Sum = 0;
400 for (const auto &I : CallTargets)
401 Sum += I.second;
402 return Sum;
403 }
404
405 /// Sort call targets in descending order of call frequency.
407 SortedCallTargetSet SortedTargets;
408 for (const auto &[Target, Frequency] : Targets) {
409 SortedTargets.emplace(Target, Frequency);
410 }
411 return SortedTargets;
412 }
413
414 /// Prorate call targets by a distribution factor.
416 float DistributionFactor) {
417 CallTargetMap AdjustedTargets;
418 for (const auto &[Target, Frequency] : Targets) {
419 AdjustedTargets[Target] = Frequency * DistributionFactor;
420 }
421 return AdjustedTargets;
422 }
423
424 /// Merge the samples in \p Other into this record.
425 /// Optionally scale sample counts by \p Weight.
427 void print(raw_ostream &OS, unsigned Indent) const;
428 void dump() const;
429
430 bool operator==(const SampleRecord &Other) const {
431 return NumSamples == Other.NumSamples && CallTargets == Other.CallTargets;
432 }
433
434 bool operator!=(const SampleRecord &Other) const {
435 return !(*this == Other);
436 }
437
438private:
439 uint64_t NumSamples = 0;
440 CallTargetMap CallTargets;
441};
442
444
445// State of context associated with FunctionSamples
447 UnknownContext = 0x0, // Profile without context
448 RawContext = 0x1, // Full context profile from input profile
449 SyntheticContext = 0x2, // Synthetic context created for context promotion
450 InlinedContext = 0x4, // Profile for context that is inlined into caller
451 MergedContext = 0x8 // Profile for context merged into base profile
453
454// Attribute of context associated with FunctionSamples
457 ContextWasInlined = 0x1, // Leaf of context was inlined in previous build
458 ContextShouldBeInlined = 0x2, // Leaf of context should be inlined
460 0x4, // Leaf of context is duplicated into the base profile
461};
462
463// Represents a context frame with function name and line location
467
469
472
473 bool operator==(const SampleContextFrame &That) const {
474 return Location == That.Location && FuncName == That.FuncName;
475 }
476
477 bool operator!=(const SampleContextFrame &That) const {
478 return !(*this == That);
479 }
480
481 std::string toString(bool OutputLineLocation) const {
482 std::ostringstream OContextStr;
483 OContextStr << FuncName.str();
484 if (OutputLineLocation) {
485 OContextStr << ":" << Location.LineOffset;
487 OContextStr << "." << Location.Discriminator;
488 }
489 return OContextStr.str();
490 }
491};
492
493static inline hash_code hash_value(const SampleContextFrame &arg) {
496}
497
500
503 return hash_combine_range(S.begin(), S.end());
504 }
505};
506
507// Sample context for FunctionSamples. It consists of the calling context,
508// the function name and context state. Internally sample context is represented
509// using ArrayRef, which is also the input for constructing a `SampleContext`.
510// It can accept and represent both full context string as well as context-less
511// function name.
512// For a CS profile, a full context vector can look like:
513// `main:3 _Z5funcAi:1 _Z8funcLeafi`
514// For a base CS profile without calling context, the context vector should only
515// contain the leaf frame name.
516// For a non-CS profile, the context vector should be empty.
518public:
519 SampleContext() : State(UnknownContext), Attributes(ContextNone) {}
520
522 : Name(Name), State(UnknownContext), Attributes(ContextNone) {}
523
526 : Attributes(ContextNone) {
527 assert(!Context.empty() && "Context is empty");
528 setContext(Context, CState);
529 }
530
531 // Give a context string, decode and populate internal states like
532 // Function name, Calling context and context state. Example of input
533 // `ContextStr`: `[main:3 @ _Z5funcAi:1 @ _Z8funcLeafi]`
535 std::list<SampleContextFrameVector> &CSNameTable,
537 : Attributes(ContextNone) {
538 assert(!ContextStr.empty());
539 // Note that `[]` wrapped input indicates a full context string, otherwise
540 // it's treated as context-less function name only.
541 bool HasContext = ContextStr.startswith("[");
542 if (!HasContext) {
543 State = UnknownContext;
544 Name = ContextStr;
545 } else {
546 CSNameTable.emplace_back();
547 SampleContextFrameVector &Context = CSNameTable.back();
548 createCtxVectorFromStr(ContextStr, Context);
549 setContext(Context, CState);
550 }
551 }
552
553 /// Create a context vector from a given context string and save it in
554 /// `Context`.
555 static void createCtxVectorFromStr(StringRef ContextStr,
556 SampleContextFrameVector &Context) {
557 // Remove encapsulating '[' and ']' if any
558 ContextStr = ContextStr.substr(1, ContextStr.size() - 2);
559 StringRef ContextRemain = ContextStr;
560 StringRef ChildContext;
561 StringRef CalleeName;
562 while (!ContextRemain.empty()) {
563 auto ContextSplit = ContextRemain.split(" @ ");
564 ChildContext = ContextSplit.first;
565 ContextRemain = ContextSplit.second;
566 LineLocation CallSiteLoc(0, 0);
567 decodeContextString(ChildContext, CalleeName, CallSiteLoc);
568 Context.emplace_back(CalleeName, CallSiteLoc);
569 }
570 }
571
572 // Decode context string for a frame to get function name and location.
573 // `ContextStr` is in the form of `FuncName:StartLine.Discriminator`.
574 static void decodeContextString(StringRef ContextStr, StringRef &FName,
575 LineLocation &LineLoc) {
576 // Get function name
577 auto EntrySplit = ContextStr.split(':');
578 FName = EntrySplit.first;
579
580 LineLoc = {0, 0};
581 if (!EntrySplit.second.empty()) {
582 // Get line offset, use signed int for getAsInteger so string will
583 // be parsed as signed.
584 int LineOffset = 0;
585 auto LocSplit = EntrySplit.second.split('.');
586 LocSplit.first.getAsInteger(10, LineOffset);
587 LineLoc.LineOffset = LineOffset;
588
589 // Get discriminator
590 if (!LocSplit.second.empty())
591 LocSplit.second.getAsInteger(10, LineLoc.Discriminator);
592 }
593 }
594
595 operator SampleContextFrames() const { return FullContext; }
596 bool hasAttribute(ContextAttributeMask A) { return Attributes & (uint32_t)A; }
597 void setAttribute(ContextAttributeMask A) { Attributes |= (uint32_t)A; }
598 uint32_t getAllAttributes() { return Attributes; }
599 void setAllAttributes(uint32_t A) { Attributes = A; }
600 bool hasState(ContextStateMask S) { return State & (uint32_t)S; }
601 void setState(ContextStateMask S) { State |= (uint32_t)S; }
602 void clearState(ContextStateMask S) { State &= (uint32_t)~S; }
603 bool hasContext() const { return State != UnknownContext; }
604 bool isBaseContext() const { return FullContext.size() == 1; }
605 StringRef getName() const { return Name; }
606 SampleContextFrames getContextFrames() const { return FullContext; }
607
608 static std::string getContextString(SampleContextFrames Context,
609 bool IncludeLeafLineLocation = false) {
610 std::ostringstream OContextStr;
611 for (uint32_t I = 0; I < Context.size(); I++) {
612 if (OContextStr.str().size()) {
613 OContextStr << " @ ";
614 }
615 OContextStr << Context[I].toString(I != Context.size() - 1 ||
616 IncludeLeafLineLocation);
617 }
618 return OContextStr.str();
619 }
620
621 std::string toString() const {
622 if (!hasContext())
623 return Name.str();
624 return getContextString(FullContext, false);
625 }
626
629 : hash_value(getName());
630 }
631
632 /// Set the name of the function and clear the current context.
633 void setName(StringRef FunctionName) {
634 Name = FunctionName;
635 FullContext = SampleContextFrames();
636 State = UnknownContext;
637 }
638
640 ContextStateMask CState = RawContext) {
641 assert(CState != UnknownContext);
642 FullContext = Context;
643 Name = Context.back().FuncName;
644 State = CState;
645 }
646
647 bool operator==(const SampleContext &That) const {
648 return State == That.State && Name == That.Name &&
649 FullContext == That.FullContext;
650 }
651
652 bool operator!=(const SampleContext &That) const { return !(*this == That); }
653
654 bool operator<(const SampleContext &That) const {
655 if (State != That.State)
656 return State < That.State;
657
658 if (!hasContext()) {
659 return Name < That.Name;
660 }
661
662 uint64_t I = 0;
663 while (I < std::min(FullContext.size(), That.FullContext.size())) {
664 auto &Context1 = FullContext[I];
665 auto &Context2 = That.FullContext[I];
666 auto V = Context1.FuncName.compare(Context2.FuncName);
667 if (V)
668 return V < 0;
669 if (Context1.Location != Context2.Location)
670 return Context1.Location < Context2.Location;
671 I++;
672 }
673
674 return FullContext.size() < That.FullContext.size();
675 }
676
677 struct Hash {
678 uint64_t operator()(const SampleContext &Context) const {
679 return Context.getHashCode();
680 }
681 };
682
683 bool IsPrefixOf(const SampleContext &That) const {
684 auto ThisContext = FullContext;
685 auto ThatContext = That.FullContext;
686 if (ThatContext.size() < ThisContext.size())
687 return false;
688 ThatContext = ThatContext.take_front(ThisContext.size());
689 // Compare Leaf frame first
690 if (ThisContext.back().FuncName != ThatContext.back().FuncName)
691 return false;
692 // Compare leading context
693 return ThisContext.drop_back() == ThatContext.drop_back();
694 }
695
696private:
697 /// Mangled name of the function.
698 StringRef Name;
699 // Full context including calling context and leaf function name
700 SampleContextFrames FullContext;
701 // State of the associated sample profile
702 uint32_t State;
703 // Attribute of the associated sample profile
704 uint32_t Attributes;
705};
706
707static inline hash_code hash_value(const SampleContext &arg) {
708 return arg.hasContext() ? hash_value(arg.getContextFrames())
709 : hash_value(arg.getName());
710}
711
712class FunctionSamples;
714
715using BodySampleMap = std::map<LineLocation, SampleRecord>;
716// NOTE: Using a StringMap here makes parsed profiles consume around 17% more
717// memory, which is *very* significant for large profiles.
718using FunctionSamplesMap = std::map<std::string, FunctionSamples, std::less<>>;
719using CallsiteSampleMap = std::map<LineLocation, FunctionSamplesMap>;
720
721/// Representation of the samples collected for a function.
722///
723/// This data structure contains all the collected samples for the body
724/// of a function. Each sample corresponds to a LineLocation instance
725/// within the body of the function.
727public:
728 FunctionSamples() = default;
729
730 void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
731 void dump() const;
732
734 bool Overflowed;
735 TotalSamples =
736 SaturatingMultiplyAdd(Num, Weight, TotalSamples, &Overflowed);
737 return Overflowed ? sampleprof_error::counter_overflow
739 }
740
742 if (TotalSamples < Num)
743 TotalSamples = 0;
744 else
745 TotalSamples -= Num;
746 }
747
748 void setTotalSamples(uint64_t Num) { TotalSamples = Num; }
749
751 bool Overflowed;
752 TotalHeadSamples =
753 SaturatingMultiplyAdd(Num, Weight, TotalHeadSamples, &Overflowed);
754 return Overflowed ? sampleprof_error::counter_overflow
756 }
757
759 uint64_t Num, uint64_t Weight = 1) {
760 return BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(
761 Num, Weight);
762 }
763
765 uint32_t Discriminator,
766 StringRef FName, uint64_t Num,
767 uint64_t Weight = 1) {
768 return BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(
769 FName, Num, Weight);
770 }
771
772 // Remove a call target and decrease the body sample correspondingly. Return
773 // the number of body samples actually decreased.
775 uint32_t Discriminator,
776 StringRef FName) {
777 uint64_t Count = 0;
778 auto I = BodySamples.find(LineLocation(LineOffset, Discriminator));
779 if (I != BodySamples.end()) {
780 Count = I->second.removeCalledTarget(FName);
781 Count = I->second.removeSamples(Count);
782 if (!I->second.getSamples())
783 BodySamples.erase(I);
784 }
785 return Count;
786 }
787
789 uint64_t Weight = 1) {
790 SampleRecord S;
791 S.addSamples(Num, Weight);
792 return BodySamples[LineLocation(Index, 0)].merge(S, Weight);
793 }
794
795 // Accumulate all call target samples to update the body samples.
797 for (auto &I : BodySamples) {
798 uint64_t TargetSamples = I.second.getCallTargetSum();
799 // It's possible that the body sample count can be greater than the call
800 // target sum. E.g, if some call targets are external targets, they won't
801 // be considered valid call targets, but the body sample count which is
802 // from lbr ranges can actually include them.
803 if (TargetSamples > I.second.getSamples())
804 I.second.addSamples(TargetSamples - I.second.getSamples());
805 }
806 }
807
808 // Accumulate all body samples to set total samples.
811 for (const auto &I : BodySamples)
812 addTotalSamples(I.second.getSamples());
813
814 for (auto &I : CallsiteSamples) {
815 for (auto &CS : I.second) {
816 CS.second.updateTotalSamples();
817 addTotalSamples(CS.second.getTotalSamples());
818 }
819 }
820 }
821
822 // Set current context and all callee contexts to be synthetic.
824 Context.setState(SyntheticContext);
825 for (auto &I : CallsiteSamples) {
826 for (auto &CS : I.second) {
827 CS.second.SetContextSynthetic();
828 }
829 }
830 }
831
832 /// Return the number of samples collected at the given location.
833 /// Each location is specified by \p LineOffset and \p Discriminator.
834 /// If the location is not found in profile, return error.
836 uint32_t Discriminator) const {
837 const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
838 if (ret == BodySamples.end())
839 return std::error_code();
840 return ret->second.getSamples();
841 }
842
843 /// Returns the call target map collected at a given location.
844 /// Each location is specified by \p LineOffset and \p Discriminator.
845 /// If the location is not found in profile, return error.
847 findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const {
848 const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
849 if (ret == BodySamples.end())
850 return std::error_code();
851 return ret->second.getCallTargets();
852 }
853
854 /// Returns the call target map collected at a given location specified by \p
855 /// CallSite. If the location is not found in profile, return error.
857 findCallTargetMapAt(const LineLocation &CallSite) const {
858 const auto &Ret = BodySamples.find(CallSite);
859 if (Ret == BodySamples.end())
860 return std::error_code();
861 return Ret->second.getCallTargets();
862 }
863
864 /// Return the function samples at the given callsite location.
866 return CallsiteSamples[Loc];
867 }
868
869 /// Returns the FunctionSamplesMap at the given \p Loc.
870 const FunctionSamplesMap *
872 auto iter = CallsiteSamples.find(Loc);
873 if (iter == CallsiteSamples.end())
874 return nullptr;
875 return &iter->second;
876 }
877
878 /// Returns a pointer to FunctionSamples at the given callsite location
879 /// \p Loc with callee \p CalleeName. If no callsite can be found, relax
880 /// the restriction to return the FunctionSamples at callsite location
881 /// \p Loc with the maximum total sample count. If \p Remapper is not
882 /// nullptr, use \p Remapper to find FunctionSamples with equivalent name
883 /// as \p CalleeName.
884 const FunctionSamples *
885 findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName,
886 SampleProfileReaderItaniumRemapper *Remapper) const;
887
888 bool empty() const { return TotalSamples == 0; }
889
890 /// Return the total number of samples collected inside the function.
891 uint64_t getTotalSamples() const { return TotalSamples; }
892
893 /// For top-level functions, return the total number of branch samples that
894 /// have the function as the branch target (or 0 otherwise). This is the raw
895 /// data fetched from the profile. This should be equivalent to the sample of
896 /// the first instruction of the symbol. But as we directly get this info for
897 /// raw profile without referring to potentially inaccurate debug info, this
898 /// gives more accurate profile data and is preferred for standalone symbols.
899 uint64_t getHeadSamples() const { return TotalHeadSamples; }
900
901 /// Return an estimate of the sample count of the function entry basic block.
902 /// The function can be either a standalone symbol or an inlined function.
903 /// For Context-Sensitive profiles, this will prefer returning the head
904 /// samples (i.e. getHeadSamples()), if non-zero. Otherwise it estimates from
905 /// the function body's samples or callsite samples.
908 // For CS profile, if we already have more accurate head samples
909 // counted by branch sample from caller, use them as entry samples.
910 return getHeadSamples();
911 }
912 uint64_t Count = 0;
913 // Use either BodySamples or CallsiteSamples which ever has the smaller
914 // lineno.
915 if (!BodySamples.empty() &&
916 (CallsiteSamples.empty() ||
917 BodySamples.begin()->first < CallsiteSamples.begin()->first))
918 Count = BodySamples.begin()->second.getSamples();
919 else if (!CallsiteSamples.empty()) {
920 // An indirect callsite may be promoted to several inlined direct calls.
921 // We need to get the sum of them.
922 for (const auto &N_FS : CallsiteSamples.begin()->second)
923 Count += N_FS.second.getHeadSamplesEstimate();
924 }
925 // Return at least 1 if total sample is not 0.
926 return Count ? Count : TotalSamples > 0;
927 }
928
929 /// Return all the samples collected in the body of the function.
930 const BodySampleMap &getBodySamples() const { return BodySamples; }
931
932 /// Return all the callsite samples collected in the body of the function.
934 return CallsiteSamples;
935 }
936
937 /// Return the maximum of sample counts in a function body. When SkipCallSite
938 /// is false, which is the default, the return count includes samples in the
939 /// inlined functions. When SkipCallSite is true, the return count only
940 /// considers the body samples.
941 uint64_t getMaxCountInside(bool SkipCallSite = false) const {
942 uint64_t MaxCount = 0;
943 for (const auto &L : getBodySamples())
944 MaxCount = std::max(MaxCount, L.second.getSamples());
945 if (SkipCallSite)
946 return MaxCount;
947 for (const auto &C : getCallsiteSamples())
948 for (const FunctionSamplesMap::value_type &F : C.second)
949 MaxCount = std::max(MaxCount, F.second.getMaxCountInside());
950 return MaxCount;
951 }
952
953 /// Merge the samples in \p Other into this one.
954 /// Optionally scale samples by \p Weight.
958 GUIDToFuncNameMap = Other.GUIDToFuncNameMap;
959 if (Context.getName().empty())
960 Context = Other.getContext();
961 if (FunctionHash == 0) {
962 // Set the function hash code for the target profile.
963 FunctionHash = Other.getFunctionHash();
964 } else if (FunctionHash != Other.getFunctionHash()) {
965 // The two profiles coming with different valid hash codes indicates
966 // either:
967 // 1. They are same-named static functions from different compilation
968 // units (without using -unique-internal-linkage-names), or
969 // 2. They are really the same function but from different compilations.
970 // Let's bail out in either case for now, which means one profile is
971 // dropped.
973 }
974
975 MergeResult(Result, addTotalSamples(Other.getTotalSamples(), Weight));
976 MergeResult(Result, addHeadSamples(Other.getHeadSamples(), Weight));
977 for (const auto &I : Other.getBodySamples()) {
978 const LineLocation &Loc = I.first;
979 const SampleRecord &Rec = I.second;
980 MergeResult(Result, BodySamples[Loc].merge(Rec, Weight));
981 }
982 for (const auto &I : Other.getCallsiteSamples()) {
983 const LineLocation &Loc = I.first;
985 for (const auto &Rec : I.second)
986 MergeResult(Result, FSMap[Rec.first].merge(Rec.second, Weight));
987 }
988 return Result;
989 }
990
991 /// Recursively traverses all children, if the total sample count of the
992 /// corresponding function is no less than \p Threshold, add its corresponding
993 /// GUID to \p S. Also traverse the BodySamples to add hot CallTarget's GUID
994 /// to \p S.
996 const StringMap<Function *> &SymbolMap,
997 uint64_t Threshold) const {
998 if (TotalSamples <= Threshold)
999 return;
1000 auto isDeclaration = [](const Function *F) {
1001 return !F || F->isDeclaration();
1002 };
1003 if (isDeclaration(SymbolMap.lookup(getFuncName()))) {
1004 // Add to the import list only when it's defined out of module.
1005 S.insert(getGUID(getName()));
1006 }
1007 // Import hot CallTargets, which may not be available in IR because full
1008 // profile annotation cannot be done until backend compilation in ThinLTO.
1009 for (const auto &BS : BodySamples)
1010 for (const auto &TS : BS.second.getCallTargets())
1011 if (TS.getValue() > Threshold) {
1012 const Function *Callee = SymbolMap.lookup(getFuncName(TS.getKey()));
1013 if (isDeclaration(Callee))
1014 S.insert(getGUID(TS.getKey()));
1015 }
1016 for (const auto &CS : CallsiteSamples)
1017 for (const auto &NameFS : CS.second)
1018 NameFS.second.findInlinedFunctions(S, SymbolMap, Threshold);
1019 }
1020
1021 /// Set the name of the function.
1022 void setName(StringRef FunctionName) { Context.setName(FunctionName); }
1023
1024 /// Return the function name.
1025 StringRef getName() const { return Context.getName(); }
1026
1027 /// Return the original function name.
1029
1030 void setFunctionHash(uint64_t Hash) { FunctionHash = Hash; }
1031
1032 uint64_t getFunctionHash() const { return FunctionHash; }
1033
1034 /// Return the canonical name for a function, taking into account
1035 /// suffix elision policy attributes.
1037 auto AttrName = "sample-profile-suffix-elision-policy";
1038 auto Attr = F.getFnAttribute(AttrName).getValueAsString();
1039 return getCanonicalFnName(F.getName(), Attr);
1040 }
1041
1042 /// Name suffixes which canonicalization should handle to avoid
1043 /// profile mismatch.
1044 static constexpr const char *LLVMSuffix = ".llvm.";
1045 static constexpr const char *PartSuffix = ".part.";
1046 static constexpr const char *UniqSuffix = ".__uniq.";
1047
1049 StringRef Attr = "selected") {
1050 // Note the sequence of the suffixes in the knownSuffixes array matters.
1051 // If suffix "A" is appended after the suffix "B", "A" should be in front
1052 // of "B" in knownSuffixes.
1053 const char *knownSuffixes[] = {LLVMSuffix, PartSuffix, UniqSuffix};
1054 if (Attr == "" || Attr == "all") {
1055 return FnName.split('.').first;
1056 } else if (Attr == "selected") {
1057 StringRef Cand(FnName);
1058 for (const auto &Suf : knownSuffixes) {
1059 StringRef Suffix(Suf);
1060 // If the profile contains ".__uniq." suffix, don't strip the
1061 // suffix for names in the IR.
1063 continue;
1064 auto It = Cand.rfind(Suffix);
1065 if (It == StringRef::npos)
1066 continue;
1067 auto Dit = Cand.rfind('.');
1068 if (Dit == It + Suffix.size() - 1)
1069 Cand = Cand.substr(0, It);
1070 }
1071 return Cand;
1072 } else if (Attr == "none") {
1073 return FnName;
1074 } else {
1075 assert(false && "internal error: unknown suffix elision policy");
1076 }
1077 return FnName;
1078 }
1079
1080 /// Translate \p Name into its original name.
1081 /// When profile doesn't use MD5, \p Name needs no translation.
1082 /// When profile uses MD5, \p Name in current FunctionSamples
1083 /// is actually GUID of the original function name. getFuncName will
1084 /// translate \p Name in current FunctionSamples into its original name
1085 /// by looking up in the function map GUIDToFuncNameMap.
1086 /// If the original name doesn't exist in the map, return empty StringRef.
1088 if (!UseMD5)
1089 return Name;
1090
1091 assert(GUIDToFuncNameMap && "GUIDToFuncNameMap needs to be populated first");
1092 return GUIDToFuncNameMap->lookup(std::stoull(Name.data()));
1093 }
1094
1095 /// Returns the line offset to the start line of the subprogram.
1096 /// We assume that a single function will not exceed 65535 LOC.
1097 static unsigned getOffset(const DILocation *DIL);
1098
1099 /// Returns a unique call site identifier for a given debug location of a call
1100 /// instruction. This is wrapper of two scenarios, the probe-based profile and
1101 /// regular profile, to hide implementation details from the sample loader and
1102 /// the context tracker.
1104 bool ProfileIsFS = false);
1105
1106 /// Returns a unique hash code for a combination of a callsite location and
1107 /// the callee function name.
1108 static uint64_t getCallSiteHash(StringRef CalleeName,
1109 const LineLocation &Callsite);
1110
1111 /// Get the FunctionSamples of the inline instance where DIL originates
1112 /// from.
1113 ///
1114 /// The FunctionSamples of the instruction (Machine or IR) associated to
1115 /// \p DIL is the inlined instance in which that instruction is coming from.
1116 /// We traverse the inline stack of that instruction, and match it with the
1117 /// tree nodes in the profile.
1118 ///
1119 /// \returns the FunctionSamples pointer to the inlined instance.
1120 /// If \p Remapper is not nullptr, it will be used to find matching
1121 /// FunctionSamples with not exactly the same but equivalent name.
1123 const DILocation *DIL,
1124 SampleProfileReaderItaniumRemapper *Remapper = nullptr) const;
1125
1127
1128 static bool ProfileIsCS;
1129
1131
1132 SampleContext &getContext() const { return Context; }
1133
1134 void setContext(const SampleContext &FContext) { Context = FContext; }
1135
1136 /// Whether the profile uses MD5 to represent string.
1137 static bool UseMD5;
1138
1139 /// Whether the profile contains any ".__uniq." suffix in a name.
1140 static bool HasUniqSuffix;
1141
1142 /// If this profile uses flow sensitive discriminators.
1143 static bool ProfileIsFS;
1144
1145 /// GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
1146 /// all the function symbols defined or declared in current module.
1148
1149 // Assume the input \p Name is a name coming from FunctionSamples itself.
1150 // If UseMD5 is true, the name is already a GUID and we
1151 // don't want to return the GUID of GUID.
1153 return UseMD5 ? std::stoull(Name.data()) : Function::getGUID(Name);
1154 }
1155
1156 // Find all the names in the current FunctionSamples including names in
1157 // all the inline instances and names of call targets.
1158 void findAllNames(DenseSet<StringRef> &NameSet) const;
1159
1160 bool operator==(const FunctionSamples &Other) const {
1161 return (GUIDToFuncNameMap == Other.GUIDToFuncNameMap ||
1162 (GUIDToFuncNameMap && Other.GUIDToFuncNameMap &&
1163 *GUIDToFuncNameMap == *Other.GUIDToFuncNameMap)) &&
1164 FunctionHash == Other.FunctionHash && Context == Other.Context &&
1165 TotalSamples == Other.TotalSamples &&
1166 TotalHeadSamples == Other.TotalHeadSamples &&
1167 BodySamples == Other.BodySamples &&
1168 CallsiteSamples == Other.CallsiteSamples;
1169 }
1170
1171 bool operator!=(const FunctionSamples &Other) const {
1172 return !(*this == Other);
1173 }
1174
1175private:
1176 /// CFG hash value for the function.
1177 uint64_t FunctionHash = 0;
1178
1179 /// Calling context for function profile
1180 mutable SampleContext Context;
1181
1182 /// Total number of samples collected inside this function.
1183 ///
1184 /// Samples are cumulative, they include all the samples collected
1185 /// inside this function and all its inlined callees.
1186 uint64_t TotalSamples = 0;
1187
1188 /// Total number of samples collected at the head of the function.
1189 /// This is an approximation of the number of calls made to this function
1190 /// at runtime.
1191 uint64_t TotalHeadSamples = 0;
1192
1193 /// Map instruction locations to collected samples.
1194 ///
1195 /// Each entry in this map contains the number of samples
1196 /// collected at the corresponding line offset. All line locations
1197 /// are an offset from the start of the function.
1198 BodySampleMap BodySamples;
1199
1200 /// Map call sites to collected samples for the called function.
1201 ///
1202 /// Each entry in this map corresponds to all the samples
1203 /// collected for the inlined function call at the given
1204 /// location. For example, given:
1205 ///
1206 /// void foo() {
1207 /// 1 bar();
1208 /// ...
1209 /// 8 baz();
1210 /// }
1211 ///
1212 /// If the bar() and baz() calls were inlined inside foo(), this
1213 /// map will contain two entries. One for all the samples collected
1214 /// in the call to bar() at line offset 1, the other for all the samples
1215 /// collected in the call to baz() at line offset 8.
1216 CallsiteSampleMap CallsiteSamples;
1217};
1218
1220
1222 std::unordered_map<SampleContext, FunctionSamples, SampleContext::Hash>;
1223
1224using NameFunctionSamples = std::pair<SampleContext, const FunctionSamples *>;
1225
1226void sortFuncProfiles(const SampleProfileMap &ProfileMap,
1227 std::vector<NameFunctionSamples> &SortedProfiles);
1228
1229/// Sort a LocationT->SampleT map by LocationT.
1230///
1231/// It produces a sorted list of <LocationT, SampleT> records by ascending
1232/// order of LocationT.
1233template <class LocationT, class SampleT> class SampleSorter {
1234public:
1235 using SamplesWithLoc = std::pair<const LocationT, SampleT>;
1237
1238 SampleSorter(const std::map<LocationT, SampleT> &Samples) {
1239 for (const auto &I : Samples)
1240 V.push_back(&I);
1241 llvm::stable_sort(V, [](const SamplesWithLoc *A, const SamplesWithLoc *B) {
1242 return A->first < B->first;
1243 });
1244 }
1245
1246 const SamplesWithLocList &get() const { return V; }
1247
1248private:
1250};
1251
1252/// SampleContextTrimmer impelements helper functions to trim, merge cold
1253/// context profiles. It also supports context profile canonicalization to make
1254/// sure ProfileMap's key is consistent with FunctionSample's name/context.
1256public:
1257 SampleContextTrimmer(SampleProfileMap &Profiles) : ProfileMap(Profiles){};
1258 // Trim and merge cold context profile when requested. TrimBaseProfileOnly
1259 // should only be effective when TrimColdContext is true. On top of
1260 // TrimColdContext, TrimBaseProfileOnly can be used to specify to trim all
1261 // cold profiles or only cold base profiles. Trimming base profiles only is
1262 // mainly to honor the preinliner decsion. Note that when MergeColdContext is
1263 // true, preinliner decsion is not honored anyway so TrimBaseProfileOnly will
1264 // be ignored.
1266 bool TrimColdContext,
1267 bool MergeColdContext,
1268 uint32_t ColdContextFrameLength,
1269 bool TrimBaseProfileOnly);
1270 // Canonicalize context profile name and attributes.
1272
1273private:
1274 SampleProfileMap &ProfileMap;
1275};
1276
1277// CSProfileConverter converts a full context-sensitive flat sample profile into
1278// a nested context-sensitive sample profile.
1280public:
1282 void convertProfiles();
1283 struct FrameNode {
1285 FunctionSamples *FSamples = nullptr,
1286 LineLocation CallLoc = {0, 0})
1287 : FuncName(FName), FuncSamples(FSamples), CallSiteLoc(CallLoc){};
1288
1289 // Map line+discriminator location to child frame
1290 std::map<uint64_t, FrameNode> AllChildFrames;
1291 // Function name for current frame
1293 // Function Samples for current frame
1295 // Callsite location in parent context
1297
1299 StringRef CalleeName);
1300 };
1301
1302private:
1303 // Nest all children profiles into the profile of Node.
1305 FrameNode *getOrCreateContextPath(const SampleContext &Context);
1306
1307 SampleProfileMap &ProfileMap;
1308 FrameNode RootFrame;
1309};
1310
1311/// ProfileSymbolList records the list of function symbols shown up
1312/// in the binary used to generate the profile. It is useful to
1313/// to discriminate a function being so cold as not to shown up
1314/// in the profile and a function newly added.
1316public:
1317 /// copy indicates whether we need to copy the underlying memory
1318 /// for the input Name.
1319 void add(StringRef Name, bool copy = false) {
1320 if (!copy) {
1321 Syms.insert(Name);
1322 return;
1323 }
1324 Syms.insert(Name.copy(Allocator));
1325 }
1326
1327 bool contains(StringRef Name) { return Syms.count(Name); }
1328
1330 for (auto Sym : List.Syms)
1331 add(Sym, true);
1332 }
1333
1334 unsigned size() { return Syms.size(); }
1335
1336 void setToCompress(bool TC) { ToCompress = TC; }
1337 bool toCompress() { return ToCompress; }
1338
1339 std::error_code read(const uint8_t *Data, uint64_t ListSize);
1340 std::error_code write(raw_ostream &OS);
1341 void dump(raw_ostream &OS = dbgs()) const;
1342
1343private:
1344 // Determine whether or not to compress the symbol list when
1345 // writing it into profile. The variable is unused when the symbol
1346 // list is read from an existing profile.
1347 bool ToCompress = false;
1349 BumpPtrAllocator Allocator;
1350};
1351
1352} // end namespace sampleprof
1353
1354using namespace sampleprof;
1355// Provide DenseMapInfo for SampleContext.
1356template <> struct DenseMapInfo<SampleContext> {
1357 static inline SampleContext getEmptyKey() { return SampleContext(); }
1358
1359 static inline SampleContext getTombstoneKey() { return SampleContext("@"); }
1360
1361 static unsigned getHashValue(const SampleContext &Val) {
1362 return Val.getHashCode();
1363 }
1364
1365 static bool isEqual(const SampleContext &LHS, const SampleContext &RHS) {
1366 return LHS == RHS;
1367 }
1368};
1369
1370// Prepend "__uniq" before the hash for tools like profilers to understand
1371// that this symbol is of internal linkage type. The "__uniq" is the
1372// pre-determined prefix that is used to tell tools that this symbol was
1373// created with -funique-internal-linakge-symbols and the tools can strip or
1374// keep the prefix as needed.
1375inline std::string getUniqueInternalLinkagePostfix(const StringRef &FName) {
1376 llvm::MD5 Md5;
1377 Md5.update(FName);
1379 Md5.final(R);
1380 SmallString<32> Str;
1382 // Convert MD5hash to Decimal. Demangler suffixes can either contain
1383 // numbers or characters but not both.
1384 llvm::APInt IntHash(128, Str.str(), 16);
1385 return toString(IntHash, /* Radix = */ 10, /* Signed = */ false)
1386 .insert(0, FunctionSamples::UniqSuffix);
1387}
1388
1389} // end namespace llvm
1390
1391#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
Provides ErrorOr<T> smart pointer.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
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:687
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:558
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:345
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:726
void setTotalSamples(uint64_t Num)
Definition: SampleProf.h:748
void setName(StringRef FunctionName)
Set the name of the function.
Definition: SampleProf.h:1022
bool operator!=(const FunctionSamples &Other) const
Definition: SampleProf.h:1171
sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:733
static uint64_t getGUID(StringRef Name)
Definition: SampleProf.h:1152
static constexpr const char * UniqSuffix
Definition: SampleProf.h:1046
static StringRef getCanonicalFnName(StringRef FnName, StringRef Attr="selected")
Definition: SampleProf.h:1048
ErrorOr< SampleRecord::CallTargetMap > findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const
Returns the call target map collected at a given location.
Definition: SampleProf.h:847
bool operator==(const FunctionSamples &Other) const
Definition: SampleProf.h:1160
static constexpr const char * PartSuffix
Definition: SampleProf.h:1045
const FunctionSamplesMap * findFunctionSamplesMapAt(const LineLocation &Loc) const
Returns the FunctionSamplesMap at the given Loc.
Definition: SampleProf.h:871
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:995
uint64_t getMaxCountInside(bool SkipCallSite=false) const
Return the maximum of sample counts in a function body.
Definition: SampleProf.h:941
void removeTotalSamples(uint64_t Num)
Definition: SampleProf.h:741
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:899
ErrorOr< uint64_t > findSamplesAt(uint32_t LineOffset, uint32_t Discriminator) const
Return the number of samples collected at the given location.
Definition: SampleProf.h:835
ErrorOr< SampleRecord::CallTargetMap > findCallTargetMapAt(const LineLocation &CallSite) const
Returns the call target map collected at a given location specified by CallSite.
Definition: SampleProf.h:857
static constexpr const char * LLVMSuffix
Name suffixes which canonicalization should handle to avoid profile mismatch.
Definition: SampleProf.h:1044
void findAllNames(DenseSet< StringRef > &NameSet) const
Definition: SampleProf.cpp:272
StringRef getFuncName(StringRef Name) const
Translate Name into its original name.
Definition: SampleProf.h:1087
sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:750
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:1147
FunctionSamplesMap & functionSamplesAt(const LineLocation &Loc)
Return the function samples at the given callsite location.
Definition: SampleProf.h:865
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
Definition: SampleProf.h:1036
StringRef getFuncName() const
Return the original function name.
Definition: SampleProf.h:1028
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:758
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:1030
uint64_t removeCalledTargetAndBodySample(uint32_t LineOffset, uint32_t Discriminator, StringRef FName)
Definition: SampleProf.h:774
static bool ProfileIsFS
If this profile uses flow sensitive discriminators.
Definition: SampleProf.h:1143
sampleprof_error addCalledTargetSamples(uint32_t LineOffset, uint32_t Discriminator, StringRef FName, uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:764
SampleContext & getContext() const
Definition: SampleProf.h:1132
static bool HasUniqSuffix
Whether the profile contains any ".__uniq." suffix in a name.
Definition: SampleProf.h:1140
sampleprof_error addBodySamplesForProbe(uint32_t Index, uint64_t Num, uint64_t Weight=1)
Definition: SampleProf.h:788
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
Definition: SampleProf.h:891
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:955
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
Definition: SampleProf.h:933
void setContext(const SampleContext &FContext)
Definition: SampleProf.h:1134
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:906
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:1025
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
Definition: SampleProf.h:930
static bool UseMD5
Whether the profile uses MD5 to represent string.
Definition: SampleProf.h:1137
ProfileSymbolList records the list of function symbols shown up in the binary used to generate the pr...
Definition: SampleProf.h:1315
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:1329
void add(StringRef Name, bool copy=false)
copy indicates whether we need to copy the underlying memory for the input Name.
Definition: SampleProf.h:1319
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:1255
SampleContextTrimmer(SampleProfileMap &Profiles)
Definition: SampleProf.h:1257
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:555
bool operator==(const SampleContext &That) const
Definition: SampleProf.h:647
SampleContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
Definition: SampleProf.h:524
bool operator<(const SampleContext &That) const
Definition: SampleProf.h:654
SampleContext(StringRef ContextStr, std::list< SampleContextFrameVector > &CSNameTable, ContextStateMask CState=RawContext)
Definition: SampleProf.h:534
bool hasState(ContextStateMask S)
Definition: SampleProf.h:600
void clearState(ContextStateMask S)
Definition: SampleProf.h:602
void setName(StringRef FunctionName)
Set the name of the function and clear the current context.
Definition: SampleProf.h:633
SampleContextFrames getContextFrames() const
Definition: SampleProf.h:606
static std::string getContextString(SampleContextFrames Context, bool IncludeLeafLineLocation=false)
Definition: SampleProf.h:608
bool operator!=(const SampleContext &That) const
Definition: SampleProf.h:652
void setState(ContextStateMask S)
Definition: SampleProf.h:601
void setAllAttributes(uint32_t A)
Definition: SampleProf.h:599
uint64_t getHashCode() const
Definition: SampleProf.h:627
void setContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
Definition: SampleProf.h:639
static void decodeContextString(StringRef ContextStr, StringRef &FName, LineLocation &LineLoc)
Definition: SampleProf.h:574
void setAttribute(ContextAttributeMask A)
Definition: SampleProf.h:597
bool IsPrefixOf(const SampleContext &That) const
Definition: SampleProf.h:683
bool hasAttribute(ContextAttributeMask A)
Definition: SampleProf.h:596
std::string toString() const
Definition: SampleProf.h:621
SampleProfileReaderItaniumRemapper remaps the profile data from a sample profile data reader,...
Representation of a single sample record.
Definition: SampleProf.h:325
bool hasCalls() const
Return true if this sample record contains function calls.
Definition: SampleProf.h:390
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:393
std::set< CallTarget, CallTargetComparator > SortedCallTargetSet
Definition: SampleProf.h:337
uint64_t getSamples() const
Definition: SampleProf.h:392
uint64_t getCallTargetSum() const
Definition: SampleProf.h:398
uint64_t removeSamples(uint64_t S)
Decrease the number of samples for this record by S.
Definition: SampleProf.h:355
sampleprof_error addSamples(uint64_t S, uint64_t Weight=1)
Increment the number of samples for this record by S.
Definition: SampleProf.h:346
sampleprof_error addCalledTarget(StringRef F, uint64_t S, uint64_t Weight=1)
Add called function F with samples S.
Definition: SampleProf.h:367
std::pair< StringRef, uint64_t > CallTarget
Definition: SampleProf.h:327
StringMap< uint64_t > CallTargetMap
Definition: SampleProf.h:338
static const SortedCallTargetSet SortCallTargets(const CallTargetMap &Targets)
Sort call targets in descending order of call frequency.
Definition: SampleProf.h:406
const SortedCallTargetSet getSortedCallTargets() const
Definition: SampleProf.h:394
static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets, float DistributionFactor)
Prorate call targets by a distribution factor.
Definition: SampleProf.h:415
bool operator!=(const SampleRecord &Other) const
Definition: SampleProf.h:434
bool operator==(const SampleRecord &Other) const
Definition: SampleProf.h:430
uint64_t removeCalledTarget(StringRef F)
Remove called function from the call target map.
Definition: SampleProf.h:379
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:1233
std::pair< const LocationT, SampleT > SamplesWithLoc
Definition: SampleProf.h:1235
SampleSorter(const std::map< LocationT, SampleT > &Samples)
Definition: SampleProf.h:1238
const SamplesWithLocList & get() const
Definition: SampleProf.h:1246
SmallVector< const SamplesWithLoc *, 20 > SamplesWithLocList
Definition: SampleProf.h:1236
#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
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:224
ArrayRef< SampleContextFrame > SampleContextFrames
Definition: SampleProf.h:499
void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
Definition: SampleProf.cpp:201
std::unordered_map< SampleContext, FunctionSamples, SampleContext::Hash > SampleProfileMap
Definition: SampleProf.h:1222
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
Definition: SampleProf.h:99
std::pair< SampleContext, const FunctionSamples * > NameFunctionSamples
Definition: SampleProf.h:1224
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition: SampleProf.h:251
raw_ostream & operator<<(raw_ostream &OS, const LineLocation &Loc)
Definition: SampleProf.cpp:111
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition: SampleProf.h:267
std::map< LineLocation, FunctionSamplesMap > CallsiteSampleMap
Definition: SampleProf.h:719
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:108
std::map< LineLocation, SampleRecord > BodySampleMap
Definition: SampleProf.h:715
@ 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:259
static hash_code hash_value(const SampleContextFrame &arg)
Definition: SampleProf.h:493
static std::string getSecName(SecType Type)
Definition: SampleProf.h:134
std::map< std::string, FunctionSamples, std::less<> > FunctionSamplesMap
Definition: SampleProf.h:718
static uint64_t SPVersion()
Definition: SampleProf.h:116
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
std::enable_if_t< std::is_unsigned< T >::value, 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:658
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
const std::error_category & sampleprof_category()
Definition: SampleProf.cpp:100
std::string getUniqueInternalLinkagePostfix(const StringRef &FName)
Definition: SampleProf.h:1375
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:1361
static SampleContext getTombstoneKey()
Definition: SampleProf.h:1359
static SampleContext getEmptyKey()
Definition: SampleProf.h:1357
static bool isEqual(const SampleContext &LHS, const SampleContext &RHS)
Definition: SampleProf.h:1365
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:51
std::map< uint64_t, FrameNode > AllChildFrames
Definition: SampleProf.h:1290
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:1284
uint64_t operator()(const LineLocation &Loc) const
Definition: SampleProf.h:307
Represents the relative location of an instruction.
Definition: SampleProf.h:283
void print(raw_ostream &OS) const
Definition: SampleProf.cpp:105
LineLocation(uint32_t L, uint32_t D)
Definition: SampleProf.h:284
bool operator!=(const LineLocation &O) const
Definition: SampleProf.h:298
bool operator<(const LineLocation &O) const
Definition: SampleProf.h:289
bool operator==(const LineLocation &O) const
Definition: SampleProf.h:294
uint64_t operator()(const SampleContextFrameVector &S) const
Definition: SampleProf.h:502
bool operator==(const SampleContextFrame &That) const
Definition: SampleProf.h:473
bool operator!=(const SampleContextFrame &That) const
Definition: SampleProf.h:477
std::string toString(bool OutputLineLocation) const
Definition: SampleProf.h:481
SampleContextFrame(StringRef FuncName, LineLocation Location)
Definition: SampleProf.h:470
uint64_t operator()(const SampleContext &Context) const
Definition: SampleProf.h:678
bool operator()(const CallTarget &LHS, const CallTarget &RHS) const
Definition: SampleProf.h:329