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