Debian Codegraph @

suite/synctools/tablegen/include/llvm/ProfileData/InstrProf.h

raw symbols SCIP
1 //===- InstrProf.h - Instrumented profiling format support ------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Instrumentation-based profiling data is generated by instrumented
10 // binaries through library functions in compiler-rt, and read by the clang
11 // frontend to feed PGO.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_PROFILEDATA_INSTRPROF_H
16 #define LLVM_PROFILEDATA_INSTRPROF_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitmaskEnum.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/StringSet.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/IR/GlobalValue.h"
25 #include "llvm/IR/ProfileSummary.h"
26 #include "llvm/ProfileData/InstrProfData.inc"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/Endian.h"
30 #include "llvm/Support/Error.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/MD5.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <cassert>
38 #include <cstddef>
39 #include <cstdint>
40 #include <cstring>
41 #include <list>
42 #include <memory>
43 #include <string>
44 #include <system_error>
45 #include <utility>
46 #include <vector>
47
48 namespace llvm {
49
50 class Function;
51 class GlobalVariable;
52 struct InstrProfRecord;
53 class InstrProfSymtab;
54 class Instruction;
55 class MDNode;
56 class Module;
57
58 enum InstrProfSectKind {
59 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind,
60 #include "llvm/ProfileData/InstrProfData.inc"
61 };
62
63 /// Return the name of the profile section corresponding to \p IPSK.
64 ///
65 /// The name of the section depends on the object format type \p OF. If
66 /// \p AddSegmentInfo is true, a segment prefix and additional linker hints may
67 /// be added to the section name (this is the default).
68 std::string getInstrProfSectionName(InstrProfSectKind IPSK,
69 Triple::ObjectFormatType OF,
70 bool AddSegmentInfo = true);
71
72 /// Return the name profile runtime entry point to do value profiling
73 /// for a given site.
74 inline StringRef getInstrProfValueProfFuncName() {
75 return INSTR_PROF_VALUE_PROF_FUNC_STR;
76 }
77
78 /// Return the name profile runtime entry point to do memop size value
79 /// profiling.
80 inline StringRef getInstrProfValueProfMemOpFuncName() {
81 return INSTR_PROF_VALUE_PROF_MEMOP_FUNC_STR;
82 }
83
84 /// Return the name prefix of variables containing instrumented function names.
85 inline StringRef getInstrProfNameVarPrefix() { return "__profn_"; }
86
87 /// Return the name prefix of variables containing per-function control data.
88 inline StringRef getInstrProfDataVarPrefix() { return "__profd_"; }
89
90 /// Return the name prefix of profile counter variables.
91 inline StringRef getInstrProfCountersVarPrefix() { return "__profc_"; }
92
93 /// Return the name prefix of value profile variables.
94 inline StringRef getInstrProfValuesVarPrefix() { return "__profvp_"; }
95
96 /// Return the name of value profile node array variables:
97 inline StringRef getInstrProfVNodesVarName() { return "__llvm_prf_vnodes"; }
98
99 /// Return the name of the variable holding the strings (possibly compressed)
100 /// of all function's PGO names.
101 inline StringRef getInstrProfNamesVarName() {
102 return "__llvm_prf_nm";
103 }
104
105 /// Return the name of a covarage mapping variable (internal linkage)
106 /// for each instrumented source module. Such variables are allocated
107 /// in the __llvm_covmap section.
108 inline StringRef getCoverageMappingVarName() {
109 return "__llvm_coverage_mapping";
110 }
111
112 /// Return the name of the internal variable recording the array
113 /// of PGO name vars referenced by the coverage mapping. The owning
114 /// functions of those names are not emitted by FE (e.g, unused inline
115 /// functions.)
116 inline StringRef getCoverageUnusedNamesVarName() {
117 return "__llvm_coverage_names";
118 }
119
120 /// Return the name of function that registers all the per-function control
121 /// data at program startup time by calling __llvm_register_function. This
122 /// function has internal linkage and is called by __llvm_profile_init
123 /// runtime method. This function is not generated for these platforms:
124 /// Darwin, Linux, and FreeBSD.
125 inline StringRef getInstrProfRegFuncsName() {
126 return "__llvm_profile_register_functions";
127 }
128
129 /// Return the name of the runtime interface that registers per-function control
130 /// data for one instrumented function.
131 inline StringRef getInstrProfRegFuncName() {
132 return "__llvm_profile_register_function";
133 }
134
135 /// Return the name of the runtime interface that registers the PGO name strings.
136 inline StringRef getInstrProfNamesRegFuncName() {
137 return "__llvm_profile_register_names_function";
138 }
139
140 /// Return the name of the runtime initialization method that is generated by
141 /// the compiler. The function calls __llvm_profile_register_functions and
142 /// __llvm_profile_override_default_filename functions if needed. This function
143 /// has internal linkage and invoked at startup time via init_array.
144 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
145
146 /// Return the name of the hook variable defined in profile runtime library.
147 /// A reference to the variable causes the linker to link in the runtime
148 /// initialization module (which defines the hook variable).
149 inline StringRef getInstrProfRuntimeHookVarName() {
150 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_RUNTIME_VAR);
151 }
152
153 /// Return the name of the compiler generated function that references the
154 /// runtime hook variable. The function is a weak global.
155 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
156 return "__llvm_profile_runtime_user";
157 }
158
159 inline StringRef getInstrProfCounterBiasVarName() {
160 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_COUNTER_BIAS_VAR);
161 }
162
163 /// Return the marker used to separate PGO names during serialization.
164 inline StringRef getInstrProfNameSeparator() { return "\01"; }
165
166 /// Return the modified name for function \c F suitable to be
167 /// used the key for profile lookup. Variable \c InLTO indicates if this
168 /// is called in LTO optimization passes.
169 std::string getPGOFuncName(const Function &F, bool InLTO = false,
170 uint64_t Version = INSTR_PROF_INDEX_VERSION);
171
172 /// Return the modified name for a function suitable to be
173 /// used the key for profile lookup. The function's original
174 /// name is \c RawFuncName and has linkage of type \c Linkage.
175 /// The function is defined in module \c FileName.
176 std::string getPGOFuncName(StringRef RawFuncName,
177 GlobalValue::LinkageTypes Linkage,
178 StringRef FileName,
179 uint64_t Version = INSTR_PROF_INDEX_VERSION);
180
181 /// Return the name of the global variable used to store a function
182 /// name in PGO instrumentation. \c FuncName is the name of the function
183 /// returned by the \c getPGOFuncName call.
184 std::string getPGOFuncNameVarName(StringRef FuncName,
185 GlobalValue::LinkageTypes Linkage);
186
187 /// Create and return the global variable for function name used in PGO
188 /// instrumentation. \c FuncName is the name of the function returned
189 /// by \c getPGOFuncName call.
190 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName);
191
192 /// Create and return the global variable for function name used in PGO
193 /// instrumentation. /// \c FuncName is the name of the function
194 /// returned by \c getPGOFuncName call, \c M is the owning module,
195 /// and \c Linkage is the linkage of the instrumented function.
196 GlobalVariable *createPGOFuncNameVar(Module &M,
197 GlobalValue::LinkageTypes Linkage,
198 StringRef PGOFuncName);
199
200 /// Return the initializer in string of the PGO name var \c NameVar.
201 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar);
202
203 /// Given a PGO function name, remove the filename prefix and return
204 /// the original (static) function name.
205 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName,
206 StringRef FileName = "<unknown>");
207
208 /// Given a vector of strings (function PGO names) \c NameStrs, the
209 /// method generates a combined string \c Result that is ready to be
210 /// serialized. The \c Result string is comprised of three fields:
211 /// The first field is the length of the uncompressed strings, and the
212 /// the second field is the length of the zlib-compressed string.
213 /// Both fields are encoded in ULEB128. If \c doCompress is false, the
214 /// third field is the uncompressed strings; otherwise it is the
215 /// compressed string. When the string compression is off, the
216 /// second field will have value zero.
217 Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
218 bool doCompression, std::string &Result);
219
220 /// Produce \c Result string with the same format described above. The input
221 /// is vector of PGO function name variables that are referenced.
222 Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
223 std::string &Result, bool doCompression = true);
224
225 /// \c NameStrings is a string composed of one of more sub-strings encoded in
226 /// the format described above. The substrings are separated by 0 or more zero
227 /// bytes. This method decodes the string and populates the \c Symtab.
228 Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab);
229
230 /// Check if INSTR_PROF_RAW_VERSION_VAR is defined. This global is only being
231 /// set in IR PGO compilation.
232 bool isIRPGOFlagSet(const Module *M);
233
234 /// Check if we can safely rename this Comdat function. Instances of the same
235 /// comdat function may have different control flows thus can not share the
236 /// same counter variable.
237 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken = false);
238
239 enum InstrProfValueKind : uint32_t {
240 #define VALUE_PROF_KIND(Enumerator, Value, Descr) Enumerator = Value,
241 #include "llvm/ProfileData/InstrProfData.inc"
242 };
243
244 /// Get the value profile data for value site \p SiteIdx from \p InstrProfR
245 /// and annotate the instruction \p Inst with the value profile meta data.
246 /// Annotate up to \p MaxMDCount (default 3) number of records per value site.
247 void annotateValueSite(Module &M, Instruction &Inst,
248 const InstrProfRecord &InstrProfR,
249 InstrProfValueKind ValueKind, uint32_t SiteIndx,
250 uint32_t MaxMDCount = 3);
251
252 /// Same as the above interface but using an ArrayRef, as well as \p Sum.
253 void annotateValueSite(Module &M, Instruction &Inst,
254 ArrayRef<InstrProfValueData> VDs, uint64_t Sum,
255 InstrProfValueKind ValueKind, uint32_t MaxMDCount);
256
257 /// Extract the value profile data from \p Inst which is annotated with
258 /// value profile meta data. Return false if there is no value data annotated,
259 /// otherwise return true.
260 bool getValueProfDataFromInst(const Instruction &Inst,
261 InstrProfValueKind ValueKind,
262 uint32_t MaxNumValueData,
263 InstrProfValueData ValueData[],
264 uint32_t &ActualNumValueData, uint64_t &TotalC,
265 bool GetNoICPValue = false);
266
267 inline StringRef getPGOFuncNameMetadataName() { return "PGOFuncName"; }
268
269 /// Return the PGOFuncName meta data associated with a function.
270 MDNode *getPGOFuncNameMetadata(const Function &F);
271
272 /// Create the PGOFuncName meta data if PGOFuncName is different from
273 /// function's raw name. This should only apply to internal linkage functions
274 /// declared by users only.
275 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName);
276
277 /// Check if we can use Comdat for profile variables. This will eliminate
278 /// the duplicated profile variables for Comdat functions.
279 bool needsComdatForCounter(const Function &F, const Module &M);
280
281 /// An enum describing the attributes of an instrumented profile.
282 enum class InstrProfKind {
283 Unknown = 0x0,
284 FE = 0x1, // A frontend clang profile, incompatible with other attrs.
285 IR = 0x2, // An IR-level profile (default when -fprofile-generate is used).
286 BB = 0x4, // A profile with entry basic block instrumentation.
287 CS = 0x8, // A context sensitive IR-level profile.
288 SingleByteCoverage = 0x10, // Use single byte probes for coverage.
289 FunctionEntryOnly = 0x20, // Only instrument the function entry basic block.
290 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/FunctionEntryOnly)
291 };
292
293 const std::error_category &instrprof_category();
294
295 enum class instrprof_error {
296 success = 0,
297 eof,
298 unrecognized_format,
299 bad_magic,
300 bad_header,
301 unsupported_version,
302 unsupported_hash_type,
303 too_large,
304 truncated,
305 malformed,
306 missing_debug_info_for_correlation,
307 unexpected_debug_info_for_correlation,
308 unable_to_correlate_profile,
309 unknown_function,
310 invalid_prof,
311 hash_mismatch,
312 count_mismatch,
313 counter_overflow,
314 value_site_count_mismatch,
315 compress_failed,
316 uncompress_failed,
317 empty_raw_profile,
318 zlib_unavailable
319 };
320
321 inline std::error_code make_error_code(instrprof_error E) {
322 return std::error_code(static_cast<int>(E), instrprof_category());
323 }
324
325 class InstrProfError : public ErrorInfo<InstrProfError> {
326 public:
327 InstrProfError(instrprof_error Err, const Twine &ErrStr = Twine())
328 : Err(Err), Msg(ErrStr.str()) {
329 assert(Err != instrprof_error::success && "Not an error");
330 }
331
332 std::string message() const override;
333
334 void log(raw_ostream &OS) const override { OS << message(); }
335
336 std::error_code convertToErrorCode() const override {
337 return make_error_code(Err);
338 }
339
340 instrprof_error get() const { return Err; }
341 const std::string &getMessage() const { return Msg; }
342
343 /// Consume an Error and return the raw enum value contained within it. The
344 /// Error must either be a success value, or contain a single InstrProfError.
345 static instrprof_error take(Error E) {
346 auto Err = instrprof_error::success;
347 handleAllErrors(std::move(E), [&Err](const InstrProfError &IPE) {
348 assert(Err == instrprof_error::success && "Multiple errors encountered");
349 Err = IPE.get();
350 });
351 return Err;
352 }
353
354 static char ID;
355
356 private:
357 instrprof_error Err;
358 std::string Msg;
359 };
360
361 class SoftInstrProfErrors {
362 /// Count the number of soft instrprof_errors encountered and keep track of
363 /// the first such error for reporting purposes.
364
365 /// The first soft error encountered.
366 instrprof_error FirstError = instrprof_error::success;
367
368 /// The number of hash mismatches.
369 unsigned NumHashMismatches = 0;
370
371 /// The number of count mismatches.
372 unsigned NumCountMismatches = 0;
373
374 /// The number of counter overflows.
375 unsigned NumCounterOverflows = 0;
376
377 /// The number of value site count mismatches.
378 unsigned NumValueSiteCountMismatches = 0;
379
380 public:
381 SoftInstrProfErrors() = default;
382
383 ~SoftInstrProfErrors() {
384 assert(FirstError == instrprof_error::success &&
385 "Unchecked soft error encountered");
386 }
387
388 /// Track a soft error (\p IE) and increment its associated counter.
389 void addError(instrprof_error IE);
390
391 /// Get the number of hash mismatches.
392 unsigned getNumHashMismatches() const { return NumHashMismatches; }
393
394 /// Get the number of count mismatches.
395 unsigned getNumCountMismatches() const { return NumCountMismatches; }
396
397 /// Get the number of counter overflows.
398 unsigned getNumCounterOverflows() const { return NumCounterOverflows; }
399
400 /// Get the number of value site count mismatches.
401 unsigned getNumValueSiteCountMismatches() const {
402 return NumValueSiteCountMismatches;
403 }
404
405 /// Return the first encountered error and reset FirstError to a success
406 /// value.
407 Error takeError() {
408 if (FirstError == instrprof_error::success)
409 return Error::success();
410 auto E = make_error<InstrProfError>(FirstError);
411 FirstError = instrprof_error::success;
412 return E;
413 }
414 };
415
416 namespace object {
417
418 class SectionRef;
419
420 } // end namespace object
421
422 namespace IndexedInstrProf {
423
424 uint64_t ComputeHash(StringRef K);
425
426 } // end namespace IndexedInstrProf
427
428 /// A symbol table used for function PGO name look-up with keys
429 /// (such as pointers, md5hash values) to the function. A function's
430 /// PGO name or name's md5hash are used in retrieving the profile
431 /// data of the function. See \c getPGOFuncName() method for details
432 /// on how PGO name is formed.
433 class InstrProfSymtab {
434 public:
435 using AddrHashMap = std::vector<std::pair<uint64_t, uint64_t>>;
436
437 private:
438 StringRef Data;
439 uint64_t Address = 0;
440 // Unique name strings.
441 StringSet<> NameTab;
442 // A map from MD5 keys to function name strings.
443 std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
444 // A map from MD5 keys to function define. We only populate this map
445 // when build the Symtab from a Module.
446 std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
447 // A map from function runtime address to function name MD5 hash.
448 // This map is only populated and used by raw instr profile reader.
449 AddrHashMap AddrToMD5Map;
450 bool Sorted = false;
451
452 static StringRef getExternalSymbol() {
453 return "** External Symbol **";
454 }
455
456 // If the symtab is created by a series of calls to \c addFuncName, \c
457 // finalizeSymtab needs to be called before looking up function names.
458 // This is required because the underlying map is a vector (for space
459 // efficiency) which needs to be sorted.
460 inline void finalizeSymtab();
461
462 public:
463 InstrProfSymtab() = default;
464
465 /// Create InstrProfSymtab from an object file section which
466 /// contains function PGO names. When section may contain raw
467 /// string data or string data in compressed form. This method
468 /// only initialize the symtab with reference to the data and
469 /// the section base address. The decompression will be delayed
470 /// until before it is used. See also \c create(StringRef) method.
471 Error create(object::SectionRef &Section);
472
473 /// This interface is used by reader of CoverageMapping test
474 /// format.
475 inline Error create(StringRef D, uint64_t BaseAddr);
476
477 /// \c NameStrings is a string composed of one of more sub-strings
478 /// encoded in the format described in \c collectPGOFuncNameStrings.
479 /// This method is a wrapper to \c readPGOFuncNameStrings method.
480 inline Error create(StringRef NameStrings);
481
482 /// A wrapper interface to populate the PGO symtab with functions
483 /// decls from module \c M. This interface is used by transformation
484 /// passes such as indirect function call promotion. Variable \c InLTO
485 /// indicates if this is called from LTO optimization passes.
486 Error create(Module &M, bool InLTO = false);
487
488 /// Create InstrProfSymtab from a set of names iteratable from
489 /// \p IterRange. This interface is used by IndexedProfReader.
490 template <typename NameIterRange> Error create(const NameIterRange &IterRange);
491
492 /// Update the symtab by adding \p FuncName to the table. This interface
493 /// is used by the raw and text profile readers.
494 Error addFuncName(StringRef FuncName) {
495 if (FuncName.empty())
496 return make_error<InstrProfError>(instrprof_error::malformed,
497 "function name is empty");
498 auto Ins = NameTab.insert(FuncName);
499 if (Ins.second) {
500 MD5NameMap.push_back(std::make_pair(
501 IndexedInstrProf::ComputeHash(FuncName), Ins.first->getKey()));
502 Sorted = false;
503 }
504 return Error::success();
505 }
506
507 /// Map a function address to its name's MD5 hash. This interface
508 /// is only used by the raw profiler reader.
509 void mapAddress(uint64_t Addr, uint64_t MD5Val) {
510 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
511 }
512
513 /// Return a function's hash, or 0, if the function isn't in this SymTab.
514 uint64_t getFunctionHashFromAddress(uint64_t Address);
515
516 /// Return function's PGO name from the function name's symbol
517 /// address in the object file. If an error occurs, return
518 /// an empty string.
519 StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize);
520
521 /// Return function's PGO name from the name's md5 hash value.
522 /// If not found, return an empty string.
523 inline StringRef getFuncName(uint64_t FuncMD5Hash);
524
525 /// Just like getFuncName, except that it will return a non-empty StringRef
526 /// if the function is external to this symbol table. All such cases
527 /// will be represented using the same StringRef value.
528 inline StringRef getFuncNameOrExternalSymbol(uint64_t FuncMD5Hash);
529
530 /// True if Symbol is the value used to represent external symbols.
531 static bool isExternalSymbol(const StringRef &Symbol) {
532 return Symbol == InstrProfSymtab::getExternalSymbol();
533 }
534
535 /// Return function from the name's md5 hash. Return nullptr if not found.
536 inline Function *getFunction(uint64_t FuncMD5Hash);
537
538 /// Return the function's original assembly name by stripping off
539 /// the prefix attached (to symbols with priviate linkage). For
540 /// global functions, it returns the same string as getFuncName.
541 inline StringRef getOrigFuncName(uint64_t FuncMD5Hash);
542
543 /// Return the name section data.
544 inline StringRef getNameData() const { return Data; }
545
546 /// Dump the symbols in this table.
547 void dumpNames(raw_ostream &OS) const {
548 for (StringRef S : NameTab.keys())
549 OS << S << "\n";
550 }
551 };
552
553 Error InstrProfSymtab::create(StringRef D, uint64_t BaseAddr) {
554 Data = D;
555 Address = BaseAddr;
556 return Error::success();
557 }
558
559 Error InstrProfSymtab::create(StringRef NameStrings) {
560 return readPGOFuncNameStrings(NameStrings, *this);
561 }
562
563 template <typename NameIterRange>
564 Error InstrProfSymtab::create(const NameIterRange &IterRange) {
565 for (auto Name : IterRange)
566 if (Error E = addFuncName(Name))
567 return E;
568
569 finalizeSymtab();
570 return Error::success();
571 }
572
573 void InstrProfSymtab::finalizeSymtab() {
574 if (Sorted)
575 return;
576 llvm::sort(MD5NameMap, less_first());
577 llvm::sort(MD5FuncMap, less_first());
578 llvm::sort(AddrToMD5Map, less_first());
579 AddrToMD5Map.erase(std::unique(AddrToMD5Map.begin(), AddrToMD5Map.end()),
580 AddrToMD5Map.end());
581 Sorted = true;
582 }
583
584 StringRef InstrProfSymtab::getFuncNameOrExternalSymbol(uint64_t FuncMD5Hash) {
585 StringRef ret = getFuncName(FuncMD5Hash);
586 if (ret.empty())
587 return InstrProfSymtab::getExternalSymbol();
588 return ret;
589 }
590
591 StringRef InstrProfSymtab::getFuncName(uint64_t FuncMD5Hash) {
592 finalizeSymtab();
593 auto Result = llvm::lower_bound(MD5NameMap, FuncMD5Hash,
594 [](const std::pair<uint64_t, StringRef> &LHS,
595 uint64_t RHS) { return LHS.first < RHS; });
596 if (Result != MD5NameMap.end() && Result->first == FuncMD5Hash)
597 return Result->second;
598 return StringRef();
599 }
600
601 Function* InstrProfSymtab::getFunction(uint64_t FuncMD5Hash) {
602 finalizeSymtab();
603 auto Result = llvm::lower_bound(MD5FuncMap, FuncMD5Hash,
604 [](const std::pair<uint64_t, Function *> &LHS,
605 uint64_t RHS) { return LHS.first < RHS; });
606 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
607 return Result->second;
608 return nullptr;
609 }
610
611 // See also getPGOFuncName implementation. These two need to be
612 // matched.
613 StringRef InstrProfSymtab::getOrigFuncName(uint64_t FuncMD5Hash) {
614 StringRef PGOName = getFuncName(FuncMD5Hash);
615 size_t S = PGOName.find_first_of(':');
616 if (S == StringRef::npos)
617 return PGOName;
618 return PGOName.drop_front(S + 1);
619 }
620
621 // To store the sums of profile count values, or the percentage of
622 // the sums of the total count values.
623 struct CountSumOrPercent {
624 uint64_t NumEntries;
625 double CountSum;
626 double ValueCounts[IPVK_Last - IPVK_First + 1];
627 CountSumOrPercent() : NumEntries(0), CountSum(0.0f), ValueCounts() {}
628 void reset() {
629 NumEntries = 0;
630 CountSum = 0.0f;
631 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++)
632 ValueCounts[I] = 0.0f;
633 }
634 };
635
636 // Function level or program level overlap information.
637 struct OverlapStats {
638 enum OverlapStatsLevel { ProgramLevel, FunctionLevel };
639 // Sum of the total count values for the base profile.
640 CountSumOrPercent Base;
641 // Sum of the total count values for the test profile.
642 CountSumOrPercent Test;
643 // Overlap lap score. Should be in range of [0.0f to 1.0f].
644 CountSumOrPercent Overlap;
645 CountSumOrPercent Mismatch;
646 CountSumOrPercent Unique;
647 OverlapStatsLevel Level;
648 const std::string *BaseFilename;
649 const std::string *TestFilename;
650 StringRef FuncName;
651 uint64_t FuncHash;
652 bool Valid;
653
654 OverlapStats(OverlapStatsLevel L = ProgramLevel)
655 : Level(L), BaseFilename(nullptr), TestFilename(nullptr), FuncHash(0),
656 Valid(false) {}
657
658 void dump(raw_fd_ostream &OS) const;
659
660 void setFuncInfo(StringRef Name, uint64_t Hash) {
661 FuncName = Name;
662 FuncHash = Hash;
663 }
664
665 Error accumulateCounts(const std::string &BaseFilename,
666 const std::string &TestFilename, bool IsCS);
667 void addOneMismatch(const CountSumOrPercent &MismatchFunc);
668 void addOneUnique(const CountSumOrPercent &UniqueFunc);
669
670 static inline double score(uint64_t Val1, uint64_t Val2, double Sum1,
671 double Sum2) {
672 if (Sum1 < 1.0f || Sum2 < 1.0f)
673 return 0.0f;
674 return std::min(Val1 / Sum1, Val2 / Sum2);
675 }
676 };
677
678 // This is used to filter the functions whose overlap information
679 // to be output.
680 struct OverlapFuncFilters {
681 uint64_t ValueCutoff;
682 const std::string NameFilter;
683 };
684
685 struct InstrProfValueSiteRecord {
686 /// Value profiling data pairs at a given value site.
687 std::list<InstrProfValueData> ValueData;
688
689 InstrProfValueSiteRecord() { ValueData.clear(); }
690 template <class InputIterator>
691 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
692 : ValueData(F, L) {}
693
694 /// Sort ValueData ascending by Value
695 void sortByTargetValues() {
696 ValueData.sort(
697 [](const InstrProfValueData &left, const InstrProfValueData &right) {
698 return left.Value < right.Value;
699 });
700 }
701 /// Sort ValueData Descending by Count
702 inline void sortByCount();
703
704 /// Merge data from another InstrProfValueSiteRecord
705 /// Optionally scale merged counts by \p Weight.
706 void merge(InstrProfValueSiteRecord &Input, uint64_t Weight,
707 function_ref<void(instrprof_error)> Warn);
708 /// Scale up value profile data counts by N (Numerator) / D (Denominator).
709 void scale(uint64_t N, uint64_t D, function_ref<void(instrprof_error)> Warn);
710
711 /// Compute the overlap b/w this record and Input record.
712 void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind,
713 OverlapStats &Overlap, OverlapStats &FuncLevelOverlap);
714 };
715
716 /// Profiling information for a single function.
717 struct InstrProfRecord {
718 std::vector<uint64_t> Counts;
719
720 InstrProfRecord() = default;
721 InstrProfRecord(std::vector<uint64_t> Counts) : Counts(std::move(Counts)) {}
722 InstrProfRecord(InstrProfRecord &&) = default;
723 InstrProfRecord(const InstrProfRecord &RHS)
724 : Counts(RHS.Counts),
725 ValueData(RHS.ValueData
726 ? std::make_unique<ValueProfData>(*RHS.ValueData)
727 : nullptr) {}
728 InstrProfRecord &operator=(InstrProfRecord &&) = default;
729 InstrProfRecord &operator=(const InstrProfRecord &RHS) {
730 Counts = RHS.Counts;
731 if (!RHS.ValueData) {
732 ValueData = nullptr;
733 return *this;
734 }
735 if (!ValueData)
736 ValueData = std::make_unique<ValueProfData>(*RHS.ValueData);
737 else
738 *ValueData = *RHS.ValueData;
739 return *this;
740 }
741
742 /// Return the number of value profile kinds with non-zero number
743 /// of profile sites.
744 inline uint32_t getNumValueKinds() const;
745 /// Return the number of instrumented sites for ValueKind.
746 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
747
748 /// Return the total number of ValueData for ValueKind.
749 inline uint32_t getNumValueData(uint32_t ValueKind) const;
750
751 /// Return the number of value data collected for ValueKind at profiling
752 /// site: Site.
753 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
754 uint32_t Site) const;
755
756 /// Return the array of profiled values at \p Site. If \p TotalC
757 /// is not null, the total count of all target values at this site
758 /// will be stored in \c *TotalC.
759 inline std::unique_ptr<InstrProfValueData[]>
760 getValueForSite(uint32_t ValueKind, uint32_t Site,
761 uint64_t *TotalC = nullptr) const;
762
763 /// Get the target value/counts of kind \p ValueKind collected at site
764 /// \p Site and store the result in array \p Dest. Return the total
765 /// counts of all target values at this site.
766 inline uint64_t getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind,
767 uint32_t Site) const;
768
769 /// Reserve space for NumValueSites sites.
770 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
771
772 /// Add ValueData for ValueKind at value Site.
773 void addValueData(uint32_t ValueKind, uint32_t Site,
774 InstrProfValueData *VData, uint32_t N,
775 InstrProfSymtab *SymTab);
776
777 /// Merge the counts in \p Other into this one.
778 /// Optionally scale merged counts by \p Weight.
779 void merge(InstrProfRecord &Other, uint64_t Weight,
780 function_ref<void(instrprof_error)> Warn);
781
782 /// Scale up profile counts (including value profile data) by
783 /// a factor of (N / D).
784 void scale(uint64_t N, uint64_t D, function_ref<void(instrprof_error)> Warn);
785
786 /// Sort value profile data (per site) by count.
787 void sortValueData() {
788 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
789 for (auto &SR : getValueSitesForKind(Kind))
790 SR.sortByCount();
791 }
792
793 /// Clear value data entries and edge counters.
794 void Clear() {
795 Counts.clear();
796 clearValueData();
797 }
798
799 /// Clear value data entries
800 void clearValueData() { ValueData = nullptr; }
801
802 /// Compute the sums of all counts and store in Sum.
803 void accumulateCounts(CountSumOrPercent &Sum) const;
804
805 /// Compute the overlap b/w this IntrprofRecord and Other.
806 void overlap(InstrProfRecord &Other, OverlapStats &Overlap,
807 OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff);
808
809 /// Compute the overlap of value profile counts.
810 void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
811 OverlapStats &Overlap,
812 OverlapStats &FuncLevelOverlap);
813
814 private:
815 struct ValueProfData {
816 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
817 std::vector<InstrProfValueSiteRecord> MemOPSizes;
818 };
819 std::unique_ptr<ValueProfData> ValueData;
820
821 MutableArrayRef<InstrProfValueSiteRecord>
822 getValueSitesForKind(uint32_t ValueKind) {
823 // Cast to /add/ const (should be an implicit_cast, ideally, if that's ever
824 // implemented in LLVM) to call the const overload of this function, then
825 // cast away the constness from the result.
826 auto AR = const_cast<const InstrProfRecord *>(this)->getValueSitesForKind(
827 ValueKind);
828 return makeMutableArrayRef(
829 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
830 }
831 ArrayRef<InstrProfValueSiteRecord>
832 getValueSitesForKind(uint32_t ValueKind) const {
833 if (!ValueData)
834 return None;
835 switch (ValueKind) {
836 case IPVK_IndirectCallTarget:
837 return ValueData->IndirectCallSites;
838 case IPVK_MemOPSize:
839 return ValueData->MemOPSizes;
840 default:
841 llvm_unreachable("Unknown value kind!");
842 }
843 }
844
845 std::vector<InstrProfValueSiteRecord> &
846 getOrCreateValueSitesForKind(uint32_t ValueKind) {
847 if (!ValueData)
848 ValueData = std::make_unique<ValueProfData>();
849 switch (ValueKind) {
850 case IPVK_IndirectCallTarget:
851 return ValueData->IndirectCallSites;
852 case IPVK_MemOPSize:
853 return ValueData->MemOPSizes;
854 default:
855 llvm_unreachable("Unknown value kind!");
856 }
857 }
858
859 // Map indirect call target name hash to name string.
860 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
861 InstrProfSymtab *SymTab);
862
863 // Merge Value Profile data from Src record to this record for ValueKind.
864 // Scale merged value counts by \p Weight.
865 void mergeValueProfData(uint32_t ValkeKind, InstrProfRecord &Src,
866 uint64_t Weight,
867 function_ref<void(instrprof_error)> Warn);
868
869 // Scale up value profile data count by N (Numerator) / D (Denominator).
870 void scaleValueProfData(uint32_t ValueKind, uint64_t N, uint64_t D,
871 function_ref<void(instrprof_error)> Warn);
872 };
873
874 struct NamedInstrProfRecord : InstrProfRecord {
875 StringRef Name;
876 uint64_t Hash;
877
878 // We reserve this bit as the flag for context sensitive profile record.
879 static const int CS_FLAG_IN_FUNC_HASH = 60;
880
881 NamedInstrProfRecord() = default;
882 NamedInstrProfRecord(StringRef Name, uint64_t Hash,
883 std::vector<uint64_t> Counts)
884 : InstrProfRecord(std::move(Counts)), Name(Name), Hash(Hash) {}
885
886 static bool hasCSFlagInHash(uint64_t FuncHash) {
887 return ((FuncHash >> CS_FLAG_IN_FUNC_HASH) & 1);
888 }
889 static void setCSFlagInHash(uint64_t &FuncHash) {
890 FuncHash |= ((uint64_t)1 << CS_FLAG_IN_FUNC_HASH);
891 }
892 };
893
894 uint32_t InstrProfRecord::getNumValueKinds() const {
895 uint32_t NumValueKinds = 0;
896 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
897 NumValueKinds += !(getValueSitesForKind(Kind).empty());
898 return NumValueKinds;
899 }
900
901 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
902 uint32_t N = 0;
903 for (auto &SR : getValueSitesForKind(ValueKind))
904 N += SR.ValueData.size();
905 return N;
906 }
907
908 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
909 return getValueSitesForKind(ValueKind).size();
910 }
911
912 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
913 uint32_t Site) const {
914 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
915 }
916
917 std::unique_ptr<InstrProfValueData[]>
918 InstrProfRecord::getValueForSite(uint32_t ValueKind, uint32_t Site,
919 uint64_t *TotalC) const {
920 uint64_t Dummy = 0;
921 uint64_t &TotalCount = (TotalC == nullptr ? Dummy : *TotalC);
922 uint32_t N = getNumValueDataForSite(ValueKind, Site);
923 if (N == 0) {
924 TotalCount = 0;
925 return std::unique_ptr<InstrProfValueData[]>(nullptr);
926 }
927
928 auto VD = std::make_unique<InstrProfValueData[]>(N);
929 TotalCount = getValueForSite(VD.get(), ValueKind, Site);
930
931 return VD;
932 }
933
934 uint64_t InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
935 uint32_t ValueKind,
936 uint32_t Site) const {
937 uint32_t I = 0;
938 uint64_t TotalCount = 0;
939 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
940 Dest[I].Value = V.Value;
941 Dest[I].Count = V.Count;
942 TotalCount = SaturatingAdd(TotalCount, V.Count);
943 I++;
944 }
945 return TotalCount;
946 }
947
948 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
949 if (!NumValueSites)
950 return;
951 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
952 }
953
954 inline support::endianness getHostEndianness() {
955 return sys::IsLittleEndianHost ? support::little : support::big;
956 }
957
958 // Include definitions for value profile data
959 #define INSTR_PROF_VALUE_PROF_DATA
960 #include "llvm/ProfileData/InstrProfData.inc"
961
962 void InstrProfValueSiteRecord::sortByCount() {
963 ValueData.sort(
964 [](const InstrProfValueData &left, const InstrProfValueData &right) {
965 return left.Count > right.Count;
966 });
967 // Now truncate
968 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
969 if (ValueData.size() > max_s)
970 ValueData.resize(max_s);
971 }
972
973 namespace IndexedInstrProf {
974
975 enum class HashT : uint32_t {
976 MD5,
977 Last = MD5
978 };
979
980 inline uint64_t ComputeHash(HashT Type, StringRef K) {
981 switch (Type) {
982 case HashT::MD5:
983 return MD5Hash(K);
984 }
985 llvm_unreachable("Unhandled hash type");
986 }
987
988 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
989
990 enum ProfVersion {
991 // Version 1 is the first version. In this version, the value of
992 // a key/value pair can only include profile data of a single function.
993 // Due to this restriction, the number of block counters for a given
994 // function is not recorded but derived from the length of the value.
995 Version1 = 1,
996 // The version 2 format supports recording profile data of multiple
997 // functions which share the same key in one value field. To support this,
998 // the number block counters is recorded as an uint64_t field right after the
999 // function structural hash.
1000 Version2 = 2,
1001 // Version 3 supports value profile data. The value profile data is expected
1002 // to follow the block counter profile data.
1003 Version3 = 3,
1004 // In this version, profile summary data \c IndexedInstrProf::Summary is
1005 // stored after the profile header.
1006 Version4 = 4,
1007 // In this version, the frontend PGO stable hash algorithm defaults to V2.
1008 Version5 = 5,
1009 // In this version, the frontend PGO stable hash algorithm got fixed and
1010 // may produce hashes different from Version5.
1011 Version6 = 6,
1012 // An additional counter is added around logical operators.
1013 Version7 = 7,
1014 // The current version is 7.
1015 CurrentVersion = INSTR_PROF_INDEX_VERSION
1016 };
1017 const uint64_t Version = ProfVersion::CurrentVersion;
1018
1019 const HashT HashType = HashT::MD5;
1020
1021 inline uint64_t ComputeHash(StringRef K) { return ComputeHash(HashType, K); }
1022
1023 // This structure defines the file header of the LLVM profile
1024 // data file in indexed-format.
1025 struct Header {
1026 uint64_t Magic;
1027 uint64_t Version;
1028 uint64_t Unused; // Becomes unused since version 4
1029 uint64_t HashType;
1030 uint64_t HashOffset;
1031 };
1032
1033 // Profile summary data recorded in the profile data file in indexed
1034 // format. It is introduced in version 4. The summary data follows
1035 // right after the profile file header.
1036 struct Summary {
1037 struct Entry {
1038 uint64_t Cutoff; ///< The required percentile of total execution count.
1039 uint64_t
1040 MinBlockCount; ///< The minimum execution count for this percentile.
1041 uint64_t NumBlocks; ///< Number of blocks >= the minumum execution count.
1042 };
1043 // The field kind enumerator to assigned value mapping should remain
1044 // unchanged when a new kind is added or an old kind gets deleted in
1045 // the future.
1046 enum SummaryFieldKind {
1047 /// The total number of functions instrumented.
1048 TotalNumFunctions = 0,
1049 /// Total number of instrumented blocks/edges.
1050 TotalNumBlocks = 1,
1051 /// The maximal execution count among all functions.
1052 /// This field does not exist for profile data from IR based
1053 /// instrumentation.
1054 MaxFunctionCount = 2,
1055 /// Max block count of the program.
1056 MaxBlockCount = 3,
1057 /// Max internal block count of the program (excluding entry blocks).
1058 MaxInternalBlockCount = 4,
1059 /// The sum of all instrumented block counts.
1060 TotalBlockCount = 5,
1061 NumKinds = TotalBlockCount + 1
1062 };
1063
1064 // The number of summmary fields following the summary header.
1065 uint64_t NumSummaryFields;
1066 // The number of Cutoff Entries (Summary::Entry) following summary fields.
1067 uint64_t NumCutoffEntries;
1068
1069 Summary() = delete;
1070 Summary(uint32_t Size) { memset(this, 0, Size); }
1071
1072 void operator delete(void *ptr) { ::operator delete(ptr); }
1073
1074 static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries) {
1075 return sizeof(Summary) + NumCutoffEntries * sizeof(Entry) +
1076 NumSumFields * sizeof(uint64_t);
1077 }
1078
1079 const uint64_t *getSummaryDataBase() const {
1080 return reinterpret_cast<const uint64_t *>(this + 1);
1081 }
1082
1083 uint64_t *getSummaryDataBase() {
1084 return reinterpret_cast<uint64_t *>(this + 1);
1085 }
1086
1087 const Entry *getCutoffEntryBase() const {
1088 return reinterpret_cast<const Entry *>(
1089 &getSummaryDataBase()[NumSummaryFields]);
1090 }
1091
1092 Entry *getCutoffEntryBase() {
1093 return reinterpret_cast<Entry *>(&getSummaryDataBase()[NumSummaryFields]);
1094 }
1095
1096 uint64_t get(SummaryFieldKind K) const {
1097 return getSummaryDataBase()[K];
1098 }
1099
1100 void set(SummaryFieldKind K, uint64_t V) {
1101 getSummaryDataBase()[K] = V;
1102 }
1103
1104 const Entry &getEntry(uint32_t I) const { return getCutoffEntryBase()[I]; }
1105
1106 void setEntry(uint32_t I, const ProfileSummaryEntry &E) {
1107 Entry &ER = getCutoffEntryBase()[I];
1108 ER.Cutoff = E.Cutoff;
1109 ER.MinBlockCount = E.MinCount;
1110 ER.NumBlocks = E.NumCounts;
1111 }
1112 };
1113
1114 inline std::unique_ptr<Summary> allocSummary(uint32_t TotalSize) {
1115 return std::unique_ptr<Summary>(new (::operator new(TotalSize))
1116 Summary(TotalSize));
1117 }
1118
1119 } // end namespace IndexedInstrProf
1120
1121 namespace RawInstrProf {
1122
1123 // Version 1: First version
1124 // Version 2: Added value profile data section. Per-function control data
1125 // struct has more fields to describe value profile information.
1126 // Version 3: Compressed name section support. Function PGO name reference
1127 // from control data struct is changed from raw pointer to Name's MD5 value.
1128 // Version 4: ValueDataBegin and ValueDataSizes fields are removed from the
1129 // raw header.
1130 // Version 5: Bit 60 of FuncHash is reserved for the flag for the context
1131 // sensitive records.
1132 // Version 6: Added binary id.
1133 // Version 7: Reorder binary id and include version in signature.
1134 // Version 8: Use relative counter pointer.
1135 const uint64_t Version = INSTR_PROF_RAW_VERSION;
1136
1137 template <class IntPtrT> inline uint64_t getMagic();
1138 template <> inline uint64_t getMagic<uint64_t>() {
1139 return INSTR_PROF_RAW_MAGIC_64;
1140 }
1141
1142 template <> inline uint64_t getMagic<uint32_t>() {
1143 return INSTR_PROF_RAW_MAGIC_32;
1144 }
1145
1146 // Per-function profile data header/control structure.
1147 // The definition should match the structure defined in
1148 // compiler-rt/lib/profile/InstrProfiling.h.
1149 // It should also match the synthesized type in
1150 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
1151 template <class IntPtrT> struct alignas(8) ProfileData {
1152 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
1153 #include "llvm/ProfileData/InstrProfData.inc"
1154 };
1155
1156 // File header structure of the LLVM profile data in raw format.
1157 // The definition should match the header referenced in
1158 // compiler-rt/lib/profile/InstrProfilingFile.c and
1159 // InstrProfilingBuffer.c.
1160 struct Header {
1161 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
1162 #include "llvm/ProfileData/InstrProfData.inc"
1163 };
1164
1165 } // end namespace RawInstrProf
1166
1167 // Parse MemOP Size range option.
1168 void getMemOPSizeRangeFromOption(StringRef Str, int64_t &RangeStart,
1169 int64_t &RangeLast);
1170
1171 // Create the variable for the profile file name.
1172 void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput);
1173
1174 // Whether to compress function names in profile records, and filenames in
1175 // code coverage mappings. Used by the Instrumentation library and unit tests.
1176 extern cl::opt<bool> DoInstrProfNameCompression;
1177
1178 } // end namespace llvm
1179 #endif // LLVM_PROFILEDATA_INSTRPROF_H