14#ifndef LLVM_PROFILEDATA_SAMPLEPROF_H
15#define LLVM_PROFILEDATA_SAMPLEPROF_H
41#include <system_error>
42#include <unordered_map>
90struct is_error_code_enum<
llvm::sampleprof_error> : std::true_type {};
141LLVM_DEPRECATED(
"Use DefaultVersion or LatestVersion instead",
"DefaultVersion")
165 switch (
static_cast<int>(
Type)) {
167 return "InvalidSection";
169 return "ProfileSummarySection";
171 return "NameTableSection";
173 return "ProfileSymbolListSection";
175 return "FuncOffsetTableSection";
177 return "FunctionMetadata";
179 return "CSNameTableSection";
181 return "CompositeFuncOffsetTableSection";
183 return "LBRProfileSection";
185 return "CompositeProfileSection";
187 return "UnknownSection";
286template <
class SecFlagType>
289 if (std::is_same<SecCommonFlags, SecFlagType>())
293 bool IsFlagLegal =
false;
296 IsFlagLegal = std::is_same<SecNameTableFlags, SecFlagType>();
299 IsFlagLegal = std::is_same<SecProfileSymbolListFlags, SecFlagType>();
302 IsFlagLegal = std::is_same<SecProfSummaryFlags, SecFlagType>();
305 IsFlagLegal = std::is_same<SecFuncMetadataFlags, SecFlagType>();
309 IsFlagLegal = std::is_same<SecFuncOffsetFlags, SecFlagType>();
318template <
class SecFlagType>
321 auto FVal =
static_cast<uint64_t>(Flag);
322 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
323 Entry.Flags |= IsCommon ? FVal : (FVal << 32);
326template <
class SecFlagType>
329 auto FVal =
static_cast<uint64_t>(Flag);
330 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
331 Entry.Flags &= ~(IsCommon ? FVal : (FVal << 32));
334template <
class SecFlagType>
337 auto FVal =
static_cast<uint64_t>(Flag);
338 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
339 return Entry.Flags & (IsCommon ? FVal : (FVal << 32));
362 std::tie(O.LineOffset, O.Discriminator);
396namespace sampleprof {
427 if (
LHS.second !=
RHS.second)
428 return LHS.second >
RHS.second;
430 return LHS.first <
RHS.first;
466 uint64_t &TargetSamples = CallTargets[
F];
478 auto I = CallTargets.find(
F);
479 if (
I != CallTargets.end()) {
481 CallTargets.erase(
I);
487 bool hasCalls()
const {
return !CallTargets.empty(); }
502 for (
const auto &
I : CallTargets)
511 return SortedTargets;
516 float DistributionFactor) {
518 for (
const auto &[
Target, Frequency] : Targets) {
519 AdjustedTargets[
Target] = Frequency * DistributionFactor;
521 return AdjustedTargets;
537 return NumSamples ==
Other.NumSamples && CallTargets ==
Other.CallTargets;
582 return !(*
this == That);
585 std::string
toString(
bool OutputLineLocation)
const {
586 std::ostringstream OContextStr;
587 OContextStr <<
Func.str();
588 if (OutputLineLocation) {
589 OContextStr <<
":" <<
Location.LineOffset;
591 OContextStr <<
"." <<
Location.Discriminator;
593 return OContextStr.str();
600 if (
Func.isStringRef())
601 NameHash = std::hash<std::string>{}(
Func.str());
603 NameHash =
Func.getHashCode();
605 return NameHash + (LocId << 5) + LocId;
638 assert(!Name.empty() &&
"Name is empty");
647 assert(!Context.empty() &&
"Context is empty");
655 std::list<SampleContextFrameVector> &CSNameTable,
666 CSNameTable.emplace_back();
678 ContextStr = ContextStr.
substr(1, ContextStr.
size() - 2);
682 while (!ContextRemain.
empty()) {
683 auto ContextSplit = ContextRemain.
split(
" @ ");
684 ChildContext = ContextSplit.first;
685 ContextRemain = ContextSplit.second;
688 Context.emplace_back(Callee, CallSiteLoc);
697 auto EntrySplit = ContextStr.
split(
':');
701 if (!EntrySplit.second.empty()) {
705 auto LocSplit = EntrySplit.second.split(
'.');
706 LocSplit.first.getAsInteger(10, LineOffset);
710 if (!LocSplit.second.empty())
729 bool IncludeLeafLineLocation =
false) {
730 std::ostringstream OContextStr;
732 if (OContextStr.str().size()) {
733 OContextStr <<
" @ ";
735 OContextStr << Context[
I].toString(
I != Context.size() - 1 ||
736 IncludeLeafLineLocation);
738 return OContextStr.str();
755 Func = NewFunctionID;
763 FullContext = Context;
764 Func = Context.back().Func;
769 return State == That.State && Func == That.Func &&
770 FullContext == That.FullContext;
776 if (State != That.State)
777 return State < That.State;
780 return Func < That.Func;
784 while (
I < std::min(FullContext.size(), That.FullContext.
size())) {
785 auto &Context1 = FullContext[
I];
786 auto &Context2 = That.FullContext[
I];
787 auto V = Context1.Func.compare(Context2.Func);
790 if (Context1.Location != Context2.Location)
791 return Context1.Location < Context2.Location;
795 return FullContext.size() < That.FullContext.
size();
800 return Context.getHashCode();
805 auto ThisContext = FullContext;
806 auto ThatContext = That.FullContext;
807 if (ThatContext.size() < ThisContext.size())
809 ThatContext = ThatContext.
take_front(ThisContext.size());
811 if (ThisContext.back().Func != ThatContext.back().Func)
830 return Context.getHashCode();
834 return OS << Context.toString();
869 if (TotalSamples < Num)
889 return BodySamples[
LineLocation(LineOffset, Discriminator)].addSamples(
897 return BodySamples[
LineLocation(LineOffset, Discriminator)].addCalledTarget(
904 return BodySamples[Location].merge(
SampleRecord, Weight);
908 BodySamples.reserve(NumEntries);
912 VirtualCallsiteTypeCounts.reserve(NumEntries);
921 auto I = BodySamples.find(
LineLocation(LineOffset, Discriminator));
922 if (
I != BodySamples.end()) {
923 Count =
I->second.removeCalledTarget(Func);
925 if (!
I->second.getSamples())
926 BodySamples.erase(
I);
937 for (
auto &
I : BodySamples) {
938 uint64_t TargetSamples =
I.second.getCallTargetSum();
943 if (TargetSamples >
I.second.getSamples())
944 I.second.addSamples(TargetSamples -
I.second.getSamples());
951 for (
const auto &
I : BodySamples)
954 for (
auto &
I : CallsiteSamples) {
955 for (
auto &CS :
I.second) {
956 CS.second.updateTotalSamples();
965 for (
auto &
I : CallsiteSamples) {
966 for (
auto &CS :
I.second) {
967 CS.second.setContextSynthetic();
975 Context.setAttribute(Attr);
976 for (
auto &
I : CallsiteSamples) {
977 for (
auto &CS :
I.second) {
978 CS.second.setContextAttribute(Attr);
987 if (!IRToProfileLocationMap)
989 const auto &ProfileLoc = IRToProfileLocationMap->find(IRLoc);
990 if (ProfileLoc != IRToProfileLocationMap->end())
991 return ProfileLoc->second;
1000 const auto &Ret = BodySamples.find(
1002 if (Ret == BodySamples.end())
1003 return std::error_code();
1004 return Ret->second.getSamples();
1015 const auto &Ret = BodySamples.find(
1017 if (Ret == BodySamples.end())
1018 return std::error_code();
1019 return Ret->second.getCallTargets();
1029 if (Ret == BodySamples.end())
1030 return std::error_code();
1031 return Ret->second.getCallTargets();
1044 if (Iter == CallsiteSamples.end())
1046 return &Iter->second;
1055 if (Iter == VirtualCallsiteTypeCounts.end())
1057 return &Iter->second;
1072 bool empty()
const {
return TotalSamples == 0; }
1099 if (!BodySamples.empty() &&
1100 (CallsiteSamples.empty() ||
1101 BodySamples.begin()->first < CallsiteSamples.begin()->first))
1102 Count = BodySamples.begin()->second.getSamples();
1103 else if (!CallsiteSamples.empty()) {
1106 for (
const auto &FuncSamples : CallsiteSamples.begin()->second)
1107 Count += FuncSamples.second.getHeadSamplesEstimate();
1122 return CallsiteSamples;
1133 return VirtualCallsiteTypeCounts;
1153 bool Overflowed =
false;
1155 TypeCounts[
Type], &Overflowed);
1164 template <
typename T>
1168 static_assert((std::is_same_v<typename T::key_type, StringRef> ||
1169 std::is_same_v<typename T::key_type, FunctionId>) &&
1170 std::is_same_v<typename T::mapped_type, uint64_t>,
1171 "T must be a map with StringRef or FunctionId as key and "
1172 "uint64_t as value");
1175 bool Overflowed =
false;
1179 bool RowOverflow =
false;
1181 Count, Weight, TypeCounts[TypeId], &RowOverflow);
1182 Overflowed |= RowOverflow;
1195 MaxCount = std::max(MaxCount, L.second.getSamples());
1199 for (
const FunctionSamplesMap::value_type &
F :
C.second)
1200 MaxCount = std::max(MaxCount,
F.second.getMaxCountInside());
1210 if (Context.getFunction().empty())
1211 Context =
Other.getContext();
1212 if (FunctionHash == 0) {
1214 FunctionHash =
Other.getFunctionHash();
1215 }
else if (FunctionHash !=
Other.getFunctionHash()) {
1230 BodySamples.reserve(BodySamples.size() +
Other.getBodySamples().size());
1231 for (
const auto &
I :
Other.getBodySamples()) {
1236 for (
const auto &
I :
Other.getCallsiteSamples()) {
1239 for (
const auto &Rec :
I.second)
1241 FSMap[Rec.first].merge(Rec.second, Weight));
1243 VirtualCallsiteTypeCounts.reserve(VirtualCallsiteTypeCounts.size() +
1244 Other.getCallsiteTypeCounts().size());
1245 for (
const auto &[
Loc, OtherTypeMap] :
Other.getCallsiteTypeCounts())
1260 if (TotalSamples <= Threshold)
1262 auto IsDeclaration = [](
const Function *
F) {
1263 return !
F ||
F->isDeclaration();
1271 for (
const auto &BS : BodySamples)
1272 for (
const auto &TS : BS.second.getCallTargets())
1273 if (TS.second > Threshold) {
1275 if (IsDeclaration(Callee))
1276 S.
insert(TS.first.getHashCode());
1278 for (
const auto &CS : CallsiteSamples)
1279 for (
const auto &NameFS : CS.second)
1280 NameFS.second.findInlinedFunctions(S, SymbolMap, Threshold);
1285 Context.setFunction(NewFunctionID);
1299 assert(IRToProfileLocationMap ==
nullptr &&
"this should be set only once");
1300 IRToProfileLocationMap = LTLM;
1306 const char *AttrName =
"sample-profile-suffix-elision-policy";
1307 auto Attr =
F.getFnAttribute(AttrName).getValueAsString();
1345 if (Attr ==
"" || Attr ==
"all")
1346 return FnName.
split(
'.').first;
1347 if (Attr ==
"selected") {
1349 for (
const auto Suffix : Suffixes) {
1354 if (!Suffix.ends_with(
".")) {
1358 auto It = Cand.
rfind(Suffix);
1361 auto Dit = Cand.
rfind(
'.');
1362 if (Dit == It + Suffix.size() - 1)
1363 Cand = Cand.
substr(0, It);
1369 assert(
false &&
"internal error: unknown suffix elision policy");
1382 return Func.stringRef();
1385 "GUIDToFuncNameMap needs to be populated first");
1464 FunctionHash ==
Other.FunctionHash && Context ==
Other.Context &&
1465 TotalSamples ==
Other.TotalSamples &&
1466 TotalHeadSamples ==
Other.TotalHeadSamples &&
1467 BodySamples ==
Other.BodySamples &&
1468 CallsiteSamples ==
Other.CallsiteSamples;
1472 return !(*
this ==
Other);
1552 const LocToLocMap *IRToProfileLocationMap =
nullptr;
1571 :
public HashKeyMap<std::unordered_map, SampleContext, FunctionSamples> {
1578 Ret.first->second.setContext(Ctx);
1579 return Ret.first->second;
1606 std::vector<NameFunctionSamples> &SortedProfiles);
1622 bool TrimColdContext,
1623 bool MergeColdContext,
1625 bool TrimBaseProfileOnly);
1661 bool ProfileIsCS =
false) {
1664 ProfileMap = std::move(TmpProfiles);
1669 bool ProfileIsCS =
false) {
1671 for (
const auto &
I : InputProfiles) {
1678 for (
const auto &
I : InputProfiles)
1679 flattenNestedProfile(OutputProfiles,
I.second);
1689 auto Ret = OutputProfiles.
try_emplace(Context, FS);
1694 Profile.removeAllCallsiteSamples();
1698 Profile.reserveBodySamples(FS.getBodySamples().size());
1705 "There should be no inlinees' profiles after flattening.");
1711 uint64_t TotalSamples =
FS.getTotalSamples();
1713 for (
const auto &
I :
FS.getCallsiteSamples()) {
1714 for (
const auto &Callee :
I.second) {
1715 const auto &CalleeProfile =
Callee.second;
1717 Profile.addBodySamples(
I.first.LineOffset,
I.first.Discriminator,
1718 CalleeProfile.getHeadSamplesEstimate());
1720 Profile.addCalledTargetSamples(
I.first.LineOffset,
1721 I.first.Discriminator,
1722 CalleeProfile.getFunction(),
1723 CalleeProfile.getHeadSamplesEstimate());
1725 TotalSamples = TotalSamples >= CalleeProfile.getTotalSamples()
1726 ? TotalSamples - CalleeProfile.getTotalSamples()
1728 TotalSamples += CalleeProfile.getHeadSamplesEstimate();
1730 flattenNestedProfile(OutputProfiles, CalleeProfile);
1733 Profile.addTotalSamples(TotalSamples);
1742 SampleProfileMap &ProfileMap;
1759 Syms.insert(Name.copy(Allocator));
1769 "Merging pre-hashed MD5 ProfileSymbolList not yet implemented");
1770 for (
auto Sym :
List.Syms)
1774 unsigned size()
const {
return IsMD5 ? ColdGUIDTable.size() : Syms.size(); }
1779 "Collecting GUIDs from existing MD5 table not yet implemented");
1780 std::vector<uint64_t> Keys;
1781 Keys.reserve(Syms.size());
1790 "Setting ColdGUIDTable shadows existing strings in Syms");
1791 ColdGUIDTable =
Table;
1795 assert(IsMD5 &&
"Retrieving ColdGUIDTable from non-MD5 ProfileSymbolList");
1796 return ColdGUIDTable;
1813using namespace sampleprof;
1840 return toString(IntHash, 10,
false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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")
#define LLVM_DEPRECATED(MSG, FIX)
#define LLVM_LIFETIME_BOUND
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Provides ErrorOr<T> smart pointer.
This file defines the EytzingerTableSpan class, a non-owning view of a buffer formatted as a complete...
Defines FunctionId class.
Defines HashKeyMap template.
static cl::opt< unsigned > ColdCountThreshold("mfs-count-threshold", cl::desc("Minimum number of times a block must be executed to be retained."), cl::init(1), cl::Hidden)
This file implements a map that provides insertion order iteration.
This file defines the SmallVector class.
This file implements a map backed by a sorted SmallVector.
Class for arbitrary precision integers.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
size_t size() const
Get the array size.
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Implements a dense probed hash-table based set.
Represents either an error or a value T.
Non-owning view of a buffer formatted as a complete binary search tree in Eytzinger (breadth-first) o...
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
static LLVM_ABI void stringifyResult(MD5Result &Result, SmallVectorImpl< char > &Str)
Translates the bytes in Res to a hex string that is deposited into Str.
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
This class implements a map that also provides access to all stored values in a deterministic order.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A map implementation backed by a sorted SmallVector.
void reserve(size_type Cap)
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
static constexpr size_t npos
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
Target - Wrapper for Target specific information.
The instances of the Type class are immutable: once they are created, they are never changed.
std::pair< iterator, bool > insert(const ValueT &V)
An opaque object representing a hash code.
This class implements an extremely fast bulk output stream that can only output to a stream.
This class represents a function that is read from a sample profile.
uint64_t getHashCode() const
Get hash code of this object.
Representation of the samples collected for a function.
void setTotalSamples(uint64_t Num)
static LLVM_ABI std::atomic< bool > ProfileIsFS
If this profile uses flow sensitive discriminators.
static LLVM_ABI std::atomic< bool > ProfileIsPreInlined
void setContextAttribute(ContextAttributeMask Attr)
const FunctionSamplesMap * findFunctionSamplesMapAt(const LineLocation &Loc) const LLVM_LIFETIME_BOUND
Returns the FunctionSamplesMap at the given Loc.
bool operator!=(const FunctionSamples &Other) const
void updateTotalSamples()
void setHeadSamples(uint64_t Num)
sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight=1)
static constexpr const char * UniqSuffix
void updateCallsiteSamples()
static LLVM_ABI std::atomic< bool > UseMD5
Whether the profile uses MD5 to represent string.
bool hasCallsiteSamples() const
Return whether this function profile contains callsite samples.
static StringRef getCanonicalFnName(StringRef FnName, StringRef Attr="selected")
sampleprof_error addTypeSamplesAt(const LineLocation &Loc, FunctionId Type, uint64_t Count)
At location Loc, add a type sample for the given Type with Count.
bool operator==(const FunctionSamples &Other) const
static constexpr const char * PartSuffix
static uint64_t getCallSiteHash(FunctionId Callee, const LineLocation &Callsite)
Returns a unique hash code for a combination of a callsite location and the callee function name.
static StringRef getCanonicalCoroFnName(StringRef FnName, StringRef Attr="selected")
void removeAllCallsiteSamples()
uint64_t getMaxCountInside(bool SkipCallSite=false) const
Return the maximum of sample counts in a function body.
void removeTotalSamples(uint64_t Num)
uint64_t getHeadSamples() const
For top-level functions, return the total number of branch samples that have the function as the bran...
void setFunction(FunctionId NewFunctionID)
Set the name of the function.
ErrorOr< uint64_t > findSamplesAt(uint32_t LineOffset, uint32_t Discriminator) const
Return the number of samples collected at the given location.
LLVM_ABI const FunctionSamples * findFunctionSamples(const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper=nullptr, const HashKeyMap< DenseMap, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const LLVM_LIFETIME_BOUND
Get the FunctionSamples of the inline instance where DIL originates from.
const CallsiteSampleMap & getCallsiteSamples() const LLVM_LIFETIME_BOUND
Return all the callsite samples collected in the body of the function.
const LineLocation & mapIRLocToProfileLoc(const LineLocation &IRLoc) const
LLVM_ABI const FunctionSamples * findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName, SampleProfileReaderItaniumRemapper *Remapper, const HashKeyMap< DenseMap, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const LLVM_LIFETIME_BOUND
Returns a pointer to FunctionSamples at the given callsite location Loc with callee CalleeName.
static StringRef getCanonicalFnName(StringRef FnName, ArrayRef< StringRef > Suffixes, StringRef Attr="selected")
FunctionId getFunction() const
Return the function name.
uint64_t getFunctionHash() const
SampleContext & getContext() const LLVM_LIFETIME_BOUND
sampleprof_error addCallsiteVTableTypeProfAt(const LineLocation &Loc, const T &Other, uint64_t Weight=1)
Scale Other sample counts by Weight and add the scaled result to the type samples for Loc.
static constexpr const char * LLVMSuffix
Name suffixes which canonicalization should handle to avoid profile mismatch.
FunctionSamplesMap & functionSamplesAt(const LineLocation &Loc) LLVM_LIFETIME_BOUND
Return the function samples at the given callsite location.
StringRef getFuncName(FunctionId Func) const
Translate Func into its original name.
ErrorOr< const SampleRecord::CallTargetMap & > findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const LLVM_LIFETIME_BOUND
Returns the call target map collected at a given location.
sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight=1)
void reserveBodySamples(size_t NumEntries)
sampleprof_error addSampleRecord(LineLocation Location, const SampleRecord &SampleRecord, uint64_t Weight=1)
uint64_t removeCalledTargetAndBodySample(uint32_t LineOffset, uint32_t Discriminator, FunctionId Func)
DenseMap< uint64_t, StringRef > * GUIDToFuncNameMap
GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for all the function symbols define...
TypeCountMap & getTypeSamplesAt(const LineLocation &Loc) LLVM_LIFETIME_BOUND
Returns the vtable access samples for the C++ types for Loc.
sampleprof_error addCalledTargetSamples(uint32_t LineOffset, uint32_t Discriminator, FunctionId Func, uint64_t Num, uint64_t Weight=1)
void setIRToProfileLocationMap(const LocToLocMap *LTLM)
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
StringRef getFuncName() const
Return the original function name.
LLVM_ABI void findAllNames(DenseSet< FunctionId > &NameSet) const
static constexpr const char * CfiSuffix
sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator, uint64_t Num, uint64_t Weight=1)
static LLVM_ABI unsigned getOffset(const DILocation *DIL)
Returns the line offset to the start line of the subprogram.
static LLVM_ABI std::atomic< bool > HasUniqSuffix
Whether the profile contains any ".__uniq." suffix in a name.
void setContextSynthetic()
void setFunctionHash(uint64_t Hash)
const TypeCountMap * findCallsiteTypeSamplesAt(const LineLocation &Loc) const LLVM_LIFETIME_BOUND
Returns the TypeCountMap for inlined callsites at the given Loc.
static LLVM_ABI std::atomic< bool > ProfileIsProbeBased
const CallsiteTypeMap & getCallsiteTypeCounts() const LLVM_LIFETIME_BOUND
Returns vtable access samples for the C++ types collected in this function.
ErrorOr< const SampleRecord::CallTargetMap & > findCallTargetMapAt(const LineLocation &CallSite) const LLVM_LIFETIME_BOUND
Returns the call target map collected at a given location specified by CallSite.
const BodySampleMap & getBodySamples() const LLVM_LIFETIME_BOUND
Return all the samples collected in the body of the function.
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
LLVM_ABI void print(raw_ostream &OS=dbgs(), unsigned Indent=0) const
Print the samples collected for a function on stream OS.
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
FunctionSamples()=default
LLVM_ABI void dump() const
void setContext(const SampleContext &FContext)
static LLVM_ABI std::atomic< bool > ProfileIsCS
static LLVM_ABI LineLocation getCallSiteIdentifier(const DILocation *DIL, bool ProfileIsFS=false)
Returns a unique call site identifier for a given debug location of a call instruction.
void reserveCallsiteTypeCounts(size_t NumEntries)
void findInlinedFunctions(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, uint64_t Threshold) const
Recursively traverses all children, if the total sample count of the corresponding function is no les...
uint64_t getHeadSamplesEstimate() const
Return an estimate of the sample count of the function entry basic block.
uint64_t getGUID() const
Return the GUID of the context's name.
This class is a wrapper to associative container MapT<KeyT, ValueT> using the hash value of the origi...
FunctionSamples mapped_type
std::pair< iterator, bool > try_emplace(const key_type &Hash, const original_key_type &Key, Ts &&...Args)
typename base_type::iterator iterator
decltype(hash_value(SampleContext())) key_type
iterator find(const original_key_type &Key)
typename base_type::const_iterator const_iterator
LLVM_ABI ProfileConverter(SampleProfileMap &Profiles)
LLVM_ABI void convertCSProfiles()
static void flattenProfile(SampleProfileMap &ProfileMap, bool ProfileIsCS=false)
static void flattenProfile(const SampleProfileMap &InputProfiles, SampleProfileMap &OutputProfiles, bool ProfileIsCS=false)
ProfileSymbolList records the list of function symbols shown up in the binary used to generate the pr...
void add(StringRef Name, bool Copy=false)
copy indicates whether we need to copy the underlying memory for the input Name.
LLVM_ABI std::error_code write(raw_ostream &OS)
bool contains(StringRef Name) const
void reserve(size_t Size)
LLVM_ABI void dump(raw_ostream &OS=dbgs()) const
void setColdGUIDTable(EytzingerTableSpan< support::ulittle64_t > Table)
std::vector< uint64_t > collectGUIDs() const
void merge(const ProfileSymbolList &List)
EytzingerTableSpan< support::ulittle64_t > getColdGUIDTable() const
LLVM_ABI std::error_code read(const uint8_t *Data, uint64_t ListSize)
SampleContextTrimmer(SampleProfileMap &Profiles)
LLVM_ABI void trimAndMergeColdContextProfiles(uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext, uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly)
static void createCtxVectorFromStr(StringRef ContextStr, SampleContextFrameVector &Context)
Create a context vector from a given context string and save it in Context.
bool operator==(const SampleContext &That) const
void setFunction(FunctionId NewFunctionID)
Set the name of the function and clear the current context.
SampleContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
bool operator<(const SampleContext &That) const
SampleContext(StringRef ContextStr, std::list< SampleContextFrameVector > &CSNameTable, ContextStateMask CState=RawContext)
bool hasState(ContextStateMask S)
void clearState(ContextStateMask S)
SampleContextFrames getContextFrames() const
SampleContext(FunctionId Func)
bool isBaseContext() const
static void decodeContextString(StringRef ContextStr, FunctionId &Func, LineLocation &LineLoc)
static std::string getContextString(SampleContextFrames Context, bool IncludeLeafLineLocation=false)
bool operator!=(const SampleContext &That) const
void setState(ContextStateMask S)
void setAllAttributes(uint32_t A)
uint64_t getHashCode() const
void setContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
FunctionId getFunction() const
uint32_t getAllAttributes()
void setAttribute(ContextAttributeMask A)
bool hasAttribute(ContextAttributeMask A)
std::string toString() const
SampleContext(StringRef Name)
bool isPrefixOf(const SampleContext &That) const
This class provides operator overloads to the map container using MD5 as the key type,...
iterator find(const SampleContext &Ctx)
mapped_type & create(const SampleContext &Ctx)
iterator erase(iterator It)
size_t erase(const key_type &Key)
const_iterator find(const SampleContext &Ctx) const
size_t erase(const SampleContext &Ctx)
SampleProfileReaderItaniumRemapper remaps the profile data from a sample profile data reader,...
Representation of a single sample record.
static SortedCallTargetSet sortCallTargets(const CallTargetMap &Targets)
Sort call targets in descending order of call frequency.
LLVM_ABI std::error_code serialize(raw_ostream &OS, const MapVector< FunctionId, uint32_t > &NameTable) const
Serialize the sample record to the output stream using ULEB128 encoding.
LLVM_ABI void dump() const
bool hasCalls() const
Return true if this sample record contains function calls.
LLVM_ABI sampleprof_error merge(const SampleRecord &Other, uint64_t Weight=1)
Merge the samples in Other into this record.
SortedCallTargetSet getSortedCallTargets() const
uint64_t getSamples() const
uint64_t getCallTargetSum() const
uint64_t removeSamples(uint64_t S)
Decrease the number of samples for this record by S.
sampleprof_error addSamples(uint64_t S, uint64_t Weight=1)
Increment the number of samples for this record by S.
uint64_t removeCalledTarget(FunctionId F)
Remove called function from the call target map.
const CallTargetMap & getCallTargets() const LLVM_LIFETIME_BOUND
Return the call targets collected in this sample record.
static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets, float DistributionFactor)
Prorate call targets by a distribution factor.
SortedVectorMap< FunctionId, uint64_t, 0 > CallTargetMap
std::pair< FunctionId, uint64_t > CallTarget
bool operator!=(const SampleRecord &Other) const
SmallVector< CallTarget > SortedCallTargetSet
bool operator==(const SampleRecord &Other) const
LLVM_ABI void print(raw_ostream &OS, unsigned Indent) const
Print the sample record to the stream OS indented by Indent.
sampleprof_error addCalledTarget(FunctionId F, uint64_t S, uint64_t Weight=1)
Add called function F with samples S.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static FunctionId getRepInFormat(StringRef Name)
Get the proper representation of a string according to whether the current Format uses MD5 to represe...
static void verifySecFlag(SecType Type, SecFlagType Flag)
LLVM_ABI void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
SecProfileSymbolListFlags
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
static bool formatVersionIsSupported(uint64_t Version)
SortedVectorMap< LineLocation, TypeCountMap, 0 > CallsiteTypeMap
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
std::map< LineLocation, FunctionSamplesMap > CallsiteSampleMap
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
static constexpr uint64_t LatestVersion
SortedVectorMap< LineLocation, SampleRecord, 0 > BodySampleMap
ArrayRef< SampleContextFrame > SampleContextFrames
std::pair< hash_code, const FunctionSamples * > NameFunctionSamples
uint64_t MD5Hash(const FunctionId &Obj)
@ ContextDuplicatedIntoBase
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
@ SecFlagHasVTableTypeProf
SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
@ 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)
static StringRef getProfTypeName(uint64_t Type)
DenseMap< LineLocation, LineLocation > LocToLocMap
SmallVector< SampleContextFrame, 1 > SampleContextFrameVector
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
static constexpr uint64_t MinSupportedVersion
raw_ostream & operator<<(raw_ostream &OS, const FunctionId &Obj)
static constexpr uint64_t DefaultVersion
static std::string getSecName(SecType Type)
static constexpr uint64_t CompositeProfileVersion
constexpr char kVTableProfPrefix[]
uint64_t hash_value(const FunctionId &Obj)
LLVM_ABI std::error_code serializeTypeMap(const TypeCountMap &Map, const MapVector< FunctionId, uint32_t > &NameTable, raw_ostream &OS)
Write Map to the output stream.
static uint64_t SPVersion()
SortedVectorMap< FunctionId, uint64_t, 0 > TypeCountMap
Key represents type of a C++ polymorphic class type by its vtable and value represents its counter.
@ SecCompositeFuncOffsetTable
This is an optimization pass for GlobalISel generic memory operations.
std::error_code make_error_code(BitcodeError E)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
auto unique(Range &&R, Predicate P)
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
sampleprof_error mergeSampleProfErrors(sampleprof_error &Accumulator, sampleprof_error Result)
@ unsupported_writing_format
@ ostream_seek_unsupported
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI const std::error_category & sampleprof_category()
std::string getUniqueInternalLinkagePostfix(const StringRef &FName)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
LogicalResult success(bool IsSuccess=true)
Utility function to generate a LogicalResult.
SmallVector< Out, Size > to_vector_of(R &&Range)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Implement std::hash so that hash_code can be used in STL containers.
static unsigned getHashValue(const SampleContext &Val)
static bool isEqual(const SampleContext &LHS, const SampleContext &RHS)
static unsigned getHashValue(const sampleprof::LineLocation &Val)
static bool isEqual(const sampleprof::LineLocation &LHS, const sampleprof::LineLocation &RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
Represents the relative location of an instruction.
LLVM_ABI void serialize(raw_ostream &OS) const
LLVM_ABI void print(raw_ostream &OS) const
LineLocation(uint32_t L, uint32_t D)
bool operator!=(const LineLocation &O) const
bool operator<(const LineLocation &O) const
uint64_t getHashCode() const
bool operator==(const LineLocation &O) const
LLVM_ABI void dump() const
FunctionSamples * FuncSamples
FrameNode(FunctionId FName=FunctionId(), FunctionSamples *FSamples=nullptr, LineLocation CallLoc={0, 0})
LLVM_ABI FrameNode * getOrCreateChildFrame(const LineLocation &CallSite, FunctionId CalleeName)
std::map< uint64_t, FrameNode > AllChildFrames
uint64_t operator()(const SampleContextFrameVector &S) const
bool operator==(const SampleContextFrame &That) const
SampleContextFrame(FunctionId Func, LineLocation Location)
bool operator!=(const SampleContextFrame &That) const
std::string toString(bool OutputLineLocation) const
uint64_t getHashCode() const
uint64_t operator()(const SampleContext &Context) const
bool operator()(const CallTarget &LHS, const CallTarget &RHS) const