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/IR/GlobalValue.h"
22 #include "llvm/ProfileData/InstrProfData.inc"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/ErrorOr.h"
26 #include "llvm/Support/MD5.h"
29 #include <system_error>
38 /// Return the name of data section containing profile counter variables.
39 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
40 return AddSegment ? "__DATA," INSTR_PROF_CNTS_SECT_NAME_STR
41 : INSTR_PROF_CNTS_SECT_NAME_STR;
44 /// Return the name of data section containing names of instrumented
46 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
47 return AddSegment ? "__DATA," INSTR_PROF_NAME_SECT_NAME_STR
48 : INSTR_PROF_NAME_SECT_NAME_STR;
51 /// Return the name of the data section containing per-function control
53 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
54 return AddSegment ? "__DATA," INSTR_PROF_DATA_SECT_NAME_STR
55 : INSTR_PROF_DATA_SECT_NAME_STR;
58 /// Return the name profile runtime entry point to do value profiling
60 inline StringRef getInstrProfValueProfFuncName() {
61 return INSTR_PROF_VALUE_PROF_FUNC_STR;
64 /// Return the name of the section containing function coverage mapping
66 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
67 return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
70 /// Return the name prefix of variables containing instrumented function names.
71 inline StringRef getInstrProfNameVarPrefix() { return "__llvm_profile_name_"; }
73 /// Return the name prefix of variables containing per-function control data.
74 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
76 /// Return the name prefix of profile counter variables.
77 inline StringRef getInstrProfCountersVarPrefix() {
78 return "__llvm_profile_counters_";
81 /// Return the name prefix of the COMDAT group for instrumentation variables
82 /// associated with a COMDAT function.
83 inline StringRef getInstrProfComdatPrefix() { return "__llvm_profile_vars_"; }
85 /// Return the name of a covarage mapping variable (internal linkage)
86 /// for each instrumented source module. Such variables are allocated
87 /// in the __llvm_covmap section.
88 inline StringRef getCoverageMappingVarName() {
89 return "__llvm_coverage_mapping";
92 /// Return the name of function that registers all the per-function control
93 /// data at program startup time by calling __llvm_register_function. This
94 /// function has internal linkage and is called by __llvm_profile_init
95 /// runtime method. This function is not generated for these platforms:
96 /// Darwin, Linux, and FreeBSD.
97 inline StringRef getInstrProfRegFuncsName() {
98 return "__llvm_profile_register_functions";
101 /// Return the name of the runtime interface that registers per-function control
102 /// data for one instrumented function.
103 inline StringRef getInstrProfRegFuncName() {
104 return "__llvm_profile_register_function";
107 /// Return the name of the runtime initialization method that is generated by
108 /// the compiler. The function calls __llvm_profile_register_functions and
109 /// __llvm_profile_override_default_filename functions if needed. This function
110 /// has internal linkage and invoked at startup time via init_array.
111 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
113 /// Return the name of the hook variable defined in profile runtime library.
114 /// A reference to the variable causes the linker to link in the runtime
115 /// initialization module (which defines the hook variable).
116 inline StringRef getInstrProfRuntimeHookVarName() {
117 return "__llvm_profile_runtime";
120 /// Return the name of the compiler generated function that references the
121 /// runtime hook variable. The function is a weak global.
122 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
123 return "__llvm_profile_runtime_user";
126 /// Return the name of the profile runtime interface that overrides the default
127 /// profile data file name.
128 inline StringRef getInstrProfFileOverriderFuncName() {
129 return "__llvm_profile_override_default_filename";
132 /// Return the modified name for function \c F suitable to be
133 /// used the key for profile lookup.
134 std::string getPGOFuncName(const Function &F);
136 /// Return the modified name for a function suitable to be
137 /// used the key for profile lookup. The function's original
138 /// name is \c RawFuncName and has linkage of type \c Linkage.
139 /// The function is defined in module \c FileName.
140 std::string getPGOFuncName(StringRef RawFuncName,
141 GlobalValue::LinkageTypes Linkage,
144 /// Create and return the global variable for function name used in PGO
145 /// instrumentation. \c FuncName is the name of the function returned
146 /// by \c getPGOFuncName call.
147 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName);
149 /// Create and return the global variable for function name used in PGO
150 /// instrumentation. /// \c FuncName is the name of the function
151 /// returned by \c getPGOFuncName call, \c M is the owning module,
152 /// and \c Linkage is the linkage of the instrumented function.
153 GlobalVariable *createPGOFuncNameVar(Module &M,
154 GlobalValue::LinkageTypes Linkage,
157 const std::error_category &instrprof_category();
159 enum class instrprof_error {
166 unsupported_hash_type,
174 value_site_count_mismatch
177 inline std::error_code make_error_code(instrprof_error E) {
178 return std::error_code(static_cast<int>(E), instrprof_category());
181 enum InstrProfValueKind : uint32_t {
182 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
183 #include "llvm/ProfileData/InstrProfData.inc"
186 struct InstrProfStringTable {
187 // Set of string values in profiling data.
188 StringSet<> StringValueSet;
189 InstrProfStringTable() { StringValueSet.clear(); }
190 // Get a pointer to internal storage of a string in set
191 const char *getStringData(StringRef Str) {
192 auto Result = StringValueSet.find(Str);
193 return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
195 // Insert a string to StringTable
196 const char *insertString(StringRef Str) {
197 auto Result = StringValueSet.insert(Str);
198 return Result.first->first().data();
202 struct InstrProfValueData {
205 // Number of times the value appears in the training run.
209 struct InstrProfValueSiteRecord {
210 /// Value profiling data pairs at a given value site.
211 std::list<InstrProfValueData> ValueData;
213 InstrProfValueSiteRecord() { ValueData.clear(); }
214 template <class InputIterator>
215 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
218 /// Sort ValueData ascending by Value
219 void sortByTargetValues() {
221 [](const InstrProfValueData &left, const InstrProfValueData &right) {
222 return left.Value < right.Value;
226 /// Merge data from another InstrProfValueSiteRecord
227 void mergeValueData(InstrProfValueSiteRecord &Input) {
228 this->sortByTargetValues();
229 Input.sortByTargetValues();
230 auto I = ValueData.begin();
231 auto IE = ValueData.end();
232 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
234 while (I != IE && I->Value < J->Value)
236 if (I != IE && I->Value == J->Value) {
237 I->Count = SaturatingAdd(I->Count, J->Count);
241 ValueData.insert(I, *J);
246 /// Profiling information for a single function.
247 struct InstrProfRecord {
249 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
250 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
253 std::vector<uint64_t> Counts;
255 typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
257 /// Return the number of value profile kinds with non-zero number
258 /// of profile sites.
259 inline uint32_t getNumValueKinds() const;
260 /// Return the number of instrumented sites for ValueKind.
261 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
262 /// Return the total number of ValueData for ValueKind.
263 inline uint32_t getNumValueData(uint32_t ValueKind) const;
264 /// Return the number of value data collected for ValueKind at profiling
266 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
267 uint32_t Site) const;
268 inline std::unique_ptr<InstrProfValueData[]>
269 getValueForSite(uint32_t ValueKind, uint32_t Site) const;
270 /// Reserve space for NumValueSites sites.
271 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
272 /// Add ValueData for ValueKind at value Site.
273 inline void addValueData(uint32_t ValueKind, uint32_t Site,
274 InstrProfValueData *VData, uint32_t N,
275 ValueMapType *HashKeys);
277 /// Merge the counts in \p Other into this one.
278 inline instrprof_error merge(InstrProfRecord &Other);
280 /// Used by InstrProfWriter: update the value strings to commoned strings in
281 /// the writer instance.
282 inline void updateStrings(InstrProfStringTable *StrTab);
284 /// Clear value data entries
285 inline void clearValueData() {
286 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
287 getValueSitesForKind(Kind).clear();
291 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
292 const std::vector<InstrProfValueSiteRecord> &
293 getValueSitesForKind(uint32_t ValueKind) const {
295 case IPVK_IndirectCallTarget:
296 return IndirectCallSites;
298 llvm_unreachable("Unknown value kind!");
300 return IndirectCallSites;
303 std::vector<InstrProfValueSiteRecord> &
304 getValueSitesForKind(uint32_t ValueKind) {
305 return const_cast<std::vector<InstrProfValueSiteRecord> &>(
306 const_cast<const InstrProfRecord *>(this)
307 ->getValueSitesForKind(ValueKind));
310 // Map indirect call target name hash to name string.
311 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
312 ValueMapType *HashKeys) {
316 case IPVK_IndirectCallTarget: {
318 std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
319 [](const std::pair<uint64_t, const char *> &LHS,
320 uint64_t RHS) { return LHS.first < RHS; });
321 if (Result != HashKeys->end())
322 Value = (uint64_t)Result->second;
329 // Merge Value Profile data from Src record to this record for ValueKind.
330 instrprof_error mergeValueProfData(uint32_t ValueKind, InstrProfRecord &Src) {
331 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
332 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
333 if (ThisNumValueSites != OtherNumValueSites)
334 return instrprof_error::value_site_count_mismatch;
335 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
336 getValueSitesForKind(ValueKind);
337 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
338 Src.getValueSitesForKind(ValueKind);
339 for (uint32_t I = 0; I < ThisNumValueSites; I++)
340 ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I]);
341 return instrprof_error::success;
345 uint32_t InstrProfRecord::getNumValueKinds() const {
346 uint32_t NumValueKinds = 0;
347 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
348 NumValueKinds += !(getValueSitesForKind(Kind).empty());
349 return NumValueKinds;
352 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
354 const std::vector<InstrProfValueSiteRecord> &SiteRecords =
355 getValueSitesForKind(ValueKind);
356 for (auto &SR : SiteRecords) {
357 N += SR.ValueData.size();
362 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
363 return getValueSitesForKind(ValueKind).size();
366 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
367 uint32_t Site) const {
368 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
371 std::unique_ptr<InstrProfValueData[]>
372 InstrProfRecord::getValueForSite(uint32_t ValueKind, uint32_t Site) const {
373 uint32_t N = getNumValueDataForSite(ValueKind, Site);
375 return std::unique_ptr<InstrProfValueData[]>(nullptr);
377 std::unique_ptr<InstrProfValueData[]> VD(new InstrProfValueData[N]);
379 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 /// This is the header of the data structure that defines the on-disk
444 /// layout of the value profile data of a particular kind for one function.
445 struct ValueProfRecord {
446 // The kind of the value profile record.
448 // The number of value profile sites. It is guaranteed to be non-zero;
449 // otherwise the record for this kind won't be emitted.
450 uint32_t NumValueSites;
451 // The first element of the array that stores the number of profiled
452 // values for each value site. The size of the array is NumValueSites.
453 // Since NumValueSites is greater than zero, there is at least one
454 // element in the array.
455 uint8_t SiteCountArray[1];
457 // The fake declaration is for documentation purpose only.
458 // Align the start of next field to be on 8 byte boundaries.
459 // uint8_t Padding[X];
461 // The array of value profile data. The size of the array is the sum
462 // of all elements in SiteCountArray[].
463 // InstrProfValueData ValueData[];
465 /// Return the \c ValueProfRecord header size including the padding bytes.
466 static uint32_t getHeaderSize(uint32_t NumValueSites);
467 /// Return the total size of the value profile record including the
468 /// header and the value data.
469 static uint32_t getSize(uint32_t NumValueSites, uint32_t NumValueData);
470 /// Return the total size of the value profile record including the
471 /// header and the value data.
472 uint32_t getSize() const { return getSize(NumValueSites, getNumValueData()); }
473 /// Use this method to advance to the next \c ValueProfRecord.
474 ValueProfRecord *getNext();
475 /// Return the pointer to the first value profile data.
476 InstrProfValueData *getValueData();
477 /// Return the number of value sites.
478 uint32_t getNumValueSites() const { return NumValueSites; }
479 /// Return the number of value data.
480 uint32_t getNumValueData() const;
481 /// Read data from this record and save it to Record.
482 void deserializeTo(InstrProfRecord &Record,
483 InstrProfRecord::ValueMapType *VMap);
484 /// Extract data from \c Record and serialize into this instance.
485 void serializeFrom(const InstrProfRecord &Record, uint32_t ValueKind,
486 uint32_t NumValueSites);
487 /// In-place byte swap:
488 /// Do byte swap for this instance. \c Old is the original order before
489 /// the swap, and \c New is the New byte order.
490 void swapBytes(support::endianness Old, support::endianness New);
493 /// Per-function header/control data structure for value profiling
494 /// data in indexed format.
495 struct ValueProfData {
496 // Total size in bytes including this field. It must be a multiple
497 // of sizeof(uint64_t).
499 // The number of value profile kinds that has value profile data.
500 // In this implementation, a value profile kind is considered to
501 // have profile data if the number of value profile sites for the
502 // kind is not zero. More aggressively, the implementation can
503 // choose to check the actual data value: if none of the value sites
504 // has any profiled values, the kind can be skipped.
505 uint32_t NumValueKinds;
507 // Following are a sequence of variable length records. The prefix/header
508 // of each record is defined by ValueProfRecord type. The number of
509 // records is NumValueKinds.
510 // ValueProfRecord Record_1;
511 // ValueProfRecord Record_N;
513 /// Return the total size in bytes of the on-disk value profile data
514 /// given the data stored in Record.
515 static uint32_t getSize(const InstrProfRecord &Record);
516 /// Return a pointer to \c ValueProfData instance ready to be streamed.
517 static std::unique_ptr<ValueProfData>
518 serializeFrom(const InstrProfRecord &Record);
519 /// Return a pointer to \c ValueProfileData instance ready to be read.
520 /// All data in the instance are properly byte swapped. The input
521 /// data is assumed to be in little endian order.
522 static ErrorOr<std::unique_ptr<ValueProfData>>
523 getValueProfData(const unsigned char *D, const unsigned char *const BufferEnd,
524 support::endianness SrcDataEndianness);
525 /// Swap byte order from \c Endianness order to host byte order.
526 void swapBytesToHost(support::endianness Endianness);
527 /// Swap byte order from host byte order to \c Endianness order.
528 void swapBytesFromHost(support::endianness Endianness);
529 /// Return the total size of \c ValueProfileData.
530 uint32_t getSize() const { return TotalSize; }
531 /// Read data from this data and save it to \c Record.
532 void deserializeTo(InstrProfRecord &Record,
533 InstrProfRecord::ValueMapType *VMap);
534 /// Return the first \c ValueProfRecord instance.
535 ValueProfRecord *getFirstValueProfRecord();
538 namespace IndexedInstrProf {
540 enum class HashT : uint32_t {
546 static inline uint64_t MD5Hash(StringRef Str) {
549 llvm::MD5::MD5Result Result;
551 // Return the least significant 8 bytes. Our MD5 implementation returns the
552 // result in little endian, so we may need to swap bytes.
553 using namespace llvm::support;
554 return endian::read<uint64_t, little, unaligned>(Result);
557 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
560 return IndexedInstrProf::MD5Hash(K);
562 llvm_unreachable("Unhandled hash type");
565 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
566 const uint64_t Version = 3;
567 const HashT HashType = HashT::MD5;
569 // This structure defines the file header of the LLVM profile
570 // data file in indexed-format.
574 uint64_t MaxFunctionCount;
579 } // end namespace IndexedInstrProf
581 namespace RawInstrProf {
583 const uint64_t Version = INSTR_PROF_RAW_VERSION;
585 template <class IntPtrT> inline uint64_t getMagic();
586 template <> inline uint64_t getMagic<uint64_t>() {
587 return INSTR_PROF_RAW_MAGIC_64;
590 template <> inline uint64_t getMagic<uint32_t>() {
591 return INSTR_PROF_RAW_MAGIC_32;
594 // Per-function profile data header/control structure.
595 // The definition should match the structure defined in
596 // compiler-rt/lib/profile/InstrProfiling.h.
597 // It should also match the synthesized type in
598 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
599 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
600 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
601 #include "llvm/ProfileData/InstrProfData.inc"
604 // File header structure of the LLVM profile data in raw format.
605 // The definition should match the header referenced in
606 // compiler-rt/lib/profile/InstrProfilingFile.c and
607 // InstrProfilingBuffer.c.
609 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
610 #include "llvm/ProfileData/InstrProfData.inc"
613 } // end namespace RawInstrProf
617 // Profile coverage map has the following layout:
618 // [CoverageMapFileHeader]
620 // [CovMapFunctionRecord]
621 // [CovMapFunctionRecord]
624 // [Encoded Region Mapping Data]
626 template <class IntPtrT> struct CovMapFunctionRecord {
627 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
628 #include "llvm/ProfileData/InstrProfData.inc"
634 } // end namespace llvm
638 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
641 #endif // LLVM_PROFILEDATA_INSTRPROF_H_