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 void mergeValueData(InstrProfValueSiteRecord &Input) {
222 this->sortByTargetValues();
223 Input.sortByTargetValues();
224 auto I = ValueData.begin();
225 auto IE = ValueData.end();
226 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
228 while (I != IE && I->Value < J->Value)
230 if (I != IE && I->Value == J->Value) {
231 I->Count = SaturatingAdd(I->Count, J->Count);
235 ValueData.insert(I, *J);
240 /// Profiling information for a single function.
241 struct InstrProfRecord {
243 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
244 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
247 std::vector<uint64_t> Counts;
249 typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
251 /// Return the number of value profile kinds with non-zero number
252 /// of profile sites.
253 inline uint32_t getNumValueKinds() const;
254 /// Return the number of instrumented sites for ValueKind.
255 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
256 /// Return the total number of ValueData for ValueKind.
257 inline uint32_t getNumValueData(uint32_t ValueKind) const;
258 /// Return the number of value data collected for ValueKind at profiling
260 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
261 uint32_t Site) const;
262 /// Return the array of profiled values at \p Site.
263 inline std::unique_ptr<InstrProfValueData[]>
264 getValueForSite(uint32_t ValueKind, uint32_t Site) const;
265 inline void getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind,
266 uint32_t Site) const;
267 /// Reserve space for NumValueSites sites.
268 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
269 /// Add ValueData for ValueKind at value Site.
270 inline void addValueData(uint32_t ValueKind, uint32_t Site,
271 InstrProfValueData *VData, uint32_t N,
272 ValueMapType *HashKeys);
274 /// Merge the counts in \p Other into this one.
275 inline instrprof_error merge(InstrProfRecord &Other);
277 /// Used by InstrProfWriter: update the value strings to commoned strings in
278 /// the writer instance.
279 inline void updateStrings(InstrProfStringTable *StrTab);
281 /// Clear value data entries
282 inline void clearValueData() {
283 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
284 getValueSitesForKind(Kind).clear();
288 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
289 const std::vector<InstrProfValueSiteRecord> &
290 getValueSitesForKind(uint32_t ValueKind) const {
292 case IPVK_IndirectCallTarget:
293 return IndirectCallSites;
295 llvm_unreachable("Unknown value kind!");
297 return IndirectCallSites;
300 std::vector<InstrProfValueSiteRecord> &
301 getValueSitesForKind(uint32_t ValueKind) {
302 return const_cast<std::vector<InstrProfValueSiteRecord> &>(
303 const_cast<const InstrProfRecord *>(this)
304 ->getValueSitesForKind(ValueKind));
307 // Map indirect call target name hash to name string.
308 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
309 ValueMapType *HashKeys) {
313 case IPVK_IndirectCallTarget: {
315 std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
316 [](const std::pair<uint64_t, const char *> &LHS,
317 uint64_t RHS) { return LHS.first < RHS; });
318 if (Result != HashKeys->end())
319 Value = (uint64_t)Result->second;
326 // Merge Value Profile data from Src record to this record for ValueKind.
327 instrprof_error mergeValueProfData(uint32_t ValueKind, InstrProfRecord &Src) {
328 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
329 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
330 if (ThisNumValueSites != OtherNumValueSites)
331 return instrprof_error::value_site_count_mismatch;
332 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
333 getValueSitesForKind(ValueKind);
334 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
335 Src.getValueSitesForKind(ValueKind);
336 for (uint32_t I = 0; I < ThisNumValueSites; I++)
337 ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I]);
338 return instrprof_error::success;
342 uint32_t InstrProfRecord::getNumValueKinds() const {
343 uint32_t NumValueKinds = 0;
344 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
345 NumValueKinds += !(getValueSitesForKind(Kind).empty());
346 return NumValueKinds;
349 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
351 const std::vector<InstrProfValueSiteRecord> &SiteRecords =
352 getValueSitesForKind(ValueKind);
353 for (auto &SR : SiteRecords) {
354 N += SR.ValueData.size();
359 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
360 return getValueSitesForKind(ValueKind).size();
363 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
364 uint32_t Site) const {
365 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
368 std::unique_ptr<InstrProfValueData[]>
369 InstrProfRecord::getValueForSite(uint32_t ValueKind, uint32_t Site) const {
370 uint32_t N = getNumValueDataForSite(ValueKind, Site);
372 return std::unique_ptr<InstrProfValueData[]>(nullptr);
374 auto VD = llvm::make_unique<InstrProfValueData[]>(N);
375 getValueForSite(VD.get(), ValueKind, Site);
379 void InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
380 uint32_t ValueKind, uint32_t Site) const {
382 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
388 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
389 InstrProfValueData *VData, uint32_t N,
390 ValueMapType *HashKeys) {
391 for (uint32_t I = 0; I < N; I++) {
392 VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
394 std::vector<InstrProfValueSiteRecord> &ValueSites =
395 getValueSitesForKind(ValueKind);
397 ValueSites.push_back(InstrProfValueSiteRecord());
399 ValueSites.emplace_back(VData, VData + N);
402 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
403 std::vector<InstrProfValueSiteRecord> &ValueSites =
404 getValueSitesForKind(ValueKind);
405 ValueSites.reserve(NumValueSites);
408 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
412 Name = StrTab->insertString(Name);
413 for (auto &VSite : IndirectCallSites)
414 for (auto &VData : VSite.ValueData)
415 VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
418 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other) {
419 // If the number of counters doesn't match we either have bad data
420 // or a hash collision.
421 if (Counts.size() != Other.Counts.size())
422 return instrprof_error::count_mismatch;
424 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
425 if (Counts[I] + Other.Counts[I] < Counts[I])
426 return instrprof_error::counter_overflow;
427 Counts[I] += Other.Counts[I];
430 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
431 instrprof_error result = mergeValueProfData(Kind, Other);
432 if (result != instrprof_error::success)
436 return instrprof_error::success;
439 inline support::endianness getHostEndianness() {
440 return sys::IsLittleEndianHost ? support::little : support::big;
443 /// Return the \c ValueProfRecord header size including the padding bytes.
444 uint32_t getValueProfRecordHeaderSize(uint32_t NumValueSites);
445 /// Return the total size of the value profile record including the
446 /// header and the value data.
447 uint32_t getValueProfRecordSize(uint32_t NumValueSites, uint32_t NumValueData);
449 /// This is the header of the data structure that defines the on-disk
450 /// layout of the value profile data of a particular kind for one function.
451 typedef struct ValueProfRecord {
452 // The kind of the value profile record.
454 // The number of value profile sites. It is guaranteed to be non-zero;
455 // otherwise the record for this kind won't be emitted.
456 uint32_t NumValueSites;
457 // The first element of the array that stores the number of profiled
458 // values for each value site. The size of the array is NumValueSites.
459 // Since NumValueSites is greater than zero, there is at least one
460 // element in the array.
461 uint8_t SiteCountArray[1];
463 // The fake declaration is for documentation purpose only.
464 // Align the start of next field to be on 8 byte boundaries.
465 // uint8_t Padding[X];
467 // The array of value profile data. The size of the array is the sum
468 // of all elements in SiteCountArray[].
469 // InstrProfValueData ValueData[];
471 /// Return the total size of the value profile record including the
472 /// header and the value data.
473 uint32_t getSize() const {
474 return getValueProfRecordSize(NumValueSites, getNumValueData());
476 /// Use this method to advance to the next \c ValueProfRecord.
477 ValueProfRecord *getNext();
478 /// Return the pointer to the first value profile data.
479 InstrProfValueData *getValueData();
480 /// Return the number of value sites.
481 uint32_t getNumValueSites() const { return NumValueSites; }
482 /// Return the number of value data.
483 uint32_t getNumValueData() const;
484 /// Read data from this record and save it to Record.
485 void deserializeTo(InstrProfRecord &Record,
486 InstrProfRecord::ValueMapType *VMap);
487 /// Extract data from \c Record and serialize into this instance.
488 void serializeFrom(const InstrProfRecord &Record, uint32_t ValueKind,
489 uint32_t NumValueSites);
490 /// In-place byte swap:
491 /// Do byte swap for this instance. \c Old is the original order before
492 /// the swap, and \c New is the New byte order.
493 void swapBytes(support::endianness Old, support::endianness New);
496 /// Per-function header/control data structure for value profiling
497 /// data in indexed format.
498 typedef struct ValueProfData {
499 // Total size in bytes including this field. It must be a multiple
500 // of sizeof(uint64_t).
502 // The number of value profile kinds that has value profile data.
503 // In this implementation, a value profile kind is considered to
504 // have profile data if the number of value profile sites for the
505 // kind is not zero. More aggressively, the implementation can
506 // choose to check the actual data value: if none of the value sites
507 // has any profiled values, the kind can be skipped.
508 uint32_t NumValueKinds;
510 // Following are a sequence of variable length records. The prefix/header
511 // of each record is defined by ValueProfRecord type. The number of
512 // records is NumValueKinds.
513 // ValueProfRecord Record_1;
514 // ValueProfRecord Record_N;
516 /// Return the total size in bytes of the on-disk value profile data
517 /// given the data stored in Record.
518 static uint32_t getSize(const InstrProfRecord &Record);
519 /// Return a pointer to \c ValueProfData instance ready to be streamed.
520 static std::unique_ptr<ValueProfData>
521 serializeFrom(const InstrProfRecord &Record);
522 /// Return a pointer to \c ValueProfileData instance ready to be read.
523 /// All data in the instance are properly byte swapped. The input
524 /// data is assumed to be in little endian order.
525 static ErrorOr<std::unique_ptr<ValueProfData>>
526 getValueProfData(const unsigned char *D, const unsigned char *const BufferEnd,
527 support::endianness SrcDataEndianness);
528 /// Swap byte order from \c Endianness order to host byte order.
529 void swapBytesToHost(support::endianness Endianness);
530 /// Swap byte order from host byte order to \c Endianness order.
531 void swapBytesFromHost(support::endianness Endianness);
532 /// Return the total size of \c ValueProfileData.
533 uint32_t getSize() const { return TotalSize; }
534 /// Read data from this data and save it to \c Record.
535 void deserializeTo(InstrProfRecord &Record,
536 InstrProfRecord::ValueMapType *VMap);
537 /// Return the first \c ValueProfRecord instance.
538 ValueProfRecord *getFirstValueProfRecord();
541 inline uint32_t getValueProfRecordHeaderSize(uint32_t NumValueSites) {
542 uint32_t Size = offsetof(ValueProfRecord, SiteCountArray) +
543 sizeof(uint8_t) * NumValueSites;
544 // Round the size to multiple of 8 bytes.
545 Size = (Size + 7) & ~7;
549 inline uint32_t getValueProfRecordSize(uint32_t NumValueSites,
550 uint32_t NumValueData) {
551 return getValueProfRecordHeaderSize(NumValueSites) +
552 sizeof(InstrProfValueData) * NumValueData;
555 namespace IndexedInstrProf {
557 enum class HashT : uint32_t {
563 static inline uint64_t MD5Hash(StringRef Str) {
566 llvm::MD5::MD5Result Result;
568 // Return the least significant 8 bytes. Our MD5 implementation returns the
569 // result in little endian, so we may need to swap bytes.
570 using namespace llvm::support;
571 return endian::read<uint64_t, little, unaligned>(Result);
574 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
577 return IndexedInstrProf::MD5Hash(K);
579 llvm_unreachable("Unhandled hash type");
582 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
583 const uint64_t Version = 3;
584 const HashT HashType = HashT::MD5;
586 // This structure defines the file header of the LLVM profile
587 // data file in indexed-format.
591 uint64_t MaxFunctionCount;
596 } // end namespace IndexedInstrProf
598 namespace RawInstrProf {
600 const uint64_t Version = INSTR_PROF_RAW_VERSION;
602 template <class IntPtrT> inline uint64_t getMagic();
603 template <> inline uint64_t getMagic<uint64_t>() {
604 return INSTR_PROF_RAW_MAGIC_64;
607 template <> inline uint64_t getMagic<uint32_t>() {
608 return INSTR_PROF_RAW_MAGIC_32;
611 // Per-function profile data header/control structure.
612 // The definition should match the structure defined in
613 // compiler-rt/lib/profile/InstrProfiling.h.
614 // It should also match the synthesized type in
615 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
616 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
617 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
618 #include "llvm/ProfileData/InstrProfData.inc"
621 // File header structure of the LLVM profile data in raw format.
622 // The definition should match the header referenced in
623 // compiler-rt/lib/profile/InstrProfilingFile.c and
624 // InstrProfilingBuffer.c.
626 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
627 #include "llvm/ProfileData/InstrProfData.inc"
630 } // end namespace RawInstrProf
634 // Profile coverage map has the following layout:
635 // [CoverageMapFileHeader]
637 // [CovMapFunctionRecord]
638 // [CovMapFunctionRecord]
641 // [Encoded Region Mapping Data]
643 template <class IntPtrT> struct CovMapFunctionRecord {
644 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
645 #include "llvm/ProfileData/InstrProfData.inc"
651 } // end namespace llvm
655 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
658 #endif // LLVM_PROFILEDATA_INSTRPROF_H_