LLVM 20.0.0git
InstrProf.h
Go to the documentation of this file.
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"
20#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/StringSet.h"
25#include "llvm/IR/GlobalValue.h"
31#include "llvm/Support/Error.h"
33#include "llvm/Support/MD5.h"
38#include <algorithm>
39#include <cassert>
40#include <cstddef>
41#include <cstdint>
42#include <cstring>
43#include <list>
44#include <memory>
45#include <string>
46#include <system_error>
47#include <utility>
48#include <vector>
49
50namespace llvm {
51
52class Function;
53class GlobalVariable;
54struct InstrProfRecord;
55class InstrProfSymtab;
56class Instruction;
57class MDNode;
58class Module;
59
61#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind,
63};
64
65/// Return the max count value. We reserver a few large values for special use.
67 return std::numeric_limits<uint64_t>::max() - 2;
68}
69
70/// Return the name of the profile section corresponding to \p IPSK.
71///
72/// The name of the section depends on the object format type \p OF. If
73/// \p AddSegmentInfo is true, a segment prefix and additional linker hints may
74/// be added to the section name (this is the default).
77 bool AddSegmentInfo = true);
78
79/// Return the name profile runtime entry point to do value profiling
80/// for a given site.
82 return INSTR_PROF_VALUE_PROF_FUNC_STR;
83}
84
85/// Return the name profile runtime entry point to do memop size value
86/// profiling.
88 return INSTR_PROF_VALUE_PROF_MEMOP_FUNC_STR;
89}
90
91/// Return the name prefix of variables containing instrumented function names.
92inline StringRef getInstrProfNameVarPrefix() { return "__profn_"; }
93
94/// Return the name prefix of variables containing virtual table profile data.
95inline StringRef getInstrProfVTableVarPrefix() { return "__profvt_"; }
96
97/// Return the name prefix of variables containing per-function control data.
98inline StringRef getInstrProfDataVarPrefix() { return "__profd_"; }
99
100/// Return the name prefix of profile counter variables.
101inline StringRef getInstrProfCountersVarPrefix() { return "__profc_"; }
102
103/// Return the name prefix of profile bitmap variables.
104inline StringRef getInstrProfBitmapVarPrefix() { return "__profbm_"; }
105
106/// Return the name prefix of value profile variables.
107inline StringRef getInstrProfValuesVarPrefix() { return "__profvp_"; }
108
109/// Return the name of value profile node array variables:
110inline StringRef getInstrProfVNodesVarName() { return "__llvm_prf_vnodes"; }
111
112/// Return the name of the variable holding the strings (possibly compressed)
113/// of all function's PGO names.
114inline StringRef getInstrProfNamesVarName() { return "__llvm_prf_nm"; }
115
116inline StringRef getInstrProfVTableNamesVarName() { return "__llvm_prf_vnm"; }
117
118/// Return the name of a covarage mapping variable (internal linkage)
119/// for each instrumented source module. Such variables are allocated
120/// in the __llvm_covmap section.
122 return "__llvm_coverage_mapping";
123}
124
125/// Return the name of the internal variable recording the array
126/// of PGO name vars referenced by the coverage mapping. The owning
127/// functions of those names are not emitted by FE (e.g, unused inline
128/// functions.)
130 return "__llvm_coverage_names";
131}
132
133/// Return the name of function that registers all the per-function control
134/// data at program startup time by calling __llvm_register_function. This
135/// function has internal linkage and is called by __llvm_profile_init
136/// runtime method. This function is not generated for these platforms:
137/// Darwin, Linux, and FreeBSD.
139 return "__llvm_profile_register_functions";
140}
141
142/// Return the name of the runtime interface that registers per-function control
143/// data for one instrumented function.
145 return "__llvm_profile_register_function";
146}
147
148/// Return the name of the runtime interface that registers the PGO name
149/// strings.
151 return "__llvm_profile_register_names_function";
152}
153
154/// Return the name of the runtime initialization method that is generated by
155/// the compiler. The function calls __llvm_profile_register_functions and
156/// __llvm_profile_override_default_filename functions if needed. This function
157/// has internal linkage and invoked at startup time via init_array.
158inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
159
160/// Return the name of the hook variable defined in profile runtime library.
161/// A reference to the variable causes the linker to link in the runtime
162/// initialization module (which defines the hook variable).
164 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_RUNTIME_VAR);
165}
166
167/// Return the name of the compiler generated function that references the
168/// runtime hook variable. The function is a weak global.
170 return "__llvm_profile_runtime_user";
171}
172
174 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_COUNTER_BIAS_VAR);
175}
176
178 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_BITMAP_BIAS_VAR);
179}
180
181/// Return the marker used to separate PGO names during serialization.
182inline StringRef getInstrProfNameSeparator() { return "\01"; }
183
184/// Determines whether module targets a GPU eligable for PGO
185/// instrumentation
186bool isGPUProfTarget(const Module &M);
187
188/// Please use getIRPGOFuncName for LLVM IR instrumentation. This function is
189/// for front-end (Clang, etc) instrumentation.
190/// Return the modified name for function \c F suitable to be
191/// used the key for profile lookup. Variable \c InLTO indicates if this
192/// is called in LTO optimization passes.
193std::string getPGOFuncName(const Function &F, bool InLTO = false,
194 uint64_t Version = INSTR_PROF_INDEX_VERSION);
195
196/// Return the modified name for a function suitable to be
197/// used the key for profile lookup. The function's original
198/// name is \c RawFuncName and has linkage of type \c Linkage.
199/// The function is defined in module \c FileName.
200std::string getPGOFuncName(StringRef RawFuncName,
202 StringRef FileName,
203 uint64_t Version = INSTR_PROF_INDEX_VERSION);
204
205/// \return the modified name for function \c F suitable to be
206/// used as the key for IRPGO profile lookup. \c InLTO indicates if this is
207/// called from LTO optimization passes.
208std::string getIRPGOFuncName(const Function &F, bool InLTO = false);
209
210/// \return the filename and the function name parsed from the output of
211/// \c getIRPGOFuncName()
212std::pair<StringRef, StringRef> getParsedIRPGOName(StringRef IRPGOName);
213
214/// Return the name of the global variable used to store a function
215/// name in PGO instrumentation. \c FuncName is the IRPGO function name
216/// (returned by \c getIRPGOFuncName) for LLVM IR instrumentation and PGO
217/// function name (returned by \c getPGOFuncName) for front-end instrumentation.
218std::string getPGOFuncNameVarName(StringRef FuncName,
220
221/// Create and return the global variable for function name used in PGO
222/// instrumentation. \c FuncName is the IRPGO function name (returned by
223/// \c getIRPGOFuncName) for LLVM IR instrumentation and PGO function name
224/// (returned by \c getPGOFuncName) for front-end instrumentation.
225GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName);
226
227/// Create and return the global variable for function name used in PGO
228/// instrumentation. \c FuncName is the IRPGO function name (returned by
229/// \c getIRPGOFuncName) for LLVM IR instrumentation and PGO function name
230/// (returned by \c getPGOFuncName) for front-end instrumentation.
231GlobalVariable *createPGOFuncNameVar(Module &M,
233 StringRef PGOFuncName);
234
235/// Return the initializer in string of the PGO name var \c NameVar.
236StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar);
237
238/// Given a PGO function name, remove the filename prefix and return
239/// the original (static) function name.
240StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName,
241 StringRef FileName = "<unknown>");
242
243/// Given a vector of strings (names of global objects like functions or,
244/// virtual tables) \c NameStrs, the method generates a combined string \c
245/// Result that is ready to be serialized. The \c Result string is comprised of
246/// three fields: The first field is the length of the uncompressed strings, and
247/// the the second field is the length of the zlib-compressed string. Both
248/// fields are encoded in ULEB128. If \c doCompress is false, the
249/// third field is the uncompressed strings; otherwise it is the
250/// compressed string. When the string compression is off, the
251/// second field will have value zero.
252Error collectGlobalObjectNameStrings(ArrayRef<std::string> NameStrs,
253 bool doCompression, std::string &Result);
254
255/// Produce \c Result string with the same format described above. The input
256/// is vector of PGO function name variables that are referenced.
257/// The global variable element in 'NameVars' is a string containing the pgo
258/// name of a function. See `createPGOFuncNameVar` that creates these global
259/// variables.
260Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
261 std::string &Result, bool doCompression = true);
262
263Error collectVTableStrings(ArrayRef<GlobalVariable *> VTables,
264 std::string &Result, bool doCompression);
265
266/// Check if INSTR_PROF_RAW_VERSION_VAR is defined. This global is only being
267/// set in IR PGO compilation.
268bool isIRPGOFlagSet(const Module *M);
269
270/// Check if we can safely rename this Comdat function. Instances of the same
271/// comdat function may have different control flows thus can not share the
272/// same counter variable.
273bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken = false);
274
276#define VALUE_PROF_KIND(Enumerator, Value, Descr) Enumerator = Value,
278};
279
280/// Get the value profile data for value site \p SiteIdx from \p InstrProfR
281/// and annotate the instruction \p Inst with the value profile meta data.
282/// Annotate up to \p MaxMDCount (default 3) number of records per value site.
283void annotateValueSite(Module &M, Instruction &Inst,
284 const InstrProfRecord &InstrProfR,
285 InstrProfValueKind ValueKind, uint32_t SiteIndx,
286 uint32_t MaxMDCount = 3);
287
288/// Same as the above interface but using an ArrayRef, as well as \p Sum.
289/// This function will not annotate !prof metadata on the instruction if the
290/// referenced array is empty.
291void annotateValueSite(Module &M, Instruction &Inst,
292 ArrayRef<InstrProfValueData> VDs, uint64_t Sum,
293 InstrProfValueKind ValueKind, uint32_t MaxMDCount);
294
295// TODO: Unify metadata name 'PGOFuncName' and 'PGOName', by supporting read
296// of this metadata for backward compatibility and generating 'PGOName' only.
297/// Extract the value profile data from \p Inst and returns them if \p Inst is
298/// annotated with value profile data. Returns an empty vector otherwise.
299SmallVector<InstrProfValueData, 4>
300getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind,
301 uint32_t MaxNumValueData, uint64_t &TotalC,
302 bool GetNoICPValue = false);
303
304inline StringRef getPGOFuncNameMetadataName() { return "PGOFuncName"; }
305
306inline StringRef getPGONameMetadataName() { return "PGOName"; }
307
308/// Return the PGOFuncName meta data associated with a function.
309MDNode *getPGOFuncNameMetadata(const Function &F);
310
311std::string getPGOName(const GlobalVariable &V, bool InLTO = false);
312
313/// Create the PGOFuncName meta data if PGOFuncName is different from
314/// function's raw name. This should only apply to internal linkage functions
315/// declared by users only.
316/// TODO: Update all callers to 'createPGONameMetadata' and deprecate this
317/// function.
318void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName);
319
320/// Create the PGOName metadata if a global object's PGO name is different from
321/// its mangled name. This should apply to local-linkage global objects only.
322void createPGONameMetadata(GlobalObject &GO, StringRef PGOName);
323
324/// Check if we can use Comdat for profile variables. This will eliminate
325/// the duplicated profile variables for Comdat functions.
326bool needsComdatForCounter(const GlobalObject &GV, const Module &M);
327
328/// An enum describing the attributes of an instrumented profile.
329enum class InstrProfKind {
330 Unknown = 0x0,
331 // A frontend clang profile, incompatible with other attrs.
333 // An IR-level profile (default when -fprofile-generate is used).
334 IRInstrumentation = 0x2,
335 // A profile with entry basic block instrumentation.
337 // A context sensitive IR-level profile.
338 ContextSensitive = 0x8,
339 // Use single byte probes for coverage.
340 SingleByteCoverage = 0x10,
341 // Only instrument the function entry basic block.
342 FunctionEntryOnly = 0x20,
343 // A memory profile collected using -fprofile=memory.
344 MemProf = 0x40,
345 // A temporal profile.
346 TemporalProfile = 0x80,
348};
349
350const std::error_category &instrprof_category();
351
352enum class instrprof_error {
353 success = 0,
354 eof,
356 bad_magic,
360 too_large,
361 truncated,
362 malformed,
379};
380
381/// An ordered list of functions identified by their NameRef found in
382/// INSTR_PROF_DATA
384 std::vector<uint64_t> FunctionNameRefs;
386 TemporalProfTraceTy(std::initializer_list<uint64_t> Trace = {},
387 uint64_t Weight = 1)
389
390 /// Use a set of temporal profile traces to create a list of balanced
391 /// partitioning function nodes used by BalancedPartitioning to generate a
392 /// function order that reduces page faults during startup
393 static void createBPFunctionNodes(ArrayRef<TemporalProfTraceTy> Traces,
394 std::vector<BPFunctionNode> &Nodes,
395 bool RemoveOutlierUNs = true);
396};
397
398inline std::error_code make_error_code(instrprof_error E) {
399 return std::error_code(static_cast<int>(E), instrprof_category());
400}
401
402class InstrProfError : public ErrorInfo<InstrProfError> {
403public:
405 : Err(Err), Msg(ErrStr.str()) {
406 assert(Err != instrprof_error::success && "Not an error");
407 }
408
409 std::string message() const override;
410
411 void log(raw_ostream &OS) const override { OS << message(); }
412
413 std::error_code convertToErrorCode() const override {
414 return make_error_code(Err);
415 }
416
417 instrprof_error get() const { return Err; }
418 const std::string &getMessage() const { return Msg; }
419
420 /// Consume an Error and return the raw enum value contained within it, and
421 /// the optional error message. The Error must either be a success value, or
422 /// contain a single InstrProfError.
423 static std::pair<instrprof_error, std::string> take(Error E) {
424 auto Err = instrprof_error::success;
425 std::string Msg = "";
426 handleAllErrors(std::move(E), [&Err, &Msg](const InstrProfError &IPE) {
427 assert(Err == instrprof_error::success && "Multiple errors encountered");
428 Err = IPE.get();
429 Msg = IPE.getMessage();
430 });
431 return {Err, Msg};
432 }
433
434 static char ID;
435
436private:
437 instrprof_error Err;
438 std::string Msg;
439};
440
441namespace object {
442
443class SectionRef;
444
445} // end namespace object
446
447namespace IndexedInstrProf {
448
450
451} // end namespace IndexedInstrProf
452
453/// A symbol table used for function [IR]PGO name look-up with keys
454/// (such as pointers, md5hash values) to the function. A function's
455/// [IR]PGO name or name's md5hash are used in retrieving the profile
456/// data of the function. See \c getIRPGOFuncName() and \c getPGOFuncName
457/// methods for details how [IR]PGO name is formed.
459public:
460 using AddrHashMap = std::vector<std::pair<uint64_t, uint64_t>>;
461
462private:
463 using AddrIntervalMap =
465 StringRef Data;
466 uint64_t Address = 0;
467 // Unique name strings. Used to ensure entries in MD5NameMap (a vector that's
468 // going to be sorted) has unique MD5 keys in the first place.
469 StringSet<> NameTab;
470 // Records the unique virtual table names. This is used by InstrProfWriter to
471 // write out an on-disk chained hash table of virtual table names.
472 // InstrProfWriter stores per function profile data (keyed by function names)
473 // so it doesn't use a StringSet for function names.
474 StringSet<> VTableNames;
475 // A map from MD5 keys to function name strings.
476 std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
477 // A map from MD5 keys to function define. We only populate this map
478 // when build the Symtab from a Module.
479 std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
480 // A map from MD5 to the global variable. This map is only populated when
481 // building the symtab from a module. Use separate container instances for
482 // `MD5FuncMap` and `MD5VTableMap`.
483 // TODO: Unify the container type and the lambda function 'mapName' inside
484 // add{Func,VTable}WithName.
486 // A map from function runtime address to function name MD5 hash.
487 // This map is only populated and used by raw instr profile reader.
488 AddrHashMap AddrToMD5Map;
489
490 AddrIntervalMap::Allocator VTableAddrMapAllocator;
491 // This map is only populated and used by raw instr profile reader.
492 AddrIntervalMap VTableAddrMap;
493 bool Sorted = false;
494
495 static StringRef getExternalSymbol() { return "** External Symbol **"; }
496
497 // Returns the canonial name of the given PGOName. In a canonical name, all
498 // suffixes that begins with "." except ".__uniq." are stripped.
499 // FIXME: Unify this with `FunctionSamples::getCanonicalFnName`.
500 static StringRef getCanonicalName(StringRef PGOName);
501
502 // Add the function into the symbol table, by creating the following
503 // map entries:
504 // name-set = {PGOFuncName} union {getCanonicalName(PGOFuncName)}
505 // - In MD5NameMap: <MD5Hash(name), name> for name in name-set
506 // - In MD5FuncMap: <MD5Hash(name), &F> for name in name-set
507 Error addFuncWithName(Function &F, StringRef PGOFuncName);
508
509 // Add the vtable into the symbol table, by creating the following
510 // map entries:
511 // name-set = {PGOName} union {getCanonicalName(PGOName)}
512 // - In MD5NameMap: <MD5Hash(name), name> for name in name-set
513 // - In MD5VTableMap: <MD5Hash(name), name> for name in name-set
514 Error addVTableWithName(GlobalVariable &V, StringRef PGOVTableName);
515
516 // If the symtab is created by a series of calls to \c addFuncName, \c
517 // finalizeSymtab needs to be called before looking up function names.
518 // This is required because the underlying map is a vector (for space
519 // efficiency) which needs to be sorted.
520 inline void finalizeSymtab();
521
522public:
523 InstrProfSymtab() : VTableAddrMap(VTableAddrMapAllocator) {}
524
525 // Not copyable or movable.
526 // Consider std::unique_ptr for move.
531
532 /// Create InstrProfSymtab from an object file section which
533 /// contains function PGO names. When section may contain raw
534 /// string data or string data in compressed form. This method
535 /// only initialize the symtab with reference to the data and
536 /// the section base address. The decompression will be delayed
537 /// until before it is used. See also \c create(StringRef) method.
539
540 /// \c NameStrings is a string composed of one of more sub-strings
541 /// encoded in the format described in \c collectPGOFuncNameStrings.
542 /// This method is a wrapper to \c readAndDecodeStrings method.
543 Error create(StringRef NameStrings);
544
545 /// Initialize symtab states with function names and vtable names. \c
546 /// FuncNameStrings is a string composed of one or more encoded function name
547 /// strings, and \c VTableNameStrings composes of one or more encoded vtable
548 /// names. This interface is solely used by raw profile reader.
549 Error create(StringRef FuncNameStrings, StringRef VTableNameStrings);
550
551 /// Initialize 'this' with the set of vtable names encoded in
552 /// \c CompressedVTableNames.
554
555 /// This interface is used by reader of CoverageMapping test
556 /// format.
557 inline Error create(StringRef D, uint64_t BaseAddr);
558
559 /// A wrapper interface to populate the PGO symtab with functions
560 /// decls from module \c M. This interface is used by transformation
561 /// passes such as indirect function call promotion. Variable \c InLTO
562 /// indicates if this is called from LTO optimization passes.
563 Error create(Module &M, bool InLTO = false);
564
565 /// Create InstrProfSymtab from a set of names iteratable from
566 /// \p IterRange. This interface is used by IndexedProfReader.
567 template <typename NameIterRange>
568 Error create(const NameIterRange &IterRange);
569
570 /// Create InstrProfSymtab from a set of function names and vtable
571 /// names iteratable from \p IterRange. This interface is used by
572 /// IndexedProfReader.
573 template <typename FuncNameIterRange, typename VTableNameIterRange>
574 Error create(const FuncNameIterRange &FuncIterRange,
575 const VTableNameIterRange &VTableIterRange);
576
577 // Map the MD5 of the symbol name to the name.
579 if (SymbolName.empty())
580 return make_error<InstrProfError>(instrprof_error::malformed,
581 "symbol name is empty");
582
583 // Insert into NameTab so that MD5NameMap (a vector that will be sorted)
584 // won't have duplicated entries in the first place.
585 auto Ins = NameTab.insert(SymbolName);
586 if (Ins.second) {
587 MD5NameMap.push_back(std::make_pair(
588 IndexedInstrProf::ComputeHash(SymbolName), Ins.first->getKey()));
589 Sorted = false;
590 }
591 return Error::success();
592 }
593
594 /// The method name is kept since there are many callers.
595 /// It just forwards to 'addSymbolName'.
596 Error addFuncName(StringRef FuncName) { return addSymbolName(FuncName); }
597
598 /// Adds VTableName as a known symbol, and inserts it to a map that
599 /// tracks all vtable names.
601 if (Error E = addSymbolName(VTableName))
602 return E;
603
604 // Record VTableName. InstrProfWriter uses this set. The comment around
605 // class member explains why.
606 VTableNames.insert(VTableName);
607 return Error::success();
608 }
609
610 const StringSet<> &getVTableNames() const { return VTableNames; }
611
612 /// Map a function address to its name's MD5 hash. This interface
613 /// is only used by the raw profiler reader.
615 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
616 }
617
618 /// Map the address range (i.e., [start_address, end_address)) of a variable
619 /// to its names' MD5 hash. This interface is only used by the raw profile
620 /// reader.
621 void mapVTableAddress(uint64_t StartAddr, uint64_t EndAddr, uint64_t MD5Val) {
622 VTableAddrMap.insert(StartAddr, EndAddr, MD5Val);
623 }
624
625 /// Return a function's hash, or 0, if the function isn't in this SymTab.
627
628 /// Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
630
631 /// Return function's PGO name from the function name's symbol
632 /// address in the object file. If an error occurs, return
633 /// an empty string.
634 StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize);
635
636 /// Return name of functions or global variables from the name's md5 hash
637 /// value. If not found, return an empty string.
638 inline StringRef getFuncOrVarName(uint64_t ValMD5Hash);
639
640 /// Just like getFuncOrVarName, except that it will return literal string
641 /// 'External Symbol' if the function or global variable is external to
642 /// this symbol table.
644
645 /// True if Symbol is the value used to represent external symbols.
646 static bool isExternalSymbol(const StringRef &Symbol) {
647 return Symbol == InstrProfSymtab::getExternalSymbol();
648 }
649
650 /// Return function from the name's md5 hash. Return nullptr if not found.
651 inline Function *getFunction(uint64_t FuncMD5Hash);
652
653 /// Return the global variable corresponding to md5 hash. Return nullptr if
654 /// not found.
656
657 /// Return the name section data.
658 inline StringRef getNameData() const { return Data; }
659
660 /// Dump the symbols in this table.
661 void dumpNames(raw_ostream &OS) const;
662};
663
665 Data = D;
666 Address = BaseAddr;
667 return Error::success();
668}
669
670template <typename NameIterRange>
671Error InstrProfSymtab::create(const NameIterRange &IterRange) {
672 for (auto Name : IterRange)
673 if (Error E = addFuncName(Name))
674 return E;
675
676 finalizeSymtab();
677 return Error::success();
678}
679
680template <typename FuncNameIterRange, typename VTableNameIterRange>
681Error InstrProfSymtab::create(const FuncNameIterRange &FuncIterRange,
682 const VTableNameIterRange &VTableIterRange) {
683 // Iterate elements by StringRef rather than by const reference.
684 // StringRef is small enough, so the loop is efficient whether
685 // element in the range is std::string or StringRef.
686 for (StringRef Name : FuncIterRange)
687 if (Error E = addFuncName(Name))
688 return E;
689
690 for (StringRef VTableName : VTableIterRange)
691 if (Error E = addVTableName(VTableName))
692 return E;
693
694 finalizeSymtab();
695 return Error::success();
696}
697
698void InstrProfSymtab::finalizeSymtab() {
699 if (Sorted)
700 return;
701 llvm::sort(MD5NameMap, less_first());
702 llvm::sort(MD5FuncMap, less_first());
703 llvm::sort(AddrToMD5Map, less_first());
704 AddrToMD5Map.erase(llvm::unique(AddrToMD5Map), AddrToMD5Map.end());
705 Sorted = true;
706}
707
710 if (ret.empty())
711 return InstrProfSymtab::getExternalSymbol();
712 return ret;
713}
714
716 finalizeSymtab();
717 auto Result = llvm::lower_bound(MD5NameMap, MD5Hash,
718 [](const std::pair<uint64_t, StringRef> &LHS,
719 uint64_t RHS) { return LHS.first < RHS; });
720 if (Result != MD5NameMap.end() && Result->first == MD5Hash)
721 return Result->second;
722 return StringRef();
723}
724
726 finalizeSymtab();
727 auto Result = llvm::lower_bound(MD5FuncMap, FuncMD5Hash,
728 [](const std::pair<uint64_t, Function *> &LHS,
729 uint64_t RHS) { return LHS.first < RHS; });
730 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
731 return Result->second;
732 return nullptr;
733}
734
736 return MD5VTableMap.lookup(MD5Hash);
737}
738
739// To store the sums of profile count values, or the percentage of
740// the sums of the total count values.
743 double CountSum = 0.0f;
744 std::array<double, IPVK_Last - IPVK_First + 1> ValueCounts = {};
745 CountSumOrPercent() = default;
746 void reset() {
747 NumEntries = 0;
748 CountSum = 0.0f;
749 ValueCounts.fill(0.0f);
750 }
751};
752
753// Function level or program level overlap information.
756 // Sum of the total count values for the base profile.
758 // Sum of the total count values for the test profile.
760 // Overlap lap score. Should be in range of [0.0f to 1.0f].
765 const std::string *BaseFilename = nullptr;
766 const std::string *TestFilename = nullptr;
769 bool Valid = false;
770
772
773 void dump(raw_fd_ostream &OS) const;
774
776 FuncName = Name;
777 FuncHash = Hash;
778 }
779
780 Error accumulateCounts(const std::string &BaseFilename,
781 const std::string &TestFilename, bool IsCS);
782 void addOneMismatch(const CountSumOrPercent &MismatchFunc);
783 void addOneUnique(const CountSumOrPercent &UniqueFunc);
784
785 static inline double score(uint64_t Val1, uint64_t Val2, double Sum1,
786 double Sum2) {
787 if (Sum1 < 1.0f || Sum2 < 1.0f)
788 return 0.0f;
789 return std::min(Val1 / Sum1, Val2 / Sum2);
790 }
791};
792
793// This is used to filter the functions whose overlap information
794// to be output.
797 const std::string NameFilter;
798};
799
801 /// Value profiling data pairs at a given value site.
802 std::vector<InstrProfValueData> ValueData;
803
805 InstrProfValueSiteRecord(std::vector<InstrProfValueData> &&VD)
806 : ValueData(VD) {}
807
808 /// Sort ValueData ascending by Value
811 [](const InstrProfValueData &L, const InstrProfValueData &R) {
812 return L.Value < R.Value;
813 });
814 }
815 /// Sort ValueData Descending by Count
816 inline void sortByCount();
817
818 /// Merge data from another InstrProfValueSiteRecord
819 /// Optionally scale merged counts by \p Weight.
820 void merge(InstrProfValueSiteRecord &Input, uint64_t Weight,
821 function_ref<void(instrprof_error)> Warn);
822 /// Scale up value profile data counts by N (Numerator) / D (Denominator).
824
825 /// Compute the overlap b/w this record and Input record.
826 void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind,
827 OverlapStats &Overlap, OverlapStats &FuncLevelOverlap);
828};
829
830/// Profiling information for a single function.
832 std::vector<uint64_t> Counts;
833 std::vector<uint8_t> BitmapBytes;
834
835 InstrProfRecord() = default;
836 InstrProfRecord(std::vector<uint64_t> Counts) : Counts(std::move(Counts)) {}
837 InstrProfRecord(std::vector<uint64_t> Counts,
838 std::vector<uint8_t> BitmapBytes)
843 ValueData(RHS.ValueData
844 ? std::make_unique<ValueProfData>(*RHS.ValueData)
845 : nullptr) {}
848 Counts = RHS.Counts;
849 BitmapBytes = RHS.BitmapBytes;
850 if (!RHS.ValueData) {
851 ValueData = nullptr;
852 return *this;
853 }
854 if (!ValueData)
855 ValueData = std::make_unique<ValueProfData>(*RHS.ValueData);
856 else
857 *ValueData = *RHS.ValueData;
858 return *this;
859 }
860
861 /// Return the number of value profile kinds with non-zero number
862 /// of profile sites.
863 inline uint32_t getNumValueKinds() const;
864 /// Return the number of instrumented sites for ValueKind.
865 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
866
867 /// Return the total number of ValueData for ValueKind.
868 inline uint32_t getNumValueData(uint32_t ValueKind) const;
869
870 /// Return the array of profiled values at \p Site.
872 uint32_t Site) const;
873
874 /// Reserve space for NumValueSites sites.
875 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
876
877 /// Add ValueData for ValueKind at value Site. We do not support adding sites
878 /// out of order. Site must go up from 0 one by one.
879 void addValueData(uint32_t ValueKind, uint32_t Site,
881 InstrProfSymtab *SymTab);
882
883 /// Merge the counts in \p Other into this one.
884 /// Optionally scale merged counts by \p Weight.
885 void merge(InstrProfRecord &Other, uint64_t Weight,
886 function_ref<void(instrprof_error)> Warn);
887
888 /// Scale up profile counts (including value profile data) by
889 /// a factor of (N / D).
891
892 /// Sort value profile data (per site) by count.
894 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
895 for (auto &SR : getValueSitesForKind(Kind))
896 SR.sortByCount();
897 }
898
899 /// Clear value data entries and edge counters.
900 void Clear() {
901 Counts.clear();
903 }
904
905 /// Clear value data entries
906 void clearValueData() { ValueData = nullptr; }
907
908 /// Compute the sums of all counts and store in Sum.
909 void accumulateCounts(CountSumOrPercent &Sum) const;
910
911 /// Compute the overlap b/w this IntrprofRecord and Other.
913 OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff);
914
915 /// Compute the overlap of value profile counts.
916 void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
917 OverlapStats &Overlap,
918 OverlapStats &FuncLevelOverlap);
919
924 };
928 };
930 uint64_t FirstCount = Counts[0];
931 if (FirstCount == (uint64_t)HotFunctionVal)
932 return PseudoHot;
933 if (FirstCount == (uint64_t)WarmFunctionVal)
934 return PseudoWarm;
935 return NotPseudo;
936 }
938 if (Kind == PseudoHot)
940 else if (Kind == PseudoWarm)
942 }
943
944private:
945 using ValueProfData = std::array<std::vector<InstrProfValueSiteRecord>,
946 IPVK_Last - IPVK_First + 1>;
947 std::unique_ptr<ValueProfData> ValueData;
948
950 getValueSitesForKind(uint32_t ValueKind) {
951 // Cast to /add/ const (should be an implicit_cast, ideally, if that's ever
952 // implemented in LLVM) to call the const overload of this function, then
953 // cast away the constness from the result.
954 auto AR = const_cast<const InstrProfRecord *>(this)->getValueSitesForKind(
955 ValueKind);
956 return MutableArrayRef(
957 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
958 }
959 ArrayRef<InstrProfValueSiteRecord>
960 getValueSitesForKind(uint32_t ValueKind) const {
961 if (!ValueData)
962 return std::nullopt;
963 assert(IPVK_First <= ValueKind && ValueKind <= IPVK_Last &&
964 "Unknown value kind!");
965 return (*ValueData)[ValueKind - IPVK_First];
966 }
967
968 std::vector<InstrProfValueSiteRecord> &
969 getOrCreateValueSitesForKind(uint32_t ValueKind) {
970 if (!ValueData)
971 ValueData = std::make_unique<ValueProfData>();
972 assert(IPVK_First <= ValueKind && ValueKind <= IPVK_Last &&
973 "Unknown value kind!");
974 return (*ValueData)[ValueKind - IPVK_First];
975 }
976
977 // Map indirect call target name hash to name string.
978 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
979 InstrProfSymtab *SymTab);
980
981 // Merge Value Profile data from Src record to this record for ValueKind.
982 // Scale merged value counts by \p Weight.
983 void mergeValueProfData(uint32_t ValkeKind, InstrProfRecord &Src,
984 uint64_t Weight,
985 function_ref<void(instrprof_error)> Warn);
986
987 // Scale up value profile data count by N (Numerator) / D (Denominator).
988 void scaleValueProfData(uint32_t ValueKind, uint64_t N, uint64_t D,
989 function_ref<void(instrprof_error)> Warn);
990};
991
995
996 // We reserve this bit as the flag for context sensitive profile record.
997 static const int CS_FLAG_IN_FUNC_HASH = 60;
998
1001 std::vector<uint64_t> Counts)
1004 std::vector<uint64_t> Counts,
1005 std::vector<uint8_t> BitmapBytes)
1007 Hash(Hash) {}
1008
1009 static bool hasCSFlagInHash(uint64_t FuncHash) {
1010 return ((FuncHash >> CS_FLAG_IN_FUNC_HASH) & 1);
1011 }
1012 static void setCSFlagInHash(uint64_t &FuncHash) {
1013 FuncHash |= ((uint64_t)1 << CS_FLAG_IN_FUNC_HASH);
1014 }
1015};
1016
1018 uint32_t NumValueKinds = 0;
1019 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1020 NumValueKinds += !(getValueSitesForKind(Kind).empty());
1021 return NumValueKinds;
1022}
1023
1025 uint32_t N = 0;
1026 for (const auto &SR : getValueSitesForKind(ValueKind))
1027 N += SR.ValueData.size();
1028 return N;
1029}
1030
1032 return getValueSitesForKind(ValueKind).size();
1033}
1034
1037 return getValueSitesForKind(ValueKind)[Site].ValueData;
1038}
1039
1040void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
1041 if (!NumValueSites)
1042 return;
1043 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
1044}
1045
1046// Include definitions for value profile data
1047#define INSTR_PROF_VALUE_PROF_DATA
1049
1052 ValueData, [](const InstrProfValueData &L, const InstrProfValueData &R) {
1053 return L.Count > R.Count;
1054 });
1055 // Now truncate
1056 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
1057 if (ValueData.size() > max_s)
1058 ValueData.resize(max_s);
1059}
1060
1061namespace IndexedInstrProf {
1062
1063enum class HashT : uint32_t {
1064 MD5,
1065 Last = MD5
1066};
1067
1069 switch (Type) {
1070 case HashT::MD5:
1071 return MD5Hash(K);
1072 }
1073 llvm_unreachable("Unhandled hash type");
1074}
1075
1076const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
1077
1079 // Version 1 is the first version. In this version, the value of
1080 // a key/value pair can only include profile data of a single function.
1081 // Due to this restriction, the number of block counters for a given
1082 // function is not recorded but derived from the length of the value.
1084 // The version 2 format supports recording profile data of multiple
1085 // functions which share the same key in one value field. To support this,
1086 // the number block counters is recorded as an uint64_t field right after the
1087 // function structural hash.
1089 // Version 3 supports value profile data. The value profile data is expected
1090 // to follow the block counter profile data.
1092 // In this version, profile summary data \c IndexedInstrProf::Summary is
1093 // stored after the profile header.
1095 // In this version, the frontend PGO stable hash algorithm defaults to V2.
1097 // In this version, the frontend PGO stable hash algorithm got fixed and
1098 // may produce hashes different from Version5.
1100 // An additional counter is added around logical operators.
1102 // An additional (optional) memory profile type is added.
1104 // Binary ids are added.
1106 // An additional (optional) temporal profile traces section is added.
1108 // An additional field is used for bitmap bytes.
1110 // VTable profiling, decision record and bitmap are modified for mcdc.
1112 // The current version is 12.
1113 CurrentVersion = INSTR_PROF_INDEX_VERSION
1116
1118
1120
1121// This structure defines the file header of the LLVM profile
1122// data file in indexed-format. Please update llvm/docs/InstrProfileFormat.rst
1123// as appropriate when updating the indexed profile format.
1124struct Header {
1126 // The lower 32 bits specify the version of the indexed profile.
1127 // The most significant 32 bits are reserved to specify the variant types of
1128 // the profile.
1130 uint64_t Unused = 0; // Becomes unused since version 4
1132 // This field records the offset of this hash table's metadata (i.e., the
1133 // number of buckets and entries), which follows right after the payload of
1134 // the entire hash table.
1140 // New fields should only be added at the end to ensure that the size
1141 // computation is correct. The methods below need to be updated to ensure that
1142 // the new field is read correctly.
1143
1144 // Reads a header struct from the buffer. Header fields are in machine native
1145 // endianness.
1146 static Expected<Header> readFromBuffer(const unsigned char *Buffer);
1147
1148 // Returns the size of the header in bytes for all valid fields based on the
1149 // version. I.e a older version header will return a smaller size.
1150 size_t size() const;
1151
1152 // Return the indexed profile version, i.e., the least significant 32 bits
1153 // in Header.Version.
1155};
1156
1157// Profile summary data recorded in the profile data file in indexed
1158// format. It is introduced in version 4. The summary data follows
1159// right after the profile file header.
1160struct Summary {
1161 struct Entry {
1162 uint64_t Cutoff; ///< The required percentile of total execution count.
1163 uint64_t
1164 MinBlockCount; ///< The minimum execution count for this percentile.
1165 uint64_t NumBlocks; ///< Number of blocks >= the minumum execution count.
1166 };
1167 // The field kind enumerator to assigned value mapping should remain
1168 // unchanged when a new kind is added or an old kind gets deleted in
1169 // the future.
1171 /// The total number of functions instrumented.
1173 /// Total number of instrumented blocks/edges.
1175 /// The maximal execution count among all functions.
1176 /// This field does not exist for profile data from IR based
1177 /// instrumentation.
1179 /// Max block count of the program.
1181 /// Max internal block count of the program (excluding entry blocks).
1183 /// The sum of all instrumented block counts.
1187
1188 // The number of summmary fields following the summary header.
1190 // The number of Cutoff Entries (Summary::Entry) following summary fields.
1192
1193 Summary() = delete;
1194 Summary(uint32_t Size) { memset(this, 0, Size); }
1195
1196 void operator delete(void *ptr) { ::operator delete(ptr); }
1197
1199 return sizeof(Summary) + NumCutoffEntries * sizeof(Entry) +
1200 NumSumFields * sizeof(uint64_t);
1201 }
1202
1204 return reinterpret_cast<const uint64_t *>(this + 1);
1205 }
1206
1208 return reinterpret_cast<uint64_t *>(this + 1);
1209 }
1210
1211 const Entry *getCutoffEntryBase() const {
1212 return reinterpret_cast<const Entry *>(
1214 }
1215
1217 return reinterpret_cast<Entry *>(&getSummaryDataBase()[NumSummaryFields]);
1218 }
1219
1221 return getSummaryDataBase()[K];
1222 }
1223
1225 getSummaryDataBase()[K] = V;
1226 }
1227
1228 const Entry &getEntry(uint32_t I) const { return getCutoffEntryBase()[I]; }
1229
1231 Entry &ER = getCutoffEntryBase()[I];
1232 ER.Cutoff = E.Cutoff;
1233 ER.MinBlockCount = E.MinCount;
1234 ER.NumBlocks = E.NumCounts;
1235 }
1236};
1237
1238inline std::unique_ptr<Summary> allocSummary(uint32_t TotalSize) {
1239 return std::unique_ptr<Summary>(new (::operator new(TotalSize))
1240 Summary(TotalSize));
1241}
1242
1243} // end namespace IndexedInstrProf
1244
1245namespace RawInstrProf {
1246
1247// Version 1: First version
1248// Version 2: Added value profile data section. Per-function control data
1249// struct has more fields to describe value profile information.
1250// Version 3: Compressed name section support. Function PGO name reference
1251// from control data struct is changed from raw pointer to Name's MD5 value.
1252// Version 4: ValueDataBegin and ValueDataSizes fields are removed from the
1253// raw header.
1254// Version 5: Bit 60 of FuncHash is reserved for the flag for the context
1255// sensitive records.
1256// Version 6: Added binary id.
1257// Version 7: Reorder binary id and include version in signature.
1258// Version 8: Use relative counter pointer.
1259// Version 9: Added relative bitmap bytes pointer and count used by MC/DC.
1260// Version 10: Added vtable, a new type of value profile data.
1261const uint64_t Version = INSTR_PROF_RAW_VERSION;
1262
1263template <class IntPtrT> inline uint64_t getMagic();
1264template <> inline uint64_t getMagic<uint64_t>() {
1265 return INSTR_PROF_RAW_MAGIC_64;
1266}
1267
1268template <> inline uint64_t getMagic<uint32_t>() {
1269 return INSTR_PROF_RAW_MAGIC_32;
1270}
1271
1272// Per-function profile data header/control structure.
1273// The definition should match the structure defined in
1274// compiler-rt/lib/profile/InstrProfiling.h.
1275// It should also match the synthesized type in
1276// Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
1277template <class IntPtrT> struct alignas(8) ProfileData {
1278#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
1280};
1281
1282template <class IntPtrT> struct alignas(8) VTableProfileData {
1283#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Type Name;
1285};
1286
1287// File header structure of the LLVM profile data in raw format.
1288// The definition should match the header referenced in
1289// compiler-rt/lib/profile/InstrProfilingFile.c and
1290// InstrProfilingBuffer.c.
1291struct Header {
1292#define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
1294};
1295
1296} // end namespace RawInstrProf
1297
1298// Create the variable for the profile file name.
1299void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput);
1300
1301// Whether to compress function names in profile records, and filenames in
1302// code coverage mappings. Used by the Instrumentation library and unit tests.
1303extern cl::opt<bool> DoInstrProfNameCompression;
1304
1305} // end namespace llvm
1306#endif // LLVM_PROFILEDATA_INSTRPROF_H
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
DXIL Finalize Linkage
This file defines the DenseMap class.
uint64_t Addr
std::string Name
uint64_t Size
This file implements a coalescing interval map for small objects.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Machine Check Debug Module
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
StringSet - A set-like wrapper for the StringMap.
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Base class for user error types.
Definition: Error.h:355
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: InstrProf.h:411
static std::pair< instrprof_error, std::string > take(Error E)
Consume an Error and return the raw enum value contained within it, and the optional error message.
Definition: InstrProf.h:423
const std::string & getMessage() const
Definition: InstrProf.h:418
static char ID
Definition: InstrProf.h:434
instrprof_error get() const
Definition: InstrProf.h:417
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: InstrProf.h:413
std::string message() const override
Return the error message as a string.
Definition: InstrProf.cpp:255
InstrProfError(instrprof_error Err, const Twine &ErrStr=Twine())
Definition: InstrProf.h:404
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition: InstrProf.h:458
static bool isExternalSymbol(const StringRef &Symbol)
True if Symbol is the value used to represent external symbols.
Definition: InstrProf.h:646
uint64_t getFunctionHashFromAddress(uint64_t Address)
Return a function's hash, or 0, if the function isn't in this SymTab.
Definition: InstrProf.cpp:656
Error addSymbolName(StringRef SymbolName)
Definition: InstrProf.h:578
std::vector< std::pair< uint64_t, uint64_t > > AddrHashMap
Definition: InstrProf.h:460
GlobalVariable * getGlobalVariable(uint64_t MD5Hash)
Return the global variable corresponding to md5 hash.
Definition: InstrProf.h:735
uint64_t getVTableHashFromAddress(uint64_t Address)
Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
Definition: InstrProf.cpp:650
StringRef getFuncOrVarName(uint64_t ValMD5Hash)
Return name of functions or global variables from the name's md5 hash value.
Definition: InstrProf.h:715
InstrProfSymtab & operator=(InstrProfSymtab &&)=delete
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
Definition: InstrProf.h:614
Error addVTableName(StringRef VTableName)
Adds VTableName as a known symbol, and inserts it to a map that tracks all vtable names.
Definition: InstrProf.h:600
void dumpNames(raw_ostream &OS) const
Dump the symbols in this table.
Definition: InstrProf.cpp:670
Function * getFunction(uint64_t FuncMD5Hash)
Return function from the name's md5 hash. Return nullptr if not found.
Definition: InstrProf.h:725
StringRef getNameData() const
Return the name section data.
Definition: InstrProf.h:658
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
Error addFuncName(StringRef FuncName)
The method name is kept since there are many callers.
Definition: InstrProf.h:596
void mapVTableAddress(uint64_t StartAddr, uint64_t EndAddr, uint64_t MD5Val)
Map the address range (i.e., [start_address, end_address)) of a variable to its names' MD5 hash.
Definition: InstrProf.h:621
Error initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames)
Initialize 'this' with the set of vtable names encoded in CompressedVTableNames.
Definition: InstrProf.cpp:600
const StringSet & getVTableNames() const
Definition: InstrProf.h:610
StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize)
Return function's PGO name from the function name's symbol address in the object file.
InstrProfSymtab & operator=(const InstrProfSymtab &)=delete
InstrProfSymtab(InstrProfSymtab &&)=delete
InstrProfSymtab(const InstrProfSymtab &)=delete
StringRef getFuncOrVarNameIfDefined(uint64_t ValMD5Hash)
Just like getFuncOrVarName, except that it will return literal string 'External Symbol' if the functi...
Definition: InstrProf.h:708
void insert(KeyT a, KeyT b, ValT y)
insert - Add a mapping of [a;b] to y, coalesce with adjacent intervals.
Definition: IntervalMap.h:1129
typename Sizer::Allocator Allocator
Definition: IntervalMap.h:962
Definition: MD5.h:41
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:307
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:23
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition: StringSet.h:38
ObjectFormatType
Definition: Triple.h:297
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
An efficient, type-erasing, non-owning reference to a callable.
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ValueKind
Value kinds.
std::unique_ptr< Summary > allocSummary(uint32_t TotalSize)
Definition: InstrProf.h:1238
uint64_t ComputeHash(StringRef K)
Definition: InstrProf.h:1119
const uint64_t Version
Definition: InstrProf.h:1115
const uint64_t Magic
Definition: InstrProf.h:1076
const HashT HashType
Definition: InstrProf.h:1117
uint64_t getMagic()
const uint64_t Version
Definition: InstrProf.h:1261
uint64_t getMagic< uint32_t >()
Definition: InstrProf.h:1268
uint64_t getMagic< uint64_t >()
Definition: InstrProf.h:1264
constexpr size_t NameSize
Definition: XCOFF.h:29
uint64_t MD5Hash(const FunctionId &Obj)
Definition: FunctionId.h:167
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void stable_sort(R &&Range)
Definition: STLExtras.h:2020
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition: InstrProf.h:92
std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Please use getIRPGOFuncName for LLVM IR instrumentation.
Definition: InstrProf.cpp:379
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
Definition: InstrProf.h:163
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
Definition: InstrProf.cpp:1423
std::string getIRPGOFuncName(const Function &F, bool InLTO=false)
Definition: InstrProf.cpp:368
std::error_code make_error_code(BitcodeError E)
StringRef getPGOFuncNameMetadataName()
Definition: InstrProf.h:304
StringRef getCoverageMappingVarName()
Return the name of a covarage mapping variable (internal linkage) for each instrumented source module...
Definition: InstrProf.h:121
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:977
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
Definition: InstrProf.h:104
cl::opt< bool > DoInstrProfNameCompression
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
Definition: InstrProf.cpp:410
void createPGONameMetadata(GlobalObject &GO, StringRef PGOName)
Create the PGOName metadata if a global object's PGO name is different from its mangled name.
Definition: InstrProf.cpp:1427
StringRef getInstrProfVTableNamesVarName()
Definition: InstrProf.h:116
std::pair< StringRef, StringRef > getParsedIRPGOName(StringRef IRPGOName)
Definition: InstrProf.cpp:403
auto unique(Range &&R, Predicate P)
Definition: STLExtras.h:2038
MDNode * getPGOFuncNameMetadata(const Function &F)
Return the PGOFuncName meta data associated with a function.
Definition: InstrProf.cpp:1403
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
Definition: InstrProf.h:98
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
Definition: InstrProf.h:129
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:236
uint64_t getInstrMaxCountValue()
Return the max count value. We reserver a few large values for special use.
Definition: InstrProf.h:66
bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
Definition: InstrProf.cpp:1431
std::string getPGOName(const GlobalVariable &V, bool InLTO=false)
Definition: InstrProf.cpp:395
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
Definition: InstrProf.h:158
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
Definition: InstrProf.h:107
StringRef getInstrProfCounterBiasVarName()
Definition: InstrProf.h:173
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
Definition: InstrProf.cpp:482
void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
Definition: InstrProf.cpp:1297
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable.
Definition: InstrProf.h:169
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Definition: InstrProf.h:138
Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
Definition: InstrProf.cpp:722
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
InstrProfSectKind
Definition: InstrProf.h:60
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
Definition: InstrProf.h:101
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
Definition: InstrProf.cpp:715
StringRef getInstrProfBitmapBiasVarName()
Definition: InstrProf.h:177
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition: InstrProf.h:182
SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
Definition: InstrProf.cpp:1365
StringRef getInstrProfValueProfMemOpFuncName()
Return the name profile runtime entry point to do memop size value profiling.
Definition: InstrProf.h:87
@ Other
Any other memory.
instrprof_error
Definition: InstrProf.h:352
InstrProfValueKind
Definition: InstrProf.h:275
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
Definition: InstrProf.h:150
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1961
const std::error_category & instrprof_category()
Definition: InstrProf.cpp:191
Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
Definition: InstrProf.cpp:732
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:1479
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
Definition: InstrProf.cpp:1502
Error collectGlobalObjectNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (names of global objects like functions or, virtual tables) NameStrs,...
Definition: InstrProf.cpp:677
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1856
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
Definition: InstrProf.h:81
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Definition: InstrProf.h:144
std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
Definition: InstrProf.cpp:422
StringRef getInstrProfNamesVarName()
Return the name of the variable holding the strings (possibly compressed) of all function's PGO names...
Definition: InstrProf.h:114
bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
Definition: InstrProf.cpp:440
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
Definition: InstrProf.cpp:1457
StringRef getPGONameMetadataName()
Definition: InstrProf.h:306
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
Definition: InstrProf.h:110
StringRef getInstrProfVTableVarPrefix()
Return the name prefix of variables containing virtual table profile data.
Definition: InstrProf.h:95
InstrProfKind
An enum describing the attributes of an instrumented profile.
Definition: InstrProf.h:329
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
std::array< double, IPVK_Last - IPVK_First+1 > ValueCounts
Definition: InstrProf.h:744
uint64_t getIndexedProfileVersion() const
Definition: InstrProf.cpp:1679
static Expected< Header > readFromBuffer(const unsigned char *Buffer)
Definition: InstrProf.cpp:1639
uint64_t Cutoff
The required percentile of total execution count.
Definition: InstrProf.h:1162
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
Definition: InstrProf.h:1165
uint64_t MinBlockCount
The minimum execution count for this percentile.
Definition: InstrProf.h:1164
const Entry * getCutoffEntryBase() const
Definition: InstrProf.h:1211
uint64_t get(SummaryFieldKind K) const
Definition: InstrProf.h:1220
void set(SummaryFieldKind K, uint64_t V)
Definition: InstrProf.h:1224
void setEntry(uint32_t I, const ProfileSummaryEntry &E)
Definition: InstrProf.h:1230
@ TotalNumFunctions
The total number of functions instrumented.
Definition: InstrProf.h:1172
@ TotalNumBlocks
Total number of instrumented blocks/edges.
Definition: InstrProf.h:1174
@ MaxFunctionCount
The maximal execution count among all functions.
Definition: InstrProf.h:1178
@ TotalBlockCount
The sum of all instrumented block counts.
Definition: InstrProf.h:1184
@ MaxBlockCount
Max block count of the program.
Definition: InstrProf.h:1180
@ MaxInternalBlockCount
Max internal block count of the program (excluding entry blocks).
Definition: InstrProf.h:1182
const uint64_t * getSummaryDataBase() const
Definition: InstrProf.h:1203
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
Definition: InstrProf.h:1198
const Entry & getEntry(uint32_t I) const
Definition: InstrProf.h:1228
Profiling information for a single function.
Definition: InstrProf.h:831
void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap of value profile counts.
Definition: InstrProf.cpp:791
std::vector< uint64_t > Counts
Definition: InstrProf.h:832
ArrayRef< InstrProfValueData > getValueArrayForSite(uint32_t ValueKind, uint32_t Site) const
Return the array of profiled values at Site.
Definition: InstrProf.h:1036
CountPseudoKind getCountPseudoKind() const
Definition: InstrProf.h:929
InstrProfRecord(std::vector< uint64_t > Counts)
Definition: InstrProf.h:836
void accumulateCounts(CountSumOrPercent &Sum) const
Compute the sums of all counts and store in Sum.
Definition: InstrProf.cpp:742
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition: InstrProf.h:1031
uint32_t getNumValueKinds() const
Return the number of value profile kinds with non-zero number of profile sites.
Definition: InstrProf.h:1017
void setPseudoCount(CountPseudoKind Kind)
Definition: InstrProf.h:937
InstrProfRecord(InstrProfRecord &&)=default
uint32_t getNumValueData(uint32_t ValueKind) const
Return the total number of ValueData for ValueKind.
Definition: InstrProf.h:1024
void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
Definition: InstrProf.cpp:920
void addValueData(uint32_t ValueKind, uint32_t Site, ArrayRef< InstrProfValueData > VData, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
Definition: InstrProf.cpp:1015
InstrProfRecord & operator=(const InstrProfRecord &RHS)
Definition: InstrProf.h:847
void clearValueData()
Clear value data entries.
Definition: InstrProf.h:906
InstrProfRecord(const InstrProfRecord &RHS)
Definition: InstrProf.h:841
InstrProfRecord(std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes)
Definition: InstrProf.h:837
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Definition: InstrProf.h:1040
void overlap(InstrProfRecord &Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff)
Compute the overlap b/w this IntrprofRecord and Other.
Definition: InstrProf.cpp:809
void sortValueData()
Sort value profile data (per site) by count.
Definition: InstrProf.h:893
std::vector< uint8_t > BitmapBytes
Definition: InstrProf.h:833
InstrProfRecord & operator=(InstrProfRecord &&)=default
void Clear()
Clear value data entries and edge counters.
Definition: InstrProf.h:900
void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by a factor of (N / D).
Definition: InstrProf.cpp:983
void sortByCount()
Sort ValueData Descending by Count.
Definition: InstrProf.h:1050
InstrProfValueSiteRecord(std::vector< InstrProfValueData > &&VD)
Definition: InstrProf.h:805
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition: InstrProf.h:809
std::vector< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition: InstrProf.h:802
void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight.
Definition: InstrProf.cpp:860
void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap b/w this record and Input record.
Definition: InstrProf.cpp:760
void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts by N (Numerator) / D (Denominator).
Definition: InstrProf.cpp:889
static bool hasCSFlagInHash(uint64_t FuncHash)
Definition: InstrProf.h:1009
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts)
Definition: InstrProf.h:1000
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes)
Definition: InstrProf.h:1003
static void setCSFlagInHash(uint64_t &FuncHash)
Definition: InstrProf.h:1012
static const int CS_FLAG_IN_FUNC_HASH
Definition: InstrProf.h:997
const std::string NameFilter
Definition: InstrProf.h:797
void addOneMismatch(const CountSumOrPercent &MismatchFunc)
Definition: InstrProf.cpp:1547
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
Definition: InstrProf.h:785
Error accumulateCounts(const std::string &BaseFilename, const std::string &TestFilename, bool IsCS)
Definition: InstrProf.cpp:1519
void dump(raw_fd_ostream &OS) const
Definition: InstrProf.cpp:1566
CountSumOrPercent Overlap
Definition: InstrProf.h:761
CountSumOrPercent Base
Definition: InstrProf.h:757
uint64_t FuncHash
Definition: InstrProf.h:768
void addOneUnique(const CountSumOrPercent &UniqueFunc)
Definition: InstrProf.cpp:1557
const std::string * BaseFilename
Definition: InstrProf.h:765
const std::string * TestFilename
Definition: InstrProf.h:766
void setFuncInfo(StringRef Name, uint64_t Hash)
Definition: InstrProf.h:775
CountSumOrPercent Unique
Definition: InstrProf.h:763
CountSumOrPercent Mismatch
Definition: InstrProf.h:762
StringRef FuncName
Definition: InstrProf.h:767
OverlapStatsLevel Level
Definition: InstrProf.h:764
OverlapStats(OverlapStatsLevel L=ProgramLevel)
Definition: InstrProf.h:771
CountSumOrPercent Test
Definition: InstrProf.h:759
An ordered list of functions identified by their NameRef found in INSTR_PROF_DATA.
Definition: InstrProf.h:383
static void createBPFunctionNodes(ArrayRef< TemporalProfTraceTy > Traces, std::vector< BPFunctionNode > &Nodes, bool RemoveOutlierUNs=true)
Use a set of temporal profile traces to create a list of balanced partitioning function nodes used by...
Definition: InstrProf.cpp:1034
std::vector< uint64_t > FunctionNameRefs
Definition: InstrProf.h:384
TemporalProfTraceTy(std::initializer_list< uint64_t > Trace={}, uint64_t Weight=1)
Definition: InstrProf.h:386
Function object to check whether the first component of a container supported by std::get (like std::...
Definition: STLExtras.h:1450