15#include "llvm/Config/llvm-config.h"
26#include <system_error>
29using namespace sampleprof;
33 cl::desc(
"Cutoff value about how many symbols in profile symbol list "
34 "will be used. This is very useful for performance debugging"));
37 "generate-merged-base-profiles",
38 cl::desc(
"When generating nested context-sensitive profiles, always "
39 "generate extra base profile for function with all its context "
40 "profiles merged into it."));
58class SampleProfErrorCategoryType :
public std::error_category {
59 const char *
name()
const noexcept
override {
return "llvm.sampleprof"; }
61 std::string message(
int IE)
const override {
64 case sampleprof_error::success:
66 case sampleprof_error::bad_magic:
67 return "Invalid sample profile data (bad magic)";
68 case sampleprof_error::unsupported_version:
69 return "Unsupported sample profile format version";
70 case sampleprof_error::too_large:
71 return "Too much profile data";
72 case sampleprof_error::truncated:
73 return "Truncated profile data";
74 case sampleprof_error::malformed:
75 return "Malformed sample profile data";
76 case sampleprof_error::unrecognized_format:
77 return "Unrecognized sample profile encoding format";
78 case sampleprof_error::unsupported_writing_format:
79 return "Profile encoding format unsupported for writing operations";
80 case sampleprof_error::truncated_name_table:
81 return "Truncated function name table";
82 case sampleprof_error::not_implemented:
83 return "Unimplemented feature";
84 case sampleprof_error::counter_overflow:
85 return "Counter overflow";
86 case sampleprof_error::ostream_seek_unsupported:
87 return "Ostream does not support seek";
88 case sampleprof_error::uncompress_failed:
89 return "Uncompress failure";
90 case sampleprof_error::zlib_unavailable:
91 return "Zlib is unavailable";
92 case sampleprof_error::hash_mismatch:
93 return "Function hash mismatch";
94 case sampleprof_error::illegal_line_offset:
95 return "Illegal line offset in sample profile data";
104 static SampleProfErrorCategoryType ErrorCategory;
105 return ErrorCategory;
126 for (
const auto &
I :
Other.getCallTargets()) {
139 if (
auto NameIndexIter = NameTable.
find(Callee);
140 NameIndexIter != NameTable.
end()) {
151#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
166 OS <<
" " <<
I.first <<
":" <<
I.second;
171#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
186 OS << TotalSamples <<
", " << TotalHeadSamples <<
", " << BodySamples.size()
187 <<
" sampled lines\n";
190 if (!BodySamples.empty()) {
191 OS <<
"Samples collected in the function's body {\n";
193 for (
const auto &SI : SortedBodySamples.
get()) {
195 OS << SI->first <<
": " << SI->second;
200 OS <<
"No samples collected in the function's body\n";
204 if (!CallsiteSamples.empty()) {
205 OS <<
"Samples collected in inlined callsites {\n";
208 for (
const auto *Element : SortedCallsiteSamples.
get()) {
210 const auto &[Loc, FunctionSampleMap] = *Element;
214 OS << Loc <<
": inlined callee: " << FuncSample.getFunction() <<
": ";
215 FuncSample.print(
OS, Indent + 4);
221 OS <<
"No inlined callsites in this function\n";
233 std::vector<NameFunctionSamples> &SortedProfiles) {
234 for (
const auto &
I : ProfileMap) {
235 SortedProfiles.push_back(std::make_pair(
I.first, &
I.second));
239 if (
A.second->getTotalSamples() ==
B.second->getTotalSamples())
240 return A.second->getContext() <
B.second->getContext();
241 return A.second->getTotalSamples() >
B.second->getTotalSamples();
246 return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
258 DIL->getDiscriminator()),
261 unsigned Discriminator =
270 *FuncNameToProfNameMap)
const {
275 for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
277 StringRef Name = PrevDIL->getScope()->getSubprogram()->getLinkageName();
279 Name = PrevDIL->getScope()->getSubprogram()->getName();
289 for (
int i = S.
size() - 1; i >= 0 && FS !=
nullptr; i--) {
290 FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper,
291 FuncNameToProfNameMap);
298 for (
const auto &BS : BodySamples)
301 for (
const auto &CS : CallsiteSamples) {
302 for (
const auto &NameFS : CS.second) {
303 NameSet.
insert(NameFS.first);
304 NameFS.second.findAllNames(NameSet);
313 *FuncNameToProfNameMap)
const {
317 if (
I == CallsiteSamples.end())
320 if (FS !=
I->second.end())
323 if (FuncNameToProfNameMap && !FuncNameToProfNameMap->empty()) {
325 if (R != FuncNameToProfNameMap->end()) {
326 CalleeName = R->second.stringRef();
328 if (FS !=
I->second.end())
336 if (FS !=
I->second.end())
343 if (!CalleeName.
empty())
347 for (
const auto &NameFS :
I->second)
348 if (NameFS.second.getTotalSamples() >= MaxTotalSamples) {
349 MaxTotalSamples = NameFS.second.getTotalSamples();
355#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
361 const char *ListStart =
reinterpret_cast<const char *
>(
Data);
367 Size += Str.size() + 1;
377 uint32_t ColdContextFrameLength,
bool TrimBaseProfileOnly) {
378 if (!TrimColdContext && !MergeColdContext)
388 if (MergeColdContext)
389 TrimBaseProfileOnly =
false;
393 std::vector<std::pair<hash_code, const FunctionSamples *>> ColdProfiles;
394 for (
const auto &
I : ProfileMap) {
398 (!TrimBaseProfileOnly ||
Context.isBaseContext()))
399 ColdProfiles.emplace_back(
I.first, &
I.second);
405 for (
const auto &
I : ColdProfiles) {
406 if (MergeColdContext) {
412 MergedProfile.
merge(*
I.second);
414 ProfileMap.erase(
I.first);
418 for (
const auto &
I : MergedProfileMap) {
421 ProfileMap.find(
I.second.getContext()) == ProfileMap.end())
428 OrigProfile.
merge(
I.second);
435 std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
438 std::string OutputString;
439 for (
auto &
Sym : SortedList) {
440 OutputString.append(
Sym.str());
441 OutputString.append(1,
'\0');
449 OS <<
"======== Dump profile symbol list ========\n";
450 std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
453 for (
auto &
Sym : SortedList)
463 assert(It->second.FuncName == CalleeName &&
464 "Hash collision for child context node");
473 : ProfileMap(Profiles) {
474 for (
auto &FuncSample : Profiles) {
476 auto *NewNode = getOrCreateContextPath(FSamples->
getContext());
477 assert(!NewNode->FuncSamples &&
"New node cannot have sample profile");
478 NewNode->FuncSamples = FSamples;
483ProfileConverter::getOrCreateContextPath(
const SampleContext &Context) {
484 auto Node = &RootFrame;
486 for (
auto &Callsite :
Context.getContextFrames()) {
487 Node = Node->getOrCreateChildFrame(CallSiteLoc, Callsite.Func);
488 CallSiteLoc = Callsite.Location;
497 auto *NodeProfile =
Node.FuncSamples;
498 for (
auto &It :
Node.AllChildFrames) {
499 auto &ChildNode = It.second;
501 auto *ChildProfile = ChildNode.FuncSamples;
507 ChildProfile->getContext().setFunction(OrigChildContext.
getFunction());
510 auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
511 SamplesMap.emplace(OrigChildContext.
getFunction(), *ChildProfile);
512 NodeProfile->addTotalSamples(ChildProfile->getTotalSamples());
515 auto Count = NodeProfile->removeCalledTargetAndBodySample(
516 ChildNode.CallSiteLoc.LineOffset, ChildNode.CallSiteLoc.Discriminator,
518 NodeProfile->removeTotalSamples(Count);
529 ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
530 NewChildProfileHash = ChildProfile->getContext().getHashCode();
532 ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
533 NewChildProfileHash = ChildProfile->getContext().getHashCode();
534 auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
535 SamplesMap[ChildProfile->getFunction()].getContext().setAttribute(
542 if (NewChildProfileHash != OrigChildContextHash)
543 ProfileMap.
erase(OrigChildContextHash);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
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)
static cl::opt< bool > GenerateMergedBaseProfiles("generate-merged-base-profiles", cl::desc("When generating nested context-sensitive profiles, always " "generate extra base profile for function with all its context " "profiles merged into it."))
static cl::opt< uint64_t > ProfileSymbolListCutOff("profile-symbol-list-cutoff", cl::Hidden, cl::init(-1), cl::desc("Cutoff value about how many symbols in profile symbol list " "will be used. This is very useful for performance debugging"))
unsigned getBaseDiscriminator() const
Returns the base discriminator stored in the discriminator.
Implements a dense probed hash-table based set.
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
reference emplace_back(ArgTypes &&... Args)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
std::pair< iterator, bool > insert(const ValueT &V)
void insert_range(Range &&R)
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
This class represents a function that is read from a sample profile.
Representation of the samples collected for a function.
static LLVM_ABI bool ProfileIsPreInlined
LLVM_ABI const FunctionSamples * findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName, SampleProfileReaderItaniumRemapper *Remapper, const HashKeyMap< std::unordered_map, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const
Returns a pointer to FunctionSamples at the given callsite location Loc with callee CalleeName.
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 LLVM_ABI bool ProfileIsCS
const LineLocation & mapIRLocToProfileLoc(const LineLocation &IRLoc) const
FunctionId getFunction() const
Return the function name.
uint64_t getFunctionHash() const
LLVM_ABI const FunctionSamples * findFunctionSamples(const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper=nullptr, const HashKeyMap< std::unordered_map, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const
Get the FunctionSamples of the inline instance where DIL originates from.
static LLVM_ABI bool ProfileIsProbeBased
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
LLVM_ABI void findAllNames(DenseSet< FunctionId > &NameSet) const
static LLVM_ABI unsigned getOffset(const DILocation *DIL)
Returns the line offset to the start line of the subprogram.
static LLVM_ABI bool ProfileIsFS
If this profile uses flow sensitive discriminators.
SampleContext & getContext() const
static LLVM_ABI bool HasUniqSuffix
Whether the profile contains any ".__uniq." suffix in a name.
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
LLVM_ABI void print(raw_ostream &OS=dbgs(), unsigned Indent=0) const
Print the samples collected for a function on stream OS.
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
LLVM_ABI void dump() const
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.
static LLVM_ABI bool UseMD5
Whether the profile uses MD5 to represent string.
This class is a wrapper to associative container MapT<KeyT, ValueT> using the hash value of the origi...
iterator find(const original_key_type &Key)
LLVM_ABI ProfileConverter(SampleProfileMap &Profiles)
LLVM_ABI void convertCSProfiles()
void add(StringRef Name, bool Copy=false)
copy indicates whether we need to copy the underlying memory for the input Name.
LLVM_ABI std::error_code write(raw_ostream &OS)
LLVM_ABI void dump(raw_ostream &OS=dbgs()) const
LLVM_ABI std::error_code read(const uint8_t *Data, uint64_t ListSize)
LLVM_ABI void trimAndMergeColdContextProfiles(uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext, uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly)
uint64_t getHashCode() const
FunctionId getFunction() const
This class provides operator overloads to the map container using MD5 as the key type,...
mapped_type & create(const SampleContext &Ctx)
size_t erase(const SampleContext &Ctx)
SampleProfileReaderItaniumRemapper remaps the profile data from a sample profile data reader,...
LLVM_ABI std::optional< StringRef > lookUpNameInProfile(StringRef FunctionName)
Return the equivalent name in the profile for FunctionName if it exists.
Representation of a single sample record.
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.
const CallTargetMap & getCallTargets() const
uint64_t getSamples() const
sampleprof_error addSamples(uint64_t S, uint64_t Weight=1)
Increment the number of samples for this record by S.
const SortedCallTargetSet getSortedCallTargets() 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.
Sort a LocationT->SampleT map by LocationT.
const SamplesWithLocList & get() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
static FunctionId getRepInFormat(StringRef Name)
Get the proper representation of a string according to whether the current Format uses MD5 to represe...
LLVM_ABI void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
std::pair< hash_code, const FunctionSamples * > NameFunctionSamples
@ ContextDuplicatedIntoBase
raw_ostream & operator<<(raw_ostream &OS, const FunctionId &Obj)
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
sampleprof_error mergeSampleProfErrors(sampleprof_error &Accumulator, sampleprof_error Result)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
LLVM_ABI const std::error_category & sampleprof_category()
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
static uint32_t extractProbeIndex(uint32_t Value)
Represents the relative location of an instruction.
LLVM_ABI void serialize(raw_ostream &OS) const
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI void dump() const
LLVM_ABI FrameNode * getOrCreateChildFrame(const LineLocation &CallSite, FunctionId CalleeName)
std::map< uint64_t, FrameNode > AllChildFrames