16 #ifndef LLVM_PROFILEDATA_INSTRPROF_H
17 #define LLVM_PROFILEDATA_INSTRPROF_H
43 #include <system_error>
51 struct InstrProfRecord;
52 class InstrProfSymtab;
58 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind,
69 bool AddSegmentInfo =
true);
74 return INSTR_PROF_VALUE_PROF_FUNC_STR;
79 return INSTR_PROF_VALUE_RANGE_PROF_FUNC_STR;
104 return "__llvm_prf_nm";
111 return "__llvm_coverage_mapping";
119 return "__llvm_coverage_names";
128 return "__llvm_profile_register_functions";
134 return "__llvm_profile_register_function";
139 return "__llvm_profile_register_names_function";
152 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_RUNTIME_VAR);
158 return "__llvm_profile_runtime_user";
168 uint64_t
Version = INSTR_PROF_INDEX_VERSION);
177 uint64_t
Version = INSTR_PROF_INDEX_VERSION);
196 StringRef PGOFuncName);
204 StringRef FileName =
"<unknown>");
216 bool doCompression, std::string &Result);
221 std::string &Result,
bool doCompression =
true);
238 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
246 const InstrProfRecord &InstrProfR,
252 ArrayRef<InstrProfValueData> VDs, uint64_t Sum,
261 InstrProfValueData ValueData[],
262 uint32_t &ActualNumValueData, uint64_t &TotalC);
311 std::string
message()
const override;
346 unsigned NumHashMismatches = 0;
349 unsigned NumCountMismatches = 0;
352 unsigned NumCounterOverflows = 0;
355 unsigned NumValueSiteCountMismatches = 0;
362 "Unchecked soft error encountered");
379 return NumValueSiteCountMismatches;
387 auto E = make_error<InstrProfError>(FirstError);
399 namespace IndexedInstrProf {
416 uint64_t Address = 0;
420 std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
423 std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
456 template <
typename NameIterRange>
Error create(
const NameIterRange &IterRange);
467 if (FuncName.
empty())
471 MD5NameMap.push_back(std::make_pair(
479 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
515 template <
typename NameIterRange>
517 for (
auto Name : IterRange)
529 AddrToMD5Map.erase(std::unique(AddrToMD5Map.begin(), AddrToMD5Map.end()),
535 std::lower_bound(MD5NameMap.begin(), MD5NameMap.end(), FuncMD5Hash,
536 [](
const std::pair<uint64_t, std::string> &LHS,
537 uint64_t RHS) {
return LHS.first < RHS; });
538 if (Result != MD5NameMap.end() && Result->first == FuncMD5Hash)
539 return Result->second;
545 std::lower_bound(MD5FuncMap.begin(), MD5FuncMap.end(), FuncMD5Hash,
546 [](
const std::pair<uint64_t, Function*> &LHS,
547 uint64_t RHS) {
return LHS.first < RHS; });
548 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
549 return Result->second;
568 template <
class InputIterator>
575 [](
const InstrProfValueData &left,
const InstrProfValueData &right) {
576 return left.Value < right.Value;
599 ValueData(RHS.ValueData
605 if (!RHS.ValueData) {
610 ValueData = llvm::make_unique<ValueProfData>(*RHS.ValueData);
612 *ValueData = *RHS.ValueData;
635 inline std::unique_ptr<InstrProfValueData[]>
637 uint64_t *TotalC =
nullptr)
const;
665 for (
auto &SR : getValueSitesForKind(
Kind))
679 struct ValueProfData {
680 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
681 std::vector<InstrProfValueSiteRecord> MemOPSizes;
683 std::unique_ptr<ValueProfData> ValueData;
685 MutableArrayRef<InstrProfValueSiteRecord>
690 auto AR =
const_cast<const InstrProfRecord *
>(
this)->getValueSitesForKind(
693 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
695 ArrayRef<InstrProfValueSiteRecord>
696 getValueSitesForKind(
uint32_t ValueKind)
const {
700 case IPVK_IndirectCallTarget:
701 return ValueData->IndirectCallSites;
703 return ValueData->MemOPSizes;
709 std::vector<InstrProfValueSiteRecord> &
710 getOrCreateValueSitesForKind(
uint32_t ValueKind) {
712 ValueData = llvm::make_unique<ValueProfData>();
714 case IPVK_IndirectCallTarget:
715 return ValueData->IndirectCallSites;
717 return ValueData->MemOPSizes;
724 uint64_t remapValue(uint64_t Value,
uint32_t ValueKind,
734 void scaleValueProfData(
uint32_t ValueKind, uint64_t Weight,
744 std::vector<uint64_t>
Counts)
751 NumValueKinds += !(getValueSitesForKind(
Kind).empty());
752 return NumValueKinds;
757 for (
auto &SR : getValueSitesForKind(ValueKind))
758 N += SR.ValueData.size();
763 return getValueSitesForKind(ValueKind).size();
768 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
771 std::unique_ptr<InstrProfValueData[]>
773 uint64_t *TotalC)
const {
775 uint64_t &TotalCount = (TotalC ==
nullptr ? Dummy : *TotalC);
779 return std::unique_ptr<InstrProfValueData[]>(
nullptr);
782 auto VD = llvm::make_unique<InstrProfValueData[]>(
N);
792 uint64_t TotalCount = 0;
793 for (
auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
794 Dest[
I].Value = V.Value;
795 Dest[
I].Count = V.Count;
805 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
813 #define INSTR_PROF_VALUE_PROF_DATA
818 [](
const InstrProfValueData &left,
const InstrProfValueData &right) {
819 return left.Count > right.Count;
822 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
827 namespace IndexedInstrProf {
842 const uint64_t
Magic = 0x8169666f72706cff;
919 void operator delete(
void *ptr) { ::operator
delete(ptr); }
922 return sizeof(
Summary) + NumCutoffEntries *
sizeof(
Entry) +
923 NumSumFields *
sizeof(uint64_t);
927 return reinterpret_cast<const uint64_t *
>(
this + 1);
931 return reinterpret_cast<uint64_t *
>(
this + 1);
935 return reinterpret_cast<const Entry *
>(
962 return std::unique_ptr<Summary>(
new (::operator
new(TotalSize))
968 namespace RawInstrProf {
977 const uint64_t
Version = INSTR_PROF_RAW_VERSION;
979 template <
class IntPtrT>
inline uint64_t
getMagic();
981 return INSTR_PROF_RAW_MAGIC_64;
985 return INSTR_PROF_RAW_MAGIC_32;
994 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
1003 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
1011 int64_t &RangeLast);
1015 #endif // LLVM_PROFILEDATA_INSTRPROF_H
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable...
unsigned getNumCountMismatches() const
Get the number of count mismatches.
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
uint64_t NumCutoffEntries
void sortByCount()
Sort ValueData Descending by Count.
uint32_t Cutoff
The required percentile of counts.
MutableArrayRef< T > makeMutableArrayRef(T &OneElt)
Construct a MutableArrayRef from a single element.
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
void sortValueData()
Sort value profile data (per site) by count.
uint64_t MinBlockCount
The minimum execution count for this percentile.
StringRef getOrigFuncName(uint64_t FuncMD5Hash)
Return the function's original assembly name by stripping off the prefix attached (to symbols with pr...
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
A Module instance is used to store all the information related to an LLVM module. ...
uint32_t getNumValueData(uint32_t ValueKind) const
Return the total number of ValueData for ValueKind.
const Entry & getEntry(uint32_t I) const
void setEntry(uint32_t I, const ProfileSummaryEntry &E)
static instrprof_error take(Error E)
Consume an Error and return the raw enum value contained within it.
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
MDNode * getPGOFuncNameMetadata(const Function &F)
Return the PGOFuncName meta data associated with a function.
uint64_t MD5Hash(StringRef Str)
Helper to compute and return lower 64 bits of the given string's MD5 hash.
Function * getFunction(uint64_t FuncMD5Hash)
Return function from the name's md5 hash. Return nullptr if not found.
uint64_t getMagic< uint64_t >()
An efficient, type-erasing, non-owning reference to a callable.
Max block count of the program.
AddrHashMap & getAddrHashMap()
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts)
std::unique_ptr< Summary > allocSummary(uint32_t TotalSize)
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
InstrProfValueSiteRecord()
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
uint64_t * getSummaryDataBase()
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight...
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
void scale(uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by Weight.
const std::error_category & instrprof_category()
std::error_code make_error_code(BitcodeError E)
Error collectPGOFuncNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (function PGO names) NameStrs, the method generates a combined string Resul...
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
const Entry * getCutoffEntryBase() const
std::unique_ptr< InstrProfValueData[]> getValueForSite(uint32_t ValueKind, uint32_t Site, uint64_t *TotalC=nullptr) const
Return the array of profiled values at Site.
uint64_t NumSummaryFields
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
InstrProfSymtab()=default
static const bool IsLittleEndianHost
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name...
NamedInstrProfRecord()=default
unsigned getNumValueSiteCountMismatches() const
Get the number of value site count mismatches.
StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize)
Return function's PGO name from the function name's symbol address in the object file.
Entry * getCutoffEntryBase()
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
void addError(instrprof_error IE)
Track a soft error (IE) and increment its associated counter.
InstrProfRecord(const InstrProfRecord &RHS)
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
std::string message() const override
Return the error message as a string.
uint64_t getMagic< uint32_t >()
InstrProfRecord & operator=(InstrProfRecord &&)=default
void getMemOPSizeRangeFromOption(StringRef Str, int64_t &RangeStart, int64_t &RangeLast)
bool needsComdatForCounter(const Function &F, const Module &M)
Check if we can use Comdat for profile variables.
bool getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, InstrProfValueData ValueData[], uint32_t &ActualNumValueData, uint64_t &TotalC)
Extract the value profile data from Inst which is annotated with value profile meta data...
void scale(uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts.
std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
uint64_t Cutoff
The required percentile of total execution count.
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
The instances of the Type class are immutable: once they are created, they are never changed...
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
std::vector< std::pair< uint64_t, uint64_t >> AddrHashMap
std::vector< std::pair< uint64_t, uint64_t >> ValueMapType
StringRef getInstrProfNamesVarName()
Return the name of the variable holding the strings (possibly compressed) of all function's PGO names...
static ManagedStatic< _object_error_category > error_category
std::list< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
InstrProfRecord()=default
uint64_t ComputeHash(StringRef K)
unsigned getNumHashMismatches() const
Get the number of hash mismatches.
void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
uint32_t getNumValueDataForSite(uint32_t ValueKind, uint32_t Site) const
Return the number of value data collected for ValueKind at profiling site: Site.
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab)
NameStrings is a string composed of one of more sub-strings encoded in the format described above...
std::pair< typename base::iterator, bool > insert(StringRef Key)
Error takeError()
Return the first encountered error and reset FirstError to a success value.
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
void addValueData(uint32_t ValueKind, uint32_t Site, InstrProfValueData *VData, uint32_t N, ValueMapType *ValueMap)
Add ValueData for ValueKind at value Site.
void clearValueData()
Clear value data entries.
SoftInstrProfErrors()=default
InstrProfRecord(std::vector< uint64_t > Counts)
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
static ErrorSuccess success()
Create a success value.
StringRef getCoverageMappingVarName()
Return the name of a covarage mapping variable (internal linkage) for each instrumented source module...
const uint64_t * getSummaryDataBase() const
instrprof_error get() const
StringRef getPGOFuncNameMetadataName()
LinkageTypes
An enumeration for the kinds of linkage for global values.
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Base class for user error types.
void sortByTargetValues()
Sort ValueData ascending by Value.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
The total number of functions instrumented.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
std::vector< uint64_t > Counts
unsigned getNumCounterOverflows() const
Get the number of counter overflows.
The sum of all instrumented block counts.
#define LLVM_ALIGNAS(x)
LLVM_ALIGNAS
Profiling information for a single function.
std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Return the modified name for function F suitable to be used the key for profile lookup.
uint32_t getNumValueKinds() const
Return the number of value profile kinds with non-zero number of profile sites.
Error addFuncName(StringRef FuncName)
Update the symtab by adding FuncName to the table.
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
InstrProfValueSiteRecord(InputIterator F, InputIterator L)
The maximal execution count among all functions.
StringRef getNameData() const
Return the name section data.
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Max internal block count of the program (excluding entry blocks).
StringRef getInstrProfValueRangeProfFuncName()
Return the name profile runtime entry point to do value range profiling.
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
Lightweight error class with error context and mandatory checking.
uint64_t MinCount
The minimum count for this percentile.
StringSet - A wrapper for StringMap that provides set-like functionality.
support::endianness getHostEndianness()
This class implements an extremely fast bulk output stream that can only output to a stream...
InstrProfRecord & operator=(const InstrProfRecord &RHS)
StringRef - Represent a constant reference to a string, i.e.
Total number of instrumented blocks/edges.
uint64_t NumCounts
Number of counts >= the minimum count.
StringRef getInstrProfComdatPrefix()
Return the name prefix of the COMDAT group for instrumentation variables associated with a COMDAT fun...
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void set(SummaryFieldKind K, uint64_t V)
InstrProfError(instrprof_error Err)
Function object to check whether the first component of a std::pair compares less than the first comp...
void Clear()
Clear value data entries and edge counters.
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
This is a value type class that represents a single section in the list of sections in the object fil...