1 //=-- InstrProf.h - Instrumented profiling format support ---------*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Instrumentation-based profiling data is generated by instrumented
11 // binaries through library functions in compiler-rt, and read by the clang
12 // frontend to feed PGO.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_PROFILEDATA_INSTRPROF_H_
17 #define LLVM_PROFILEDATA_INSTRPROF_H_
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/StringSet.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/IR/GlobalValue.h"
23 #include "llvm/ProfileData/InstrProfData.inc"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/ErrorOr.h"
27 #include "llvm/Support/MD5.h"
30 #include <system_error>
39 /// Return the name of data section containing profile counter variables.
40 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
41 return AddSegment ? "__DATA," INSTR_PROF_CNTS_SECT_NAME_STR
42 : INSTR_PROF_CNTS_SECT_NAME_STR;
45 /// Return the name of data section containing names of instrumented
47 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
48 return AddSegment ? "__DATA," INSTR_PROF_NAME_SECT_NAME_STR
49 : INSTR_PROF_NAME_SECT_NAME_STR;
52 /// Return the name of the data section containing per-function control
54 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
55 return AddSegment ? "__DATA," INSTR_PROF_DATA_SECT_NAME_STR
56 : INSTR_PROF_DATA_SECT_NAME_STR;
59 /// Return the name profile runtime entry point to do value profiling
61 inline StringRef getInstrProfValueProfFuncName() {
62 return INSTR_PROF_VALUE_PROF_FUNC_STR;
65 /// Return the name of the section containing function coverage mapping
67 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
68 return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
71 /// Return the name prefix of variables containing instrumented function names.
72 inline StringRef getInstrProfNameVarPrefix() { return "__llvm_profile_name_"; }
74 /// Return the name prefix of variables containing per-function control data.
75 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
77 /// Return the name prefix of profile counter variables.
78 inline StringRef getInstrProfCountersVarPrefix() {
79 return "__llvm_profile_counters_";
82 /// Return the name prefix of the COMDAT group for instrumentation variables
83 /// associated with a COMDAT function.
84 inline StringRef getInstrProfComdatPrefix() { return "__llvm_profile_vars_"; }
86 /// Return the name of a covarage mapping variable (internal linkage)
87 /// for each instrumented source module. Such variables are allocated
88 /// in the __llvm_covmap section.
89 inline StringRef getCoverageMappingVarName() {
90 return "__llvm_coverage_mapping";
93 /// Return the name of function that registers all the per-function control
94 /// data at program startup time by calling __llvm_register_function. This
95 /// function has internal linkage and is called by __llvm_profile_init
96 /// runtime method. This function is not generated for these platforms:
97 /// Darwin, Linux, and FreeBSD.
98 inline StringRef getInstrProfRegFuncsName() {
99 return "__llvm_profile_register_functions";
102 /// Return the name of the runtime interface that registers per-function control
103 /// data for one instrumented function.
104 inline StringRef getInstrProfRegFuncName() {
105 return "__llvm_profile_register_function";
108 /// Return the name of the runtime initialization method that is generated by
109 /// the compiler. The function calls __llvm_profile_register_functions and
110 /// __llvm_profile_override_default_filename functions if needed. This function
111 /// has internal linkage and invoked at startup time via init_array.
112 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
114 /// Return the name of the hook variable defined in profile runtime library.
115 /// A reference to the variable causes the linker to link in the runtime
116 /// initialization module (which defines the hook variable).
117 inline StringRef getInstrProfRuntimeHookVarName() {
118 return "__llvm_profile_runtime";
121 /// Return the name of the compiler generated function that references the
122 /// runtime hook variable. The function is a weak global.
123 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
124 return "__llvm_profile_runtime_user";
127 /// Return the name of the profile runtime interface that overrides the default
128 /// profile data file name.
129 inline StringRef getInstrProfFileOverriderFuncName() {
130 return "__llvm_profile_override_default_filename";
133 /// Return the modified name for function \c F suitable to be
134 /// used the key for profile lookup.
135 std::string getPGOFuncName(const Function &F);
137 /// Return the modified name for a function suitable to be
138 /// used the key for profile lookup. The function's original
139 /// name is \c RawFuncName and has linkage of type \c Linkage.
140 /// The function is defined in module \c FileName.
141 std::string getPGOFuncName(StringRef RawFuncName,
142 GlobalValue::LinkageTypes Linkage,
145 /// Create and return the global variable for function name used in PGO
146 /// instrumentation. \c FuncName is the name of the function returned
147 /// by \c getPGOFuncName call.
148 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName);
150 /// Create and return the global variable for function name used in PGO
151 /// instrumentation. /// \c FuncName is the name of the function
152 /// returned by \c getPGOFuncName call, \c M is the owning module,
153 /// and \c Linkage is the linkage of the instrumented function.
154 GlobalVariable *createPGOFuncNameVar(Module &M,
155 GlobalValue::LinkageTypes Linkage,
158 const std::error_category &instrprof_category();
160 enum class instrprof_error {
167 unsupported_hash_type,
175 value_site_count_mismatch
178 inline std::error_code make_error_code(instrprof_error E) {
179 return std::error_code(static_cast<int>(E), instrprof_category());
182 enum InstrProfValueKind : uint32_t {
183 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
184 #include "llvm/ProfileData/InstrProfData.inc"
187 struct InstrProfStringTable {
188 // Set of string values in profiling data.
189 StringSet<> StringValueSet;
190 InstrProfStringTable() { StringValueSet.clear(); }
191 // Get a pointer to internal storage of a string in set
192 const char *getStringData(StringRef Str) {
193 auto Result = StringValueSet.find(Str);
194 return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
196 // Insert a string to StringTable
197 const char *insertString(StringRef Str) {
198 auto Result = StringValueSet.insert(Str);
199 return Result.first->first().data();
203 struct InstrProfValueSiteRecord {
204 /// Value profiling data pairs at a given value site.
205 std::list<InstrProfValueData> ValueData;
207 InstrProfValueSiteRecord() { ValueData.clear(); }
208 template <class InputIterator>
209 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
212 /// Sort ValueData ascending by Value
213 void sortByTargetValues() {
215 [](const InstrProfValueData &left, const InstrProfValueData &right) {
216 return left.Value < right.Value;
220 /// Merge data from another InstrProfValueSiteRecord
221 /// Optionally scale merged counts by \p Weight.
222 void mergeValueData(InstrProfValueSiteRecord &Input, uint64_t Weight = 1) {
223 this->sortByTargetValues();
224 Input.sortByTargetValues();
225 auto I = ValueData.begin();
226 auto IE = ValueData.end();
227 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
229 while (I != IE && I->Value < J->Value)
231 if (I != IE && I->Value == J->Value) {
232 // TODO: Check for counter overflow and return error if it occurs.
233 uint64_t JCount = J->Count;
235 JCount = SaturatingMultiply(JCount, Weight);
236 I->Count = SaturatingAdd(I->Count, JCount);
240 ValueData.insert(I, *J);
245 /// Profiling information for a single function.
246 struct InstrProfRecord {
248 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
249 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
252 std::vector<uint64_t> Counts;
254 typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
256 /// Return the number of value profile kinds with non-zero number
257 /// of profile sites.
258 inline uint32_t getNumValueKinds() const;
259 /// Return the number of instrumented sites for ValueKind.
260 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
261 /// Return the total number of ValueData for ValueKind.
262 inline uint32_t getNumValueData(uint32_t ValueKind) const;
263 /// Return the number of value data collected for ValueKind at profiling
265 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
266 uint32_t Site) const;
267 /// Return the array of profiled values at \p Site.
268 inline std::unique_ptr<InstrProfValueData[]>
269 getValueForSite(uint32_t ValueKind, uint32_t Site,
270 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
272 getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind, uint32_t Site,
273 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
274 /// Reserve space for NumValueSites sites.
275 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
276 /// Add ValueData for ValueKind at value Site.
277 inline void addValueData(uint32_t ValueKind, uint32_t Site,
278 InstrProfValueData *VData, uint32_t N,
279 ValueMapType *HashKeys);
281 /// Merge the counts in \p Other into this one.
282 /// Optionally scale merged counts by \p Weight.
283 inline instrprof_error merge(InstrProfRecord &Other, uint64_t Weight = 1);
285 /// Used by InstrProfWriter: update the value strings to commoned strings in
286 /// the writer instance.
287 inline void updateStrings(InstrProfStringTable *StrTab);
289 /// Clear value data entries
290 inline void clearValueData() {
291 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
292 getValueSitesForKind(Kind).clear();
296 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
297 const std::vector<InstrProfValueSiteRecord> &
298 getValueSitesForKind(uint32_t ValueKind) const {
300 case IPVK_IndirectCallTarget:
301 return IndirectCallSites;
303 llvm_unreachable("Unknown value kind!");
305 return IndirectCallSites;
308 std::vector<InstrProfValueSiteRecord> &
309 getValueSitesForKind(uint32_t ValueKind) {
310 return const_cast<std::vector<InstrProfValueSiteRecord> &>(
311 const_cast<const InstrProfRecord *>(this)
312 ->getValueSitesForKind(ValueKind));
315 // Map indirect call target name hash to name string.
316 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
317 ValueMapType *HashKeys) {
321 case IPVK_IndirectCallTarget: {
323 std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
324 [](const std::pair<uint64_t, const char *> &LHS,
325 uint64_t RHS) { return LHS.first < RHS; });
326 if (Result != HashKeys->end())
327 Value = (uint64_t)Result->second;
334 // Merge Value Profile data from Src record to this record for ValueKind.
335 // Scale merged value counts by \p Weight.
336 instrprof_error mergeValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
338 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
339 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
340 if (ThisNumValueSites != OtherNumValueSites)
341 return instrprof_error::value_site_count_mismatch;
342 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
343 getValueSitesForKind(ValueKind);
344 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
345 Src.getValueSitesForKind(ValueKind);
346 for (uint32_t I = 0; I < ThisNumValueSites; I++)
347 ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I], Weight);
348 return instrprof_error::success;
352 uint32_t InstrProfRecord::getNumValueKinds() const {
353 uint32_t NumValueKinds = 0;
354 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
355 NumValueKinds += !(getValueSitesForKind(Kind).empty());
356 return NumValueKinds;
359 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
361 const std::vector<InstrProfValueSiteRecord> &SiteRecords =
362 getValueSitesForKind(ValueKind);
363 for (auto &SR : SiteRecords) {
364 N += SR.ValueData.size();
369 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
370 return getValueSitesForKind(ValueKind).size();
373 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
374 uint32_t Site) const {
375 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
378 std::unique_ptr<InstrProfValueData[]> InstrProfRecord::getValueForSite(
379 uint32_t ValueKind, uint32_t Site,
380 uint64_t (*ValueMapper)(uint32_t, uint64_t)) const {
381 uint32_t N = getNumValueDataForSite(ValueKind, Site);
383 return std::unique_ptr<InstrProfValueData[]>(nullptr);
385 auto VD = llvm::make_unique<InstrProfValueData[]>(N);
386 getValueForSite(VD.get(), ValueKind, Site, ValueMapper);
391 void InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
392 uint32_t ValueKind, uint32_t Site,
393 uint64_t (*ValueMapper)(uint32_t,
396 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
397 Dest[I].Value = ValueMapper ? ValueMapper(ValueKind, V.Value) : V.Value;
398 Dest[I].Count = V.Count;
403 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
404 InstrProfValueData *VData, uint32_t N,
405 ValueMapType *HashKeys) {
406 for (uint32_t I = 0; I < N; I++) {
407 VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
409 std::vector<InstrProfValueSiteRecord> &ValueSites =
410 getValueSitesForKind(ValueKind);
412 ValueSites.push_back(InstrProfValueSiteRecord());
414 ValueSites.emplace_back(VData, VData + N);
417 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
418 std::vector<InstrProfValueSiteRecord> &ValueSites =
419 getValueSitesForKind(ValueKind);
420 ValueSites.reserve(NumValueSites);
423 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
427 Name = StrTab->insertString(Name);
428 for (auto &VSite : IndirectCallSites)
429 for (auto &VData : VSite.ValueData)
430 VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
433 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
435 // If the number of counters doesn't match we either have bad data
436 // or a hash collision.
437 if (Counts.size() != Other.Counts.size())
438 return instrprof_error::count_mismatch;
440 instrprof_error Result = instrprof_error::success;
442 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
443 bool ResultOverflowed;
444 uint64_t OtherCount = Other.Counts[I];
446 OtherCount = SaturatingMultiply(OtherCount, Weight, ResultOverflowed);
447 if (ResultOverflowed)
448 Result = instrprof_error::counter_overflow;
450 Counts[I] = SaturatingAdd(Counts[I], OtherCount, ResultOverflowed);
451 if (ResultOverflowed)
452 Result = instrprof_error::counter_overflow;
455 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
456 instrprof_error MergeValueResult = mergeValueProfData(Kind, Other, Weight);
457 if (MergeValueResult != instrprof_error::success)
458 Result = MergeValueResult;
464 inline support::endianness getHostEndianness() {
465 return sys::IsLittleEndianHost ? support::little : support::big;
469 // Include definitions for value profile data
470 #define INSTR_PROF_VALUE_PROF_DATA
471 #include "llvm/ProfileData/InstrProfData.inc"
474 * Initialize the record for runtime value profile data.
475 * Return 0 if the initialization is successful, otherwise
478 int initializeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord,
479 const uint16_t *NumValueSites,
480 ValueProfNode **Nodes);
482 /* Release memory allocated for the runtime record. */
483 void finalizeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord);
485 /* Return the size of ValueProfData structure that can be used to store
486 the value profile data collected at runtime. */
487 uint32_t getValueProfDataSizeRT(const ValueProfRuntimeRecord *Record);
489 /* Return a ValueProfData instance that stores the data collected at runtime. */
491 serializeValueProfDataFromRT(const ValueProfRuntimeRecord *Record,
494 namespace IndexedInstrProf {
496 enum class HashT : uint32_t {
502 static inline uint64_t MD5Hash(StringRef Str) {
505 llvm::MD5::MD5Result Result;
507 // Return the least significant 8 bytes. Our MD5 implementation returns the
508 // result in little endian, so we may need to swap bytes.
509 using namespace llvm::support;
510 return endian::read<uint64_t, little, unaligned>(Result);
513 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
516 return IndexedInstrProf::MD5Hash(K);
518 llvm_unreachable("Unhandled hash type");
521 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
522 const uint64_t Version = 3;
523 const HashT HashType = HashT::MD5;
525 // This structure defines the file header of the LLVM profile
526 // data file in indexed-format.
530 uint64_t MaxFunctionCount;
535 } // end namespace IndexedInstrProf
537 namespace RawInstrProf {
539 const uint64_t Version = INSTR_PROF_RAW_VERSION;
541 template <class IntPtrT> inline uint64_t getMagic();
542 template <> inline uint64_t getMagic<uint64_t>() {
543 return INSTR_PROF_RAW_MAGIC_64;
546 template <> inline uint64_t getMagic<uint32_t>() {
547 return INSTR_PROF_RAW_MAGIC_32;
550 // Per-function profile data header/control structure.
551 // The definition should match the structure defined in
552 // compiler-rt/lib/profile/InstrProfiling.h.
553 // It should also match the synthesized type in
554 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
555 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
556 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
557 #include "llvm/ProfileData/InstrProfData.inc"
560 // File header structure of the LLVM profile data in raw format.
561 // The definition should match the header referenced in
562 // compiler-rt/lib/profile/InstrProfilingFile.c and
563 // InstrProfilingBuffer.c.
565 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
566 #include "llvm/ProfileData/InstrProfData.inc"
569 } // end namespace RawInstrProf
573 // Profile coverage map has the following layout:
574 // [CoverageMapFileHeader]
576 // [CovMapFunctionRecord]
577 // [CovMapFunctionRecord]
580 // [Encoded Region Mapping Data]
582 template <class IntPtrT> struct CovMapFunctionRecord {
583 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
584 #include "llvm/ProfileData/InstrProfData.inc"
590 } // end namespace llvm
594 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
597 #endif // LLVM_PROFILEDATA_INSTRPROF_H_