59baf30d7b3c4c24b98f57d121feed2ba8de7cd9
[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/Support/Endian.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MD5.h"
24 #include <cstdint>
25 #include <list>
26 #include <system_error>
27 #include <vector>
28
29 namespace llvm {
30
31 /// Return the name of data section containing profile counter variables.
32 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
33   return AddSegment ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
34 }
35
36 /// Return the name of data section containing names of instrumented
37 /// functions.
38 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
39   return AddSegment ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
40 }
41
42 /// Return the name of the data section containing per-function control
43 /// data.
44 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
45   return AddSegment ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
46 }
47
48 /// Return the name of the section containing function coverage mapping
49 /// data.
50 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
51   return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
52 }
53
54 /// Return the name prefix of variables containing instrumented function names.
55 inline StringRef getInstrProfNameVarPrefix() { return "__llvm_profile_name_"; }
56
57 /// Return the name prefix of variables containing per-function control data.
58 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
59
60 /// Return the name prefix of profile counter variables.
61 inline StringRef getInstrProfCountersVarPrefix() {
62   return "__llvm_profile_counters_";
63 }
64
65 /// Return the name prefix of the COMDAT group for instrumentation variables
66 /// associated with a COMDAT function.
67 inline StringRef getInstrProfComdatPrefix() { return "__llvm_profile_vars_"; }
68
69 /// Return the name of a covarage mapping variable (internal linkage) 
70 /// for each instrumented source module. Such variables are allocated
71 /// in the __llvm_covmap section.
72 inline StringRef getCoverageMappingVarName() {
73   return "__llvm_coverage_mapping";
74 }
75
76 /// Return the name of function that registers all the per-function control
77 /// data at program startup time by calling __llvm_register_function. This
78 /// function has internal linkage and is called by  __llvm_profile_init
79 /// runtime method. This function is not generated for these platforms:
80 /// Darwin, Linux, and FreeBSD.
81 inline StringRef getInstrProfRegFuncsName() {
82   return "__llvm_profile_register_functions";
83 }
84
85 /// Return the name of the runtime interface that registers per-function control
86 /// data for one instrumented function.
87 inline StringRef getInstrProfRegFuncName() {
88   return "__llvm_profile_register_function";
89 }
90
91 /// Return the name of the runtime initialization method that is generated by
92 /// the compiler. The function calls __llvm_profile_register_functions and
93 /// __llvm_profile_override_default_filename functions if needed. This function
94 /// has internal linkage and invoked at startup time via init_array.
95 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
96
97 /// Return the name of the hook variable defined in profile runtime library.
98 /// A reference to the variable causes the linker to link in the runtime
99 /// initialization module (which defines the hook variable).
100 inline StringRef getInstrProfRuntimeHookVarName() {
101   return "__llvm_profile_runtime";
102 }
103
104 /// Return the name of the compiler generated function that references the
105 /// runtime hook variable. The function is a weak global.
106 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
107   return "__llvm_profile_runtime_user";
108 }
109
110 /// Return the name of the profile runtime interface that overrides the default
111 /// profile data file name.
112 inline StringRef getInstrProfFileOverriderFuncName() {
113   return "__llvm_profile_override_default_filename";
114 }
115
116 const std::error_category &instrprof_category();
117
118 enum class instrprof_error {
119   success = 0,
120   eof,
121   bad_magic,
122   bad_header,
123   unsupported_version,
124   unsupported_hash_type,
125   too_large,
126   truncated,
127   malformed,
128   unknown_function,
129   hash_mismatch,
130   count_mismatch,
131   counter_overflow,
132   value_site_count_mismatch
133 };
134
135 inline std::error_code make_error_code(instrprof_error E) {
136   return std::error_code(static_cast<int>(E), instrprof_category());
137 }
138
139 enum InstrProfValueKind : uint32_t {
140   IPVK_IndirectCallTarget = 0,
141
142   IPVK_First = IPVK_IndirectCallTarget,
143   IPVK_Last = IPVK_IndirectCallTarget
144 };
145
146 struct InstrProfStringTable {
147   // Set of string values in profiling data.
148   StringSet<> StringValueSet;
149   InstrProfStringTable() { StringValueSet.clear(); }
150   // Get a pointer to internal storage of a string in set
151   const char *getStringData(StringRef Str) {
152     auto Result = StringValueSet.find(Str);
153     return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
154   }
155   // Insert a string to StringTable
156   const char *insertString(StringRef Str) {
157     auto Result = StringValueSet.insert(Str);
158     return Result.first->first().data();
159   }
160 };
161
162 struct InstrProfValueData {
163   // Profiled value.
164   uint64_t Value;
165   // Number of times the value appears in the training run.
166   uint64_t Count;
167 };
168
169 struct InstrProfValueSiteRecord {
170   /// Value profiling data pairs at a given value site.
171   std::list<InstrProfValueData> ValueData;
172
173   InstrProfValueSiteRecord() { ValueData.clear(); }
174   template <class InputIterator>
175   InstrProfValueSiteRecord(InputIterator F, InputIterator L)
176       : ValueData(F, L) {}
177
178   /// Sort ValueData ascending by Value
179   void sortByTargetValues() {
180     ValueData.sort(
181         [](const InstrProfValueData &left, const InstrProfValueData &right) {
182           return left.Value < right.Value;
183         });
184   }
185
186   /// Merge data from another InstrProfValueSiteRecord
187   void mergeValueData(InstrProfValueSiteRecord &Input) {
188     this->sortByTargetValues();
189     Input.sortByTargetValues();
190     auto I = ValueData.begin();
191     auto IE = ValueData.end();
192     for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
193          ++J) {
194       while (I != IE && I->Value < J->Value)
195         ++I;
196       if (I != IE && I->Value == J->Value) {
197         I->Count += J->Count;
198         ++I;
199         continue;
200       }
201       ValueData.insert(I, *J);
202     }
203   }
204 };
205
206 /// Profiling information for a single function.
207 struct InstrProfRecord {
208   InstrProfRecord() {}
209   InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
210       : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
211   StringRef Name;
212   uint64_t Hash;
213   std::vector<uint64_t> Counts;
214
215   typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
216
217   /// Return the number of value profile kinds with non-zero number
218   /// of profile sites.
219   inline uint32_t getNumValueKinds() const;
220   /// Return the number of instrumented sites for ValueKind.
221   inline uint32_t getNumValueSites(uint32_t ValueKind) const;
222   /// Return the total number of ValueData for ValueKind.
223   inline uint32_t getNumValueData(uint32_t ValueKind) const;
224   /// Return the number of value data collected for ValueKind at profiling
225   /// site: Site.
226   inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
227                                          uint32_t Site) const;
228   inline std::unique_ptr<InstrProfValueData[]>
229   getValueForSite(uint32_t ValueKind, uint32_t Site) const;
230   /// Reserve space for NumValueSites sites.
231   inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
232   /// Add ValueData for ValueKind at value Site.
233   inline void addValueData(uint32_t ValueKind, uint32_t Site,
234                            InstrProfValueData *VData, uint32_t N,
235                            ValueMapType *HashKeys);
236   /// Merge Value Profile ddata from Src record to this record for ValueKind.
237   inline instrprof_error mergeValueProfData(uint32_t ValueKind,
238                                             InstrProfRecord &Src);
239
240   /// Used by InstrProfWriter: update the value strings to commoned strings in
241   /// the writer instance.
242   inline void updateStrings(InstrProfStringTable *StrTab);
243
244 private:
245   std::vector<InstrProfValueSiteRecord> IndirectCallSites;
246   const std::vector<InstrProfValueSiteRecord> &
247   getValueSitesForKind(uint32_t ValueKind) const {
248     switch (ValueKind) {
249     case IPVK_IndirectCallTarget:
250       return IndirectCallSites;
251     default:
252       llvm_unreachable("Unknown value kind!");
253     }
254     return IndirectCallSites;
255   }
256
257   std::vector<InstrProfValueSiteRecord> &
258   getValueSitesForKind(uint32_t ValueKind) {
259     return const_cast<std::vector<InstrProfValueSiteRecord> &>(
260         const_cast<const InstrProfRecord *>(this)
261             ->getValueSitesForKind(ValueKind));
262   }
263   // Map indirect call target name hash to name string.
264   uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
265                       ValueMapType *HashKeys) {
266     if (!HashKeys)
267       return Value;
268     switch (ValueKind) {
269     case IPVK_IndirectCallTarget: {
270       auto Result =
271           std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
272                            [](const std::pair<uint64_t, const char *> &LHS,
273                               uint64_t RHS) { return LHS.first < RHS; });
274       assert(Result != HashKeys->end() &&
275              "Hash does not match any known keys\n");
276       Value = (uint64_t)Result->second;
277       break;
278     }
279     }
280     return Value;
281   }
282 };
283
284 uint32_t InstrProfRecord::getNumValueKinds() const {
285   uint32_t NumValueKinds = 0;
286   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
287     NumValueKinds += !(getValueSitesForKind(Kind).empty());
288   return NumValueKinds;
289 }
290
291 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
292   return getValueSitesForKind(ValueKind).size();
293 }
294
295 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
296                                                  uint32_t Site) const {
297   return getValueSitesForKind(ValueKind)[Site].ValueData.size();
298 }
299
300 std::unique_ptr<InstrProfValueData[]>
301 InstrProfRecord::getValueForSite(uint32_t ValueKind, uint32_t Site) const {
302   uint32_t N = getNumValueDataForSite(ValueKind, Site);
303   if (N == 0)
304     return std::unique_ptr<InstrProfValueData[]>(nullptr);
305
306   std::unique_ptr<InstrProfValueData[]> VD(new InstrProfValueData[N]);
307   uint32_t I = 0;
308   for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
309     VD[I] = V;
310     I++;
311   }
312   assert(I == N);
313
314   return VD;
315 }
316
317 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
318                                    InstrProfValueData *VData, uint32_t N,
319                                    ValueMapType *HashKeys) {
320   for (uint32_t I = 0; I < N; I++) {
321     VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
322   }
323   std::vector<InstrProfValueSiteRecord> &ValueSites =
324       getValueSitesForKind(ValueKind);
325   if (N == 0)
326     ValueSites.push_back(InstrProfValueSiteRecord());
327   else
328     ValueSites.emplace_back(VData, VData + N);
329 }
330
331 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
332   std::vector<InstrProfValueSiteRecord> &ValueSites =
333       getValueSitesForKind(ValueKind);
334   ValueSites.reserve(NumValueSites);
335 }
336
337 instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
338                                                     InstrProfRecord &Src) {
339   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
340   uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
341   if (ThisNumValueSites != OtherNumValueSites)
342     return instrprof_error::value_site_count_mismatch;
343   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
344       getValueSitesForKind(ValueKind);
345   std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
346       Src.getValueSitesForKind(ValueKind);
347   for (uint32_t I = 0; I < ThisNumValueSites; I++)
348     ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I]);
349   return instrprof_error::success;
350 }
351
352 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
353   if (!StrTab)
354     return;
355
356   Name = StrTab->insertString(Name);
357   for (auto &VSite : IndirectCallSites)
358     for (auto &VData : VSite.ValueData)
359       VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
360 }
361
362 namespace IndexedInstrProf {
363 enum class HashT : uint32_t {
364   MD5,
365
366   Last = MD5
367 };
368
369 static inline uint64_t MD5Hash(StringRef Str) {
370   MD5 Hash;
371   Hash.update(Str);
372   llvm::MD5::MD5Result Result;
373   Hash.final(Result);
374   // Return the least significant 8 bytes. Our MD5 implementation returns the
375   // result in little endian, so we may need to swap bytes.
376   using namespace llvm::support;
377   return endian::read<uint64_t, little, unaligned>(Result);
378 }
379
380 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
381   switch (Type) {
382     case HashT::MD5:
383       return IndexedInstrProf::MD5Hash(K);
384   }
385   llvm_unreachable("Unhandled hash type");
386 }
387
388 const uint64_t Magic = 0x8169666f72706cff;  // "\xfflprofi\x81"
389 const uint64_t Version = 3;
390 const HashT HashType = HashT::MD5;
391
392 struct Header {
393   uint64_t Magic;
394   uint64_t Version;
395   uint64_t MaxFunctionCount;
396   uint64_t HashType;
397   uint64_t HashOffset;
398 };
399
400 }  // end namespace IndexedInstrProf
401
402 namespace RawInstrProf {
403
404 const uint64_t Version = 1;
405
406 // Magic number to detect file format and endianness.
407 // Use 255 at one end, since no UTF-8 file can use that character.  Avoid 0,
408 // so that utilities, like strings, don't grab it as a string.  129 is also
409 // invalid UTF-8, and high enough to be interesting.
410 // Use "lprofr" in the centre to stand for "LLVM Profile Raw", or "lprofR"
411 // for 32-bit platforms.
412 // The magic and version need to be kept in sync with
413 // projects/compiler-rt/lib/profile/InstrProfiling.c
414
415 template <class IntPtrT>
416 inline uint64_t getMagic();
417 template <>
418 inline uint64_t getMagic<uint64_t>() {
419   return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
420          uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
421          uint64_t('r') << 8 | uint64_t(129);
422 }
423
424 template <>
425 inline uint64_t getMagic<uint32_t>() {
426   return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
427          uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
428          uint64_t('R') << 8 | uint64_t(129);
429 }
430
431 // The definition should match the structure defined in
432 // compiler-rt/lib/profile/InstrProfiling.h.
433 // It should also match the synthesized type in
434 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
435
436 template <class IntPtrT> struct ProfileData {
437   #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
438   #include "llvm/ProfileData/InstrProfData.inc"
439 };
440
441 // The definition should match the header referenced in
442 // compiler-rt/lib/profile/InstrProfilingFile.c  and
443 // InstrProfilingBuffer.c.
444
445 struct Header {
446   const uint64_t Magic;
447   const uint64_t Version;
448   const uint64_t DataSize;
449   const uint64_t CountersSize;
450   const uint64_t NamesSize;
451   const uint64_t CountersDelta;
452   const uint64_t NamesDelta;
453 };
454
455 }  // end namespace RawInstrProf
456
457 namespace coverage {
458
459 LLVM_PACKED_START
460 template <class IntPtrT> struct CovMapFunctionRecord {
461   #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
462   #include "llvm/ProfileData/InstrProfData.inc"
463 };
464 LLVM_PACKED_END
465
466 }
467
468 } // end namespace llvm
469
470 namespace std {
471 template <>
472 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
473 }
474
475 #endif // LLVM_PROFILEDATA_INSTRPROF_H_