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