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/STLExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSet.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>
33 #define INSTR_PROF_INDEX_VERSION 3
40 /// Return the name of data section containing profile counter variables.
41 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
42 return AddSegment ? "__DATA," INSTR_PROF_CNTS_SECT_NAME_STR
43 : INSTR_PROF_CNTS_SECT_NAME_STR;
46 /// Return the name of data section containing names of instrumented
48 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
49 return AddSegment ? "__DATA," INSTR_PROF_NAME_SECT_NAME_STR
50 : INSTR_PROF_NAME_SECT_NAME_STR;
53 /// Return the name of the data section containing per-function control
55 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
56 return AddSegment ? "__DATA," INSTR_PROF_DATA_SECT_NAME_STR
57 : INSTR_PROF_DATA_SECT_NAME_STR;
60 /// Return the name profile runtime entry point to do value profiling
62 inline StringRef getInstrProfValueProfFuncName() {
63 return INSTR_PROF_VALUE_PROF_FUNC_STR;
66 /// Return the name of the section containing function coverage mapping
68 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
69 return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
72 /// Return the name prefix of variables containing instrumented function names.
73 inline StringRef getInstrProfNameVarPrefix() { return "__prf_nm_"; }
75 /// Return the name prefix of variables containing per-function control data.
76 inline StringRef getInstrProfDataVarPrefix() { return "__prf_dt_"; }
78 /// Return the name prefix of profile counter variables.
79 inline StringRef getInstrProfCountersVarPrefix() { return "__prf_cn_"; }
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,
135 uint64_t Version = INSTR_PROF_INDEX_VERSION);
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,
144 uint64_t Version = INSTR_PROF_INDEX_VERSION);
146 /// Create and return the global variable for function name used in PGO
147 /// instrumentation. \c FuncName is the name of the function returned
148 /// by \c getPGOFuncName call.
149 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName);
151 /// Create and return the global variable for function name used in PGO
152 /// instrumentation. /// \c FuncName is the name of the function
153 /// returned by \c getPGOFuncName call, \c M is the owning module,
154 /// and \c Linkage is the linkage of the instrumented function.
155 GlobalVariable *createPGOFuncNameVar(Module &M,
156 GlobalValue::LinkageTypes Linkage,
159 const std::error_category &instrprof_category();
161 enum class instrprof_error {
168 unsupported_hash_type,
176 value_site_count_mismatch
179 inline std::error_code make_error_code(instrprof_error E) {
180 return std::error_code(static_cast<int>(E), instrprof_category());
183 enum InstrProfValueKind : uint32_t {
184 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
185 #include "llvm/ProfileData/InstrProfData.inc"
188 struct InstrProfStringTable {
189 // Set of string values in profiling data.
190 StringSet<> StringValueSet;
191 InstrProfStringTable() { StringValueSet.clear(); }
192 // Get a pointer to internal storage of a string in set
193 const char *getStringData(StringRef Str) {
194 auto Result = StringValueSet.find(Str);
195 return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
197 // Insert a string to StringTable
198 const char *insertString(StringRef Str) {
199 auto Result = StringValueSet.insert(Str);
200 return Result.first->first().data();
204 struct InstrProfValueSiteRecord {
205 /// Value profiling data pairs at a given value site.
206 std::list<InstrProfValueData> ValueData;
208 InstrProfValueSiteRecord() { ValueData.clear(); }
209 template <class InputIterator>
210 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
213 /// Sort ValueData ascending by Value
214 void sortByTargetValues() {
216 [](const InstrProfValueData &left, const InstrProfValueData &right) {
217 return left.Value < right.Value;
221 /// Merge data from another InstrProfValueSiteRecord
222 void mergeValueData(InstrProfValueSiteRecord &Input) {
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 I->Count = SaturatingAdd(I->Count, J->Count);
236 ValueData.insert(I, *J);
241 /// Profiling information for a single function.
242 struct InstrProfRecord {
244 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
245 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
248 std::vector<uint64_t> Counts;
250 typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
252 /// Return the number of value profile kinds with non-zero number
253 /// of profile sites.
254 inline uint32_t getNumValueKinds() const;
255 /// Return the number of instrumented sites for ValueKind.
256 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
257 /// Return the total number of ValueData for ValueKind.
258 inline uint32_t getNumValueData(uint32_t ValueKind) const;
259 /// Return the number of value data collected for ValueKind at profiling
261 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
262 uint32_t Site) const;
263 /// Return the array of profiled values at \p Site.
264 inline std::unique_ptr<InstrProfValueData[]>
265 getValueForSite(uint32_t ValueKind, uint32_t Site,
266 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
268 getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind, uint32_t Site,
269 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) 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[]> InstrProfRecord::getValueForSite(
372 uint32_t ValueKind, uint32_t Site,
373 uint64_t (*ValueMapper)(uint32_t, uint64_t)) const {
374 uint32_t N = getNumValueDataForSite(ValueKind, Site);
376 return std::unique_ptr<InstrProfValueData[]>(nullptr);
378 auto VD = llvm::make_unique<InstrProfValueData[]>(N);
379 getValueForSite(VD.get(), ValueKind, Site, ValueMapper);
384 void InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
385 uint32_t ValueKind, uint32_t Site,
386 uint64_t (*ValueMapper)(uint32_t,
389 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
390 Dest[I].Value = ValueMapper ? ValueMapper(ValueKind, V.Value) : V.Value;
391 Dest[I].Count = V.Count;
396 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
397 InstrProfValueData *VData, uint32_t N,
398 ValueMapType *HashKeys) {
399 for (uint32_t I = 0; I < N; I++) {
400 VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
402 std::vector<InstrProfValueSiteRecord> &ValueSites =
403 getValueSitesForKind(ValueKind);
405 ValueSites.push_back(InstrProfValueSiteRecord());
407 ValueSites.emplace_back(VData, VData + N);
410 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
411 std::vector<InstrProfValueSiteRecord> &ValueSites =
412 getValueSitesForKind(ValueKind);
413 ValueSites.reserve(NumValueSites);
416 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
420 Name = StrTab->insertString(Name);
421 for (auto &VSite : IndirectCallSites)
422 for (auto &VData : VSite.ValueData)
423 VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
426 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other) {
427 // If the number of counters doesn't match we either have bad data
428 // or a hash collision.
429 if (Counts.size() != Other.Counts.size())
430 return instrprof_error::count_mismatch;
432 instrprof_error Result = instrprof_error::success;
434 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
435 bool ResultOverflowed;
436 Counts[I] = SaturatingAdd(Counts[I], Other.Counts[I], &ResultOverflowed);
437 if (ResultOverflowed)
438 Result = instrprof_error::counter_overflow;
441 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
442 instrprof_error MergeValueResult = mergeValueProfData(Kind, Other);
443 if (MergeValueResult != instrprof_error::success)
444 Result = MergeValueResult;
450 inline support::endianness getHostEndianness() {
451 return sys::IsLittleEndianHost ? support::little : support::big;
455 // Include definitions for value profile data
456 #define INSTR_PROF_VALUE_PROF_DATA
457 #include "llvm/ProfileData/InstrProfData.inc"
460 * Initialize the record for runtime value profile data.
461 * Return 0 if the initialization is successful, otherwise
464 int initializeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord,
465 const uint16_t *NumValueSites,
466 ValueProfNode **Nodes);
468 /* Release memory allocated for the runtime record. */
469 void finalizeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord);
471 /* Return the size of ValueProfData structure that can be used to store
472 the value profile data collected at runtime. */
473 uint32_t getValueProfDataSizeRT(const ValueProfRuntimeRecord *Record);
475 /* Return a ValueProfData instance that stores the data collected at runtime. */
477 serializeValueProfDataFromRT(const ValueProfRuntimeRecord *Record,
480 namespace IndexedInstrProf {
482 enum class HashT : uint32_t {
488 static inline uint64_t MD5Hash(StringRef Str) {
491 llvm::MD5::MD5Result Result;
493 // Return the least significant 8 bytes. Our MD5 implementation returns the
494 // result in little endian, so we may need to swap bytes.
495 using namespace llvm::support;
496 return endian::read<uint64_t, little, unaligned>(Result);
499 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
502 return IndexedInstrProf::MD5Hash(K);
504 llvm_unreachable("Unhandled hash type");
507 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
508 const uint64_t Version = INSTR_PROF_INDEX_VERSION;
509 const HashT HashType = HashT::MD5;
511 // This structure defines the file header of the LLVM profile
512 // data file in indexed-format.
516 uint64_t MaxFunctionCount;
521 } // end namespace IndexedInstrProf
523 namespace RawInstrProf {
525 const uint64_t Version = INSTR_PROF_RAW_VERSION;
527 template <class IntPtrT> inline uint64_t getMagic();
528 template <> inline uint64_t getMagic<uint64_t>() {
529 return INSTR_PROF_RAW_MAGIC_64;
532 template <> inline uint64_t getMagic<uint32_t>() {
533 return INSTR_PROF_RAW_MAGIC_32;
536 // Per-function profile data header/control structure.
537 // The definition should match the structure defined in
538 // compiler-rt/lib/profile/InstrProfiling.h.
539 // It should also match the synthesized type in
540 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
541 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
542 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
543 #include "llvm/ProfileData/InstrProfData.inc"
546 // File header structure of the LLVM profile data in raw format.
547 // The definition should match the header referenced in
548 // compiler-rt/lib/profile/InstrProfilingFile.c and
549 // InstrProfilingBuffer.c.
551 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
552 #include "llvm/ProfileData/InstrProfData.inc"
555 } // end namespace RawInstrProf
559 // Profile coverage map has the following layout:
560 // [CoverageMapFileHeader]
562 // [CovMapFunctionRecord]
563 // [CovMapFunctionRecord]
566 // [Encoded Region Mapping Data]
568 template <class IntPtrT> struct CovMapFunctionRecord {
569 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
570 #include "llvm/ProfileData/InstrProfData.inc"
576 } // end namespace llvm
580 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
583 #endif // LLVM_PROFILEDATA_INSTRPROF_H_