[PGO] Move value profile format related structures and APIs to common file
[oota-llvm.git] / include / llvm / ProfileData / InstrProf.h
1 //=-- InstrProf.h - Instrumented profiling format support ---------*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_PROFILEDATA_INSTRPROF_H_
17 #define LLVM_PROFILEDATA_INSTRPROF_H_
18
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"
28 #include <cstdint>
29 #include <list>
30 #include <system_error>
31 #include <vector>
32
33 namespace llvm {
34
35 class Function;
36 class GlobalVariable;
37 class Module;
38
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;
43 }
44
45 /// Return the name of data section containing names of instrumented
46 /// functions.
47 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
48   return AddSegment ? "__DATA," INSTR_PROF_NAME_SECT_NAME_STR
49                     : INSTR_PROF_NAME_SECT_NAME_STR;
50 }
51
52 /// Return the name of the data section containing per-function control
53 /// data.
54 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
55   return AddSegment ? "__DATA," INSTR_PROF_DATA_SECT_NAME_STR
56                     : INSTR_PROF_DATA_SECT_NAME_STR;
57 }
58
59 /// Return the name profile runtime entry point to do value profiling
60 /// for a given site.
61 inline StringRef getInstrProfValueProfFuncName() {
62   return INSTR_PROF_VALUE_PROF_FUNC_STR;
63 }
64
65 /// Return the name of the section containing function coverage mapping
66 /// data.
67 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
68   return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
69 }
70
71 /// Return the name prefix of variables containing instrumented function names.
72 inline StringRef getInstrProfNameVarPrefix() { return "__llvm_profile_name_"; }
73
74 /// Return the name prefix of variables containing per-function control data.
75 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
76
77 /// Return the name prefix of profile counter variables.
78 inline StringRef getInstrProfCountersVarPrefix() {
79   return "__llvm_profile_counters_";
80 }
81
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_"; }
85
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";
91 }
92
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";
100 }
101
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";
106 }
107
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"; }
113
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";
119 }
120
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";
125 }
126
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";
131 }
132
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);
136
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,
143                            StringRef FileName);
144
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);
149
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,
156                                      StringRef FuncName);
157
158 const std::error_category &instrprof_category();
159
160 enum class instrprof_error {
161   success = 0,
162   eof,
163   unrecognized_format,
164   bad_magic,
165   bad_header,
166   unsupported_version,
167   unsupported_hash_type,
168   too_large,
169   truncated,
170   malformed,
171   unknown_function,
172   hash_mismatch,
173   count_mismatch,
174   counter_overflow,
175   value_site_count_mismatch
176 };
177
178 inline std::error_code make_error_code(instrprof_error E) {
179   return std::error_code(static_cast<int>(E), instrprof_category());
180 }
181
182 enum InstrProfValueKind : uint32_t {
183 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
184 #include "llvm/ProfileData/InstrProfData.inc"
185 };
186
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();
195   }
196   // Insert a string to StringTable
197   const char *insertString(StringRef Str) {
198     auto Result = StringValueSet.insert(Str);
199     return Result.first->first().data();
200   }
201 };
202
203 struct InstrProfValueSiteRecord {
204   /// Value profiling data pairs at a given value site.
205   std::list<InstrProfValueData> ValueData;
206
207   InstrProfValueSiteRecord() { ValueData.clear(); }
208   template <class InputIterator>
209   InstrProfValueSiteRecord(InputIterator F, InputIterator L)
210       : ValueData(F, L) {}
211
212   /// Sort ValueData ascending by Value
213   void sortByTargetValues() {
214     ValueData.sort(
215         [](const InstrProfValueData &left, const InstrProfValueData &right) {
216           return left.Value < right.Value;
217         });
218   }
219
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;
227          ++J) {
228       while (I != IE && I->Value < J->Value)
229         ++I;
230       if (I != IE && I->Value == J->Value) {
231         I->Count = SaturatingAdd(I->Count, J->Count);
232         ++I;
233         continue;
234       }
235       ValueData.insert(I, *J);
236     }
237   }
238 };
239
240 /// Profiling information for a single function.
241 struct InstrProfRecord {
242   InstrProfRecord() {}
243   InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
244       : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
245   StringRef Name;
246   uint64_t Hash;
247   std::vector<uint64_t> Counts;
248
249   typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
250
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
259   /// site: Site.
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,
265                   uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
266   inline void
267   getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind, uint32_t Site,
268                   uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
269   /// Reserve space for NumValueSites sites.
270   inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
271   /// Add ValueData for ValueKind at value Site.
272   inline void addValueData(uint32_t ValueKind, uint32_t Site,
273                            InstrProfValueData *VData, uint32_t N,
274                            ValueMapType *HashKeys);
275
276   /// Merge the counts in \p Other into this one.
277   inline instrprof_error merge(InstrProfRecord &Other);
278
279   /// Used by InstrProfWriter: update the value strings to commoned strings in
280   /// the writer instance.
281   inline void updateStrings(InstrProfStringTable *StrTab);
282
283   /// Clear value data entries
284   inline void clearValueData() {
285     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
286       getValueSitesForKind(Kind).clear();
287   }
288
289 private:
290   std::vector<InstrProfValueSiteRecord> IndirectCallSites;
291   const std::vector<InstrProfValueSiteRecord> &
292   getValueSitesForKind(uint32_t ValueKind) const {
293     switch (ValueKind) {
294     case IPVK_IndirectCallTarget:
295       return IndirectCallSites;
296     default:
297       llvm_unreachable("Unknown value kind!");
298     }
299     return IndirectCallSites;
300   }
301
302   std::vector<InstrProfValueSiteRecord> &
303   getValueSitesForKind(uint32_t ValueKind) {
304     return const_cast<std::vector<InstrProfValueSiteRecord> &>(
305         const_cast<const InstrProfRecord *>(this)
306             ->getValueSitesForKind(ValueKind));
307   }
308
309   // Map indirect call target name hash to name string.
310   uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
311                       ValueMapType *HashKeys) {
312     if (!HashKeys)
313       return Value;
314     switch (ValueKind) {
315     case IPVK_IndirectCallTarget: {
316       auto Result =
317           std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
318                            [](const std::pair<uint64_t, const char *> &LHS,
319                               uint64_t RHS) { return LHS.first < RHS; });
320       if (Result != HashKeys->end())
321         Value = (uint64_t)Result->second;
322       break;
323     }
324     }
325     return Value;
326   }
327
328   // Merge Value Profile data from Src record to this record for ValueKind.
329   instrprof_error mergeValueProfData(uint32_t ValueKind, InstrProfRecord &Src) {
330     uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
331     uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
332     if (ThisNumValueSites != OtherNumValueSites)
333       return instrprof_error::value_site_count_mismatch;
334     std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
335         getValueSitesForKind(ValueKind);
336     std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
337         Src.getValueSitesForKind(ValueKind);
338     for (uint32_t I = 0; I < ThisNumValueSites; I++)
339       ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I]);
340     return instrprof_error::success;
341   }
342 };
343
344 uint32_t InstrProfRecord::getNumValueKinds() const {
345   uint32_t NumValueKinds = 0;
346   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
347     NumValueKinds += !(getValueSitesForKind(Kind).empty());
348   return NumValueKinds;
349 }
350
351 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
352   uint32_t N = 0;
353   const std::vector<InstrProfValueSiteRecord> &SiteRecords =
354       getValueSitesForKind(ValueKind);
355   for (auto &SR : SiteRecords) {
356     N += SR.ValueData.size();
357   }
358   return N;
359 }
360
361 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
362   return getValueSitesForKind(ValueKind).size();
363 }
364
365 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
366                                                  uint32_t Site) const {
367   return getValueSitesForKind(ValueKind)[Site].ValueData.size();
368 }
369
370 std::unique_ptr<InstrProfValueData[]> InstrProfRecord::getValueForSite(
371     uint32_t ValueKind, uint32_t Site,
372     uint64_t (*ValueMapper)(uint32_t, uint64_t)) const {
373   uint32_t N = getNumValueDataForSite(ValueKind, Site);
374   if (N == 0)
375     return std::unique_ptr<InstrProfValueData[]>(nullptr);
376
377   auto VD = llvm::make_unique<InstrProfValueData[]>(N);
378   getValueForSite(VD.get(), ValueKind, Site, ValueMapper);
379
380   return VD;
381 }
382
383 void InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
384                                       uint32_t ValueKind, uint32_t Site,
385                                       uint64_t (*ValueMapper)(uint32_t,
386                                                               uint64_t)) const {
387   uint32_t I = 0;
388   for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
389     Dest[I].Value = ValueMapper ? ValueMapper(ValueKind, V.Value) : V.Value;
390     Dest[I].Count = V.Count;
391     I++;
392   }
393 }
394
395 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
396                                    InstrProfValueData *VData, uint32_t N,
397                                    ValueMapType *HashKeys) {
398   for (uint32_t I = 0; I < N; I++) {
399     VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
400   }
401   std::vector<InstrProfValueSiteRecord> &ValueSites =
402       getValueSitesForKind(ValueKind);
403   if (N == 0)
404     ValueSites.push_back(InstrProfValueSiteRecord());
405   else
406     ValueSites.emplace_back(VData, VData + N);
407 }
408
409 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
410   std::vector<InstrProfValueSiteRecord> &ValueSites =
411       getValueSitesForKind(ValueKind);
412   ValueSites.reserve(NumValueSites);
413 }
414
415 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
416   if (!StrTab)
417     return;
418
419   Name = StrTab->insertString(Name);
420   for (auto &VSite : IndirectCallSites)
421     for (auto &VData : VSite.ValueData)
422       VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
423 }
424
425 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other) {
426   // If the number of counters doesn't match we either have bad data
427   // or a hash collision.
428   if (Counts.size() != Other.Counts.size())
429     return instrprof_error::count_mismatch;
430
431   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
432     if (Counts[I] + Other.Counts[I] < Counts[I])
433       return instrprof_error::counter_overflow;
434     Counts[I] += Other.Counts[I];
435   }
436
437   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
438     instrprof_error result = mergeValueProfData(Kind, Other);
439     if (result != instrprof_error::success)
440       return result;
441   }
442
443   return instrprof_error::success;
444 }
445
446 inline support::endianness getHostEndianness() {
447   return sys::IsLittleEndianHost ? support::little : support::big;
448 }
449
450
451 // Include definitions for value profile data
452 #define INSTR_PROF_VALUE_PROF_DATA
453 #include "llvm/ProfileData/InstrProfData.inc"
454
455  /*
456  * Initialize the record for runtime value profile data. 
457  * Return 0 if the initialization is successful, otherwise
458  * return 1.
459  */
460 int initializeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord,
461                                      uint16_t *NumValueSites,
462                                      ValueProfNode **Nodes);
463
464 /* Release memory allocated for the runtime record.  */
465 void finalizeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord);
466
467 /* Return the size of ValueProfData structure that can be used to store
468    the value profile data collected at runtime. */
469 uint32_t getValueProfDataSizeRT(const ValueProfRuntimeRecord *Record);
470
471 /* Return a ValueProfData instance that stores the data collected at runtime. */
472 ValueProfData *
473 serializeValueProfDataFromRT(const ValueProfRuntimeRecord *Record,
474                              ValueProfData *Dst);
475
476 namespace IndexedInstrProf {
477
478 enum class HashT : uint32_t {
479   MD5,
480
481   Last = MD5
482 };
483
484 static inline uint64_t MD5Hash(StringRef Str) {
485   MD5 Hash;
486   Hash.update(Str);
487   llvm::MD5::MD5Result Result;
488   Hash.final(Result);
489   // Return the least significant 8 bytes. Our MD5 implementation returns the
490   // result in little endian, so we may need to swap bytes.
491   using namespace llvm::support;
492   return endian::read<uint64_t, little, unaligned>(Result);
493 }
494
495 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
496   switch (Type) {
497   case HashT::MD5:
498     return IndexedInstrProf::MD5Hash(K);
499   }
500   llvm_unreachable("Unhandled hash type");
501 }
502
503 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
504 const uint64_t Version = 3;
505 const HashT HashType = HashT::MD5;
506
507 // This structure defines the file header of the LLVM profile
508 // data file in indexed-format.
509 struct Header {
510   uint64_t Magic;
511   uint64_t Version;
512   uint64_t MaxFunctionCount;
513   uint64_t HashType;
514   uint64_t HashOffset;
515 };
516
517 } // end namespace IndexedInstrProf
518
519 namespace RawInstrProf {
520
521 const uint64_t Version = INSTR_PROF_RAW_VERSION;
522
523 template <class IntPtrT> inline uint64_t getMagic();
524 template <> inline uint64_t getMagic<uint64_t>() {
525   return INSTR_PROF_RAW_MAGIC_64;
526 }
527
528 template <> inline uint64_t getMagic<uint32_t>() {
529   return INSTR_PROF_RAW_MAGIC_32;
530 }
531
532 // Per-function profile data header/control structure.
533 // The definition should match the structure defined in
534 // compiler-rt/lib/profile/InstrProfiling.h.
535 // It should also match the synthesized type in
536 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
537 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
538   #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
539   #include "llvm/ProfileData/InstrProfData.inc"
540 };
541
542 // File header structure of the LLVM profile data in raw format.
543 // The definition should match the header referenced in
544 // compiler-rt/lib/profile/InstrProfilingFile.c  and
545 // InstrProfilingBuffer.c.
546 struct Header {
547 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
548 #include "llvm/ProfileData/InstrProfData.inc"
549 };
550
551 }  // end namespace RawInstrProf
552
553 namespace coverage {
554
555 // Profile coverage map has the following layout:
556 // [CoverageMapFileHeader]
557 // [ArrayStart]
558 //  [CovMapFunctionRecord]
559 //  [CovMapFunctionRecord]
560 //  ...
561 // [ArrayEnd]
562 // [Encoded Region Mapping Data]
563 LLVM_PACKED_START
564 template <class IntPtrT> struct CovMapFunctionRecord {
565   #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
566   #include "llvm/ProfileData/InstrProfData.inc"
567 };
568 LLVM_PACKED_END
569
570 }
571
572 } // end namespace llvm
573
574 namespace std {
575 template <>
576 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
577 }
578
579 #endif // LLVM_PROFILEDATA_INSTRPROF_H_