1//===- InstrProf.cpp - Instrumented profiling format support --------------===//
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// This file contains support for clang's instrumentation based PGO and
10// coverage.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ProfileData/InstrProf.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Config/config.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/GlobalValue.h"
24#include "llvm/IR/GlobalVariable.h"
25#include "llvm/IR/Instruction.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/MDBuilder.h"
28#include "llvm/IR/Metadata.h"
29#include "llvm/IR/Module.h"
30#include "llvm/IR/ProfDataUtils.h"
31#include "llvm/IR/Type.h"
32#include "llvm/ProfileData/InstrProfReader.h"
33#include "llvm/ProfileData/SampleProf.h"
34#include "llvm/Support/Casting.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/Compression.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/Endian.h"
40#include "llvm/Support/Error.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/LEB128.h"
43#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/SwapByteOrder.h"
46#include "llvm/Support/VirtualFileSystem.h"
47#include "llvm/Support/raw_ostream.h"
48#include "llvm/TargetParser/Triple.h"
49#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <memory>
55#include <string>
56#include <system_error>
57#include <type_traits>
58#include <utility>
59#include <vector>
60
61using namespace llvm;
62
63#define DEBUG_TYPE "instrprof"
64
65static cl::opt<bool> StaticFuncFullModulePrefix(
66 "static-func-full-module-prefix", cl::init(Val: true), cl::Hidden,
67 cl::desc("Use full module build paths in the profile counter names for "
68 "static functions."));
69
70// This option is tailored to users that have different top-level directory in
71// profile-gen and profile-use compilation. Users need to specific the number
72// of levels to strip. A value larger than the number of directories in the
73// source file will strip all the directory names and only leave the basename.
74//
75// Note current ThinLTO module importing for the indirect-calls assumes
76// the source directory name not being stripped. A non-zero option value here
77// can potentially prevent some inter-module indirect-call-promotions.
78static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
79 "static-func-strip-dirname-prefix", cl::init(Val: 0), cl::Hidden,
80 cl::desc("Strip specified level of directory name from source path in "
81 "the profile counter name for static functions."));
82
83static std::string getInstrProfErrString(instrprof_error Err,
84 const std::string &ErrMsg = "") {
85 std::string Msg;
86 raw_string_ostream OS(Msg);
87
88 switch (Err) {
89 case instrprof_error::success:
90 OS << "success";
91 break;
92 case instrprof_error::eof:
93 OS << "end of File";
94 break;
95 case instrprof_error::unrecognized_format:
96 OS << "unrecognized instrumentation profile encoding format";
97 break;
98 case instrprof_error::bad_magic:
99 OS << "invalid instrumentation profile data (bad magic)";
100 break;
101 case instrprof_error::bad_header:
102 OS << "invalid instrumentation profile data (file header is corrupt)";
103 break;
104 case instrprof_error::header_size_mismatch:
105 OS << "invalid instrumentation profile data (file is incomplete or header "
106 "is corrupt)";
107 break;
108 case instrprof_error::unsupported_version:
109 OS << "unsupported instrumentation profile format version";
110 break;
111 case instrprof_error::unsupported_hash_type:
112 OS << "unsupported instrumentation profile hash type";
113 break;
114 case instrprof_error::too_large:
115 OS << "too much profile data";
116 break;
117 case instrprof_error::truncated:
118 OS << "truncated profile data";
119 break;
120 case instrprof_error::malformed:
121 OS << "malformed instrumentation profile data";
122 break;
123 case instrprof_error::missing_correlation_info:
124 OS << "debug info/binary for correlation is required";
125 break;
126 case instrprof_error::unexpected_correlation_info:
127 OS << "debug info/binary for correlation is not necessary";
128 break;
129 case instrprof_error::unable_to_correlate_profile:
130 OS << "unable to correlate profile";
131 break;
132 case instrprof_error::invalid_prof:
133 OS << "invalid profile created. Please file a bug "
134 "at: " BUG_REPORT_URL
135 " and include the profraw files that caused this error.";
136 break;
137 case instrprof_error::unknown_function:
138 OS << "no profile data available for function";
139 break;
140 case instrprof_error::hash_mismatch:
141 OS << "function control flow change detected (hash mismatch)";
142 break;
143 case instrprof_error::count_mismatch:
144 OS << "function basic block count change detected (counter mismatch)";
145 break;
146 case instrprof_error::bitmap_mismatch:
147 OS << "function bitmap size change detected (bitmap size mismatch)";
148 break;
149 case instrprof_error::counter_overflow:
150 OS << "counter overflow";
151 break;
152 case instrprof_error::value_site_count_mismatch:
153 OS << "function value site count change detected (counter mismatch)";
154 break;
155 case instrprof_error::compress_failed:
156 OS << "failed to compress data (zlib)";
157 break;
158 case instrprof_error::uncompress_failed:
159 OS << "failed to uncompress data (zlib)";
160 break;
161 case instrprof_error::empty_raw_profile:
162 OS << "empty raw profile file";
163 break;
164 case instrprof_error::zlib_unavailable:
165 OS << "profile uses zlib compression but the profile reader was built "
166 "without zlib support";
167 break;
168 case instrprof_error::raw_profile_version_mismatch:
169 OS << "raw profile version mismatch";
170 break;
171 case instrprof_error::counter_value_too_large:
172 OS << "excessively large counter value suggests corrupted profile data";
173 break;
174 case instrprof_error::coverage_count_mismatch:
175 OS << "cannot merge single-byte and incrementing counter profiles";
176 break;
177 }
178
179 // If optional error message is not empty, append it to the message.
180 if (!ErrMsg.empty())
181 OS << ": " << ErrMsg;
182
183 return OS.str();
184}
185
186namespace {
187
188// FIXME: This class is only here to support the transition to llvm::Error. It
189// will be removed once this transition is complete. Clients should prefer to
190// deal with the Error value directly, rather than converting to error_code.
191class InstrProfErrorCategoryType : public std::error_category {
192 const char *name() const noexcept override { return "llvm.instrprof"; }
193
194 std::string message(int IE) const override {
195 return getInstrProfErrString(Err: static_cast<instrprof_error>(IE));
196 }
197};
198
199} // end anonymous namespace
200
201const std::error_category &llvm::instrprof_category() {
202 static InstrProfErrorCategoryType ErrorCategory;
203 return ErrorCategory;
204}
205
206namespace {
207
208const char *InstrProfSectNameCommon[] = {
209#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
210 SectNameCommon,
211#include "llvm/ProfileData/InstrProfData.inc"
212};
213
214const char *InstrProfSectNameCoff[] = {
215#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
216 SectNameCoff,
217#include "llvm/ProfileData/InstrProfData.inc"
218};
219
220const char *InstrProfSectNamePrefix[] = {
221#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
222 Prefix,
223#include "llvm/ProfileData/InstrProfData.inc"
224};
225
226} // namespace
227
228namespace llvm {
229
230cl::opt<bool> DoInstrProfNameCompression(
231 "enable-name-compression",
232 cl::desc("Enable name/filename string compression"), cl::init(Val: true));
233
234cl::opt<bool> EnableVTableValueProfiling(
235 "enable-vtable-value-profiling", cl::init(Val: false),
236 cl::desc("If true, the virtual table address will be instrumented to know "
237 "the types of a C++ pointer. The information is used in indirect "
238 "call promotion to do selective vtable-based comparison."));
239
240cl::opt<bool> EnableVTableProfileUse(
241 "enable-vtable-profile-use", cl::init(Val: false),
242 cl::desc("If ThinLTO and WPD is enabled and this option is true, vtable "
243 "profiles will be used by ICP pass for more efficient indirect "
244 "call sequence. If false, type profiles won't be used."));
245
246std::string getInstrProfSectionName(InstrProfSectKind IPSK,
247 Triple::ObjectFormatType OF,
248 bool AddSegmentInfo) {
249 std::string SectName;
250
251 if (OF == Triple::MachO && AddSegmentInfo)
252 SectName = InstrProfSectNamePrefix[IPSK];
253
254 if (OF == Triple::COFF)
255 SectName += InstrProfSectNameCoff[IPSK];
256 else
257 SectName += InstrProfSectNameCommon[IPSK];
258
259 if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
260 SectName += ",regular,live_support";
261
262 return SectName;
263}
264
265std::string InstrProfError::message() const {
266 return getInstrProfErrString(Err, ErrMsg: Msg);
267}
268
269char InstrProfError::ID = 0;
270
271ProfOStream::ProfOStream(raw_fd_ostream &FD)
272 : IsFDOStream(true), OS(FD), LE(FD, llvm::endianness::little) {}
273
274ProfOStream::ProfOStream(raw_string_ostream &STR)
275 : IsFDOStream(false), OS(STR), LE(STR, llvm::endianness::little) {}
276
277uint64_t ProfOStream::tell() const { return OS.tell(); }
278void ProfOStream::write(uint64_t V) { LE.write<uint64_t>(Val: V); }
279void ProfOStream::write32(uint32_t V) { LE.write<uint32_t>(Val: V); }
280void ProfOStream::writeByte(uint8_t V) { LE.write<uint8_t>(Val: V); }
281
282void ProfOStream::patch(ArrayRef<PatchItem> P) {
283 using namespace support;
284
285 if (IsFDOStream) {
286 raw_fd_ostream &FDOStream = static_cast<raw_fd_ostream &>(OS);
287 const uint64_t LastPos = FDOStream.tell();
288 for (const auto &K : P) {
289 FDOStream.seek(off: K.Pos);
290 for (uint64_t Elem : K.D)
291 write(V: Elem);
292 }
293 // Reset the stream to the last position after patching so that users
294 // don't accidentally overwrite data. This makes it consistent with
295 // the string stream below which replaces the data directly.
296 FDOStream.seek(off: LastPos);
297 } else {
298 raw_string_ostream &SOStream = static_cast<raw_string_ostream &>(OS);
299 std::string &Data = SOStream.str(); // with flush
300 for (const auto &K : P) {
301 for (int I = 0, E = K.D.size(); I != E; I++) {
302 uint64_t Bytes =
303 endian::byte_swap<uint64_t>(value: K.D[I], endian: llvm::endianness::little);
304 Data.replace(pos: K.Pos + I * sizeof(uint64_t), n1: sizeof(uint64_t),
305 s: (const char *)&Bytes, n2: sizeof(uint64_t));
306 }
307 }
308 }
309}
310
311std::string getPGOFuncName(StringRef Name, GlobalValue::LinkageTypes Linkage,
312 StringRef FileName,
313 [[maybe_unused]] uint64_t Version) {
314 // Value names may be prefixed with a binary '1' to indicate
315 // that the backend should not modify the symbols due to any platform
316 // naming convention. Do not include that '1' in the PGO profile name.
317 if (Name[0] == '\1')
318 Name = Name.substr(Start: 1);
319
320 std::string NewName = std::string(Name);
321 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
322 // For local symbols, prepend the main file name to distinguish them.
323 // Do not include the full path in the file name since there's no guarantee
324 // that it will stay the same, e.g., if the files are checked out from
325 // version control in different locations.
326 if (FileName.empty())
327 NewName = NewName.insert(pos: 0, s: "<unknown>:");
328 else
329 NewName = NewName.insert(pos1: 0, str: FileName.str() + ":");
330 }
331 return NewName;
332}
333
334// Strip NumPrefix level of directory name from PathNameStr. If the number of
335// directory separators is less than NumPrefix, strip all the directories and
336// leave base file name only.
337static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
338 uint32_t Count = NumPrefix;
339 uint32_t Pos = 0, LastPos = 0;
340 for (const auto &CI : PathNameStr) {
341 ++Pos;
342 if (llvm::sys::path::is_separator(value: CI)) {
343 LastPos = Pos;
344 --Count;
345 }
346 if (Count == 0)
347 break;
348 }
349 return PathNameStr.substr(Start: LastPos);
350}
351
352static StringRef getStrippedSourceFileName(const GlobalObject &GO) {
353 StringRef FileName(GO.getParent()->getSourceFileName());
354 uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
355 if (StripLevel < StaticFuncStripDirNamePrefix)
356 StripLevel = StaticFuncStripDirNamePrefix;
357 if (StripLevel)
358 FileName = stripDirPrefix(PathNameStr: FileName, NumPrefix: StripLevel);
359 return FileName;
360}
361
362// The PGO name has the format [<filepath>;]<mangled-name> where <filepath>; is
363// provided if linkage is local and is used to discriminate possibly identical
364// mangled names. ";" is used because it is unlikely to be found in either
365// <filepath> or <mangled-name>.
366//
367// Older compilers used getPGOFuncName() which has the format
368// [<filepath>:]<mangled-name>. This caused trouble for Objective-C functions
369// which commonly have :'s in their names. We still need to compute this name to
370// lookup functions from profiles built by older compilers.
371static std::string
372getIRPGONameForGlobalObject(const GlobalObject &GO,
373 GlobalValue::LinkageTypes Linkage,
374 StringRef FileName) {
375 return GlobalValue::getGlobalIdentifier(Name: GO.getName(), Linkage, FileName);
376}
377
378// Returns the PGO object name. This function has some special handling
379// when called in LTO optimization. In LTO mode (when InLTO is true),
380// LTO's internalization privatizes many global linkage symbols, so we assume
381// non-internal linkage without a source prefix.
382std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO) {
383 if (!InLTO) {
384 auto FileName = getStrippedSourceFileName(GO);
385 return getIRPGONameForGlobalObject(GO, Linkage: GO.getLinkage(), FileName);
386 }
387
388 return getIRPGONameForGlobalObject(GO, Linkage: GlobalValue::ExternalLinkage, FileName: "");
389}
390
391// Please use getIRPGOObjectName for LLVM IR instrumentation. This function is
392// for front-end (Clang, etc) instrumentation.
393// The implementation is kept for profile matching from older profiles.
394// This is similar to `getIRPGOObjectName` except that this function calls
395// 'getPGOFuncName' to get a name and `getIRPGOObjectName` calls
396// 'getIRPGONameForGlobalObject'. See the difference between two callees in the
397// comments of `getIRPGONameForGlobalObject`.
398std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
399 if (!InLTO) {
400 auto FileName = getStrippedSourceFileName(GO: F);
401 return getPGOFuncName(Name: F.getName(), Linkage: F.getLinkage(), FileName, Version);
402 }
403
404 return getPGOFuncName(Name: F.getName(), Linkage: GlobalValue::ExternalLinkage, FileName: "");
405}
406
407// See getIRPGOObjectName() for a discription of the format.
408std::pair<StringRef, StringRef> getParsedIRPGOName(StringRef IRPGOName) {
409 auto [FileName, MangledName] = IRPGOName.split(Separator: GlobalIdentifierDelimiter);
410 if (MangledName.empty())
411 return std::make_pair(x: StringRef(), y&: IRPGOName);
412 return std::make_pair(x&: FileName, y&: MangledName);
413}
414
415StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
416 if (FileName.empty())
417 return PGOFuncName;
418 // Drop the file name including ':' or ';'. See getIRPGONameForGlobalObject as
419 // well.
420 if (PGOFuncName.starts_with(Prefix: FileName))
421 PGOFuncName = PGOFuncName.drop_front(N: FileName.size() + 1);
422 return PGOFuncName;
423}
424
425// \p FuncName is the string used as profile lookup key for the function. A
426// symbol is created to hold the name. Return the legalized symbol name.
427std::string getPGOFuncNameVarName(StringRef FuncName,
428 GlobalValue::LinkageTypes Linkage) {
429 std::string VarName = std::string(getInstrProfNameVarPrefix());
430 VarName += FuncName;
431
432 if (!GlobalValue::isLocalLinkage(Linkage))
433 return VarName;
434
435 // Now fix up illegal chars in local VarName that may upset the assembler.
436 const char InvalidChars[] = "-:;<>/\"'";
437 size_t FoundPos = VarName.find_first_of(s: InvalidChars);
438 while (FoundPos != std::string::npos) {
439 VarName[FoundPos] = '_';
440 FoundPos = VarName.find_first_of(s: InvalidChars, pos: FoundPos + 1);
441 }
442 return VarName;
443}
444
445bool isGPUProfTarget(const Module &M) {
446 const Triple &T = M.getTargetTriple();
447 return T.isGPU();
448}
449
450void setPGOFuncVisibility(Module &M, GlobalVariable *FuncNameVar) {
451 // Hide the symbol so that we correctly get a copy for each executable.
452 if (!GlobalValue::isLocalLinkage(Linkage: FuncNameVar->getLinkage()))
453 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
454}
455
456GlobalVariable *createPGOFuncNameVar(Module &M,
457 GlobalValue::LinkageTypes Linkage,
458 StringRef PGOFuncName) {
459 // We generally want to match the function's linkage, but available_externally
460 // and extern_weak both have the wrong semantics, and anything that doesn't
461 // need to link across compilation units doesn't need to be visible at all.
462 if (Linkage == GlobalValue::ExternalWeakLinkage)
463 Linkage = GlobalValue::LinkOnceAnyLinkage;
464 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
465 Linkage = GlobalValue::LinkOnceODRLinkage;
466 else if (Linkage == GlobalValue::InternalLinkage ||
467 Linkage == GlobalValue::ExternalLinkage)
468 Linkage = GlobalValue::PrivateLinkage;
469
470 auto *Value =
471 ConstantDataArray::getString(Context&: M.getContext(), Initializer: PGOFuncName, AddNull: false);
472 auto *FuncNameVar =
473 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
474 getPGOFuncNameVarName(FuncName: PGOFuncName, Linkage));
475
476 setPGOFuncVisibility(M, FuncNameVar);
477 return FuncNameVar;
478}
479
480GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
481 return createPGOFuncNameVar(M&: *F.getParent(), Linkage: F.getLinkage(), PGOFuncName);
482}
483
484Error InstrProfSymtab::create(Module &M, bool InLTO, bool AddCanonical,
485 bool KeyImportedAliasesByAliasGUID) {
486 for (Function &F : M) {
487 // Function may not have a name: like using asm("") to overwrite the name.
488 // Ignore in this case.
489 if (!F.hasName())
490 continue;
491 auto IRPGOFuncName = getIRPGOObjectName(GO: F, InLTO);
492 if (Error E = addFuncWithName(F, PGOFuncName: IRPGOFuncName, AddCanonical,
493 KeyImportedAliasesByAliasGUID))
494 return E;
495 // Also use getPGOFuncName() so that we can find records from older profiles
496 auto PGOFuncName = getPGOFuncName(F, InLTO);
497 if (PGOFuncName != IRPGOFuncName)
498 if (Error E = addFuncWithName(F, PGOFuncName, AddCanonical,
499 KeyImportedAliasesByAliasGUID))
500 return E;
501 }
502
503 for (GlobalVariable &G : M.globals()) {
504 if (!G.hasName() || !G.hasMetadata(KindID: LLVMContext::MD_type))
505 continue;
506 if (Error E = addVTableWithName(V&: G, PGOVTableName: getIRPGOObjectName(GO: G, InLTO)))
507 return E;
508 }
509
510 // Place definitions before declarations so finalizeSymtab()'s stable_sort
511 // keeps definitions (e.g. @foo.cfi) ahead of jump-table declarations (@foo)
512 // when they share a canonical name or GUID.
513 std::stable_partition(
514 first: MD5FuncMap.begin(), last: MD5FuncMap.end(),
515 pred: [](const auto &Entry) { return !Entry.second->isDeclaration(); });
516
517 Sorted = false;
518 finalizeSymtab();
519 return Error::success();
520}
521
522Error InstrProfSymtab::addVTableWithName(GlobalVariable &VTable,
523 StringRef VTablePGOName) {
524 // Key each name by its own hash, so profiles that recorded that name can find
525 // the vtable.
526 auto NameToGUIDMap = [&](StringRef Name) -> Error {
527 if (Error E = addSymbolName(SymbolName: Name))
528 return E;
529
530 bool Inserted = true;
531 std::tie(args: std::ignore, args&: Inserted) = MD5VTableMap.try_emplace(
532 Key: GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: Name), Args: &VTable);
533 if (!Inserted)
534 LLVM_DEBUG(dbgs() << "GUID conflict within one module");
535 return Error::success();
536 };
537 if (Error E = NameToGUIDMap(VTablePGOName))
538 return E;
539
540 // Also key the vtable by its GUID, so it can still be found if LTO has
541 // renamed it. See addFuncWithName.
542 if (auto GUID = VTable.getGUIDIfAssigned();
543 GUID &&
544 *GUID != GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: VTablePGOName))
545 MD5VTableMap.try_emplace(Key: *GUID, Args: &VTable);
546
547 StringRef CanonicalName = getCanonicalName(PGOName: VTablePGOName);
548 if (!CanonicalName.empty() && CanonicalName != VTablePGOName)
549 return NameToGUIDMap(CanonicalName);
550
551 return Error::success();
552}
553
554Error readAndDecodeStrings(StringRef NameStrings,
555 std::function<Error(StringRef)> NameCallback) {
556 const uint8_t *P = NameStrings.bytes_begin();
557 const uint8_t *EndP = NameStrings.bytes_end();
558 while (P < EndP) {
559 uint32_t N;
560 uint64_t UncompressedSize = decodeULEB128(p: P, n: &N);
561 P += N;
562 uint64_t CompressedSize = decodeULEB128(p: P, n: &N);
563 P += N;
564 const bool IsCompressed = (CompressedSize != 0);
565 SmallVector<uint8_t, 128> UncompressedNameStrings;
566 StringRef NameStrings;
567 if (IsCompressed) {
568 if (!llvm::compression::zlib::isAvailable())
569 return make_error<InstrProfError>(Args: instrprof_error::zlib_unavailable);
570
571 if (Error E = compression::zlib::decompress(Input: ArrayRef(P, CompressedSize),
572 Output&: UncompressedNameStrings,
573 UncompressedSize)) {
574 consumeError(Err: std::move(E));
575 return make_error<InstrProfError>(Args: instrprof_error::uncompress_failed);
576 }
577 P += CompressedSize;
578 NameStrings = toStringRef(Input: UncompressedNameStrings);
579 } else {
580 NameStrings =
581 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
582 P += UncompressedSize;
583 }
584 // Now parse the name strings.
585 SmallVector<StringRef, 0> Names;
586 NameStrings.split(A&: Names, Separator: getInstrProfNameSeparator());
587 for (StringRef &Name : Names)
588 if (Error E = NameCallback(Name))
589 return E;
590
591 while (P < EndP && *P == 0)
592 P++;
593 }
594 return Error::success();
595}
596
597Error InstrProfSymtab::create(StringRef NameStrings) {
598 return readAndDecodeStrings(NameStrings,
599 NameCallback: [&](StringRef S) { return addFuncName(FuncName: S); });
600}
601
602Error InstrProfSymtab::create(StringRef FuncNameStrings,
603 StringRef VTableNameStrings) {
604 if (Error E = readAndDecodeStrings(
605 NameStrings: FuncNameStrings, NameCallback: [&](StringRef S) { return addFuncName(FuncName: S); }))
606 return E;
607
608 return readAndDecodeStrings(NameStrings: VTableNameStrings,
609 NameCallback: [&](StringRef S) { return addVTableName(VTableName: S); });
610}
611
612Error InstrProfSymtab::initVTableNamesFromCompressedStrings(
613 StringRef CompressedVTableStrings) {
614 return readAndDecodeStrings(NameStrings: CompressedVTableStrings,
615 NameCallback: [&](StringRef S) { return addVTableName(VTableName: S); });
616}
617
618StringRef InstrProfSymtab::getCanonicalName(StringRef PGOName) {
619 // In ThinLTO, local function may have been promoted to global and have
620 // suffix ".llvm." added to the function name. We need to add the
621 // stripped function name to the symbol table so that we can find a match
622 // from profile.
623 //
624 // ".__uniq." suffix is used to differentiate internal linkage functions in
625 // different modules and should be kept. This is the only suffix with the
626 // pattern ".xxx" which is kept before matching; ".cfi", ".llvm.", and
627 // ".part." will be stripped.
628 //
629 // Leverage the common canonicalization logic from FunctionSamples. Instead of
630 // removing all suffixes except ".__uniq.", explicitly specify the ones to be
631 // removed. This avoids the issue of colliding the canonical names of
632 // coroutine function with its await suspend wrappers or with its post-split
633 // clones. i.e. coro function foo, its wrappers
634 // (foo.__await_suspend_wrapper__init, and foo.__await_suspend_wrapper__final)
635 // and its post-split clones (foo.resume, foo.cleanup) are all canonicalized
636 // to "foo" otherwise, which can make the symtab lookup return unexpected
637 // result.
638 const SmallVector<StringRef> SuffixesToRemove{FunctionSamples::CfiSuffix,
639 FunctionSamples::LLVMSuffix,
640 FunctionSamples::PartSuffix};
641 return FunctionSamples::getCanonicalFnName(FnName: PGOName, Suffixes: SuffixesToRemove);
642}
643
644Error InstrProfSymtab::addFuncWithName(Function &F, StringRef PGOFuncName,
645 bool AddCanonical,
646 bool KeyImportedAliasesByAliasGUID) {
647 // Key each name by its own hash, so profiles that recorded that name can find
648 // the function. This is called once per name, e.g. a second time with the
649 // deprecated PGO name, for profiles from older compilers.
650 auto NameToGUIDMap = [&](StringRef Name) -> Error {
651 if (Error E = addFuncName(FuncName: Name))
652 return E;
653 MD5FuncMap.emplace_back(args: Function::getGUIDAssumingExternalLinkage(GlobalName: Name), args: &F);
654 return Error::success();
655 };
656 if (Error E = NameToGUIDMap(PGOFuncName))
657 return E;
658
659 // Also key the function by its GUID, if it has one. The GUID is the hash of
660 // the function's name when the GUID was assigned, so this still finds the
661 // function if LTO has renamed it since. This used to need !PGOFuncName.
662 // If requested, key an imported copy of an alias by the alias's GUID instead
663 // of the aliasee's GUID retained in its !guid metadata (see create()).
664 std::optional<GlobalValue::GUID> GUID;
665 MDNode *AliasGUIDMD = KeyImportedAliasesByAliasGUID
666 ? F.getMetadata(Kind: "thinlto_alias_guid")
667 : nullptr;
668 if (AliasGUIDMD)
669 GUID = mdconst::extract<ConstantInt>(MD: AliasGUIDMD->getOperand(I: 0))
670 ->getZExtValue();
671 else
672 GUID = F.getGUIDIfAssigned();
673 if (GUID && *GUID != Function::getGUIDAssumingExternalLinkage(GlobalName: PGOFuncName))
674 MD5FuncMap.emplace_back(args&: *GUID, args: &F);
675
676 if (!AddCanonical)
677 return Error::success();
678
679 StringRef CanonicalFuncName = getCanonicalName(PGOName: PGOFuncName);
680 if (!CanonicalFuncName.empty() && CanonicalFuncName != PGOFuncName)
681 return NameToGUIDMap(CanonicalFuncName);
682
683 return Error::success();
684}
685
686uint64_t InstrProfSymtab::getVTableHashFromAddress(uint64_t Address) const {
687 // Given a runtime address, look up the hash value in the interval map, and
688 // fallback to value 0 if a hash value is not found.
689 return VTableAddrMap.lookup(x: Address, NotFound: 0);
690}
691
692uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) const {
693 finalizeSymtab();
694 auto It = partition_point(Range&: AddrToMD5Map, P: [=](std::pair<uint64_t, uint64_t> A) {
695 return A.first < Address;
696 });
697 // Raw function pointer collected by value profiler may be from
698 // external functions that are not instrumented. They won't have
699 // mapping data to be used by the deserializer. Force the value to
700 // be 0 in this case.
701 if (It != AddrToMD5Map.end() && It->first == Address)
702 return (uint64_t)It->second;
703 return 0;
704}
705
706void InstrProfSymtab::dumpNames(raw_ostream &OS) const {
707 SmallVector<StringRef, 0> Sorted(NameTab.keys());
708 llvm::sort(C&: Sorted);
709 for (StringRef S : Sorted)
710 OS << S << '\n';
711}
712
713Error collectGlobalObjectNameStrings(ArrayRef<std::string> NameStrs,
714 bool DoCompression, std::string &Result) {
715 assert(!NameStrs.empty() && "No name data to emit");
716
717 uint8_t Header[20], *P = Header;
718 std::string UncompressedNameStrings =
719 join(Begin: NameStrs.begin(), End: NameStrs.end(), Separator: getInstrProfNameSeparator());
720
721 assert(StringRef(UncompressedNameStrings)
722 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
723 "PGO name is invalid (contains separator token)");
724
725 unsigned EncLen = encodeULEB128(Value: UncompressedNameStrings.length(), p: P);
726 P += EncLen;
727
728 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
729 EncLen = encodeULEB128(Value: CompressedLen, p: P);
730 P += EncLen;
731 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
732 unsigned HeaderLen = P - &Header[0];
733 Result.append(s: HeaderStr, n: HeaderLen);
734 Result += InputStr;
735 return Error::success();
736 };
737
738 if (!DoCompression) {
739 return WriteStringToResult(0, UncompressedNameStrings);
740 }
741
742 SmallVector<uint8_t, 128> CompressedNameStrings;
743 compression::zlib::compress(Input: arrayRefFromStringRef(Input: UncompressedNameStrings),
744 CompressedBuffer&: CompressedNameStrings,
745 Level: compression::zlib::BestSizeCompression);
746
747 return WriteStringToResult(CompressedNameStrings.size(),
748 toStringRef(Input: CompressedNameStrings));
749}
750
751StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
752 auto *Arr = cast<ConstantDataArray>(Val: NameVar->getInitializer());
753 StringRef NameStr =
754 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
755 return NameStr;
756}
757
758Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
759 std::string &Result, bool DoCompression) {
760 std::vector<std::string> NameStrs;
761 for (auto *NameVar : NameVars) {
762 NameStrs.push_back(x: std::string(getPGOFuncNameVarInitializer(NameVar)));
763 }
764 return collectGlobalObjectNameStrings(
765 NameStrs, DoCompression: compression::zlib::isAvailable() && DoCompression, Result);
766}
767
768Error collectVTableStrings(ArrayRef<GlobalVariable *> VTables,
769 std::string &Result, bool DoCompression) {
770 std::vector<std::string> VTableNameStrs;
771 for (auto *VTable : VTables)
772 VTableNameStrs.push_back(x: getIRPGOObjectName(GO: *VTable));
773 return collectGlobalObjectNameStrings(
774 NameStrs: VTableNameStrs, DoCompression: compression::zlib::isAvailable() && DoCompression,
775 Result);
776}
777
778void InstrProfRecord::accumulateCounts(CountSumOrPercent &Sum) const {
779 uint64_t FuncSum = 0;
780 Sum.NumEntries += Counts.size();
781 for (uint64_t Count : Counts)
782 FuncSum += Count;
783 Sum.CountSum += FuncSum;
784
785 for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
786 uint64_t KindSum = 0;
787 uint32_t NumValueSites = getNumValueSites(ValueKind: VK);
788 for (size_t I = 0; I < NumValueSites; ++I) {
789 for (const auto &V : getValueArrayForSite(ValueKind: VK, Site: I))
790 KindSum += V.Count;
791 }
792 Sum.ValueCounts[VK] += KindSum;
793 }
794}
795
796void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord &Input,
797 uint32_t ValueKind,
798 OverlapStats &Overlap,
799 OverlapStats &FuncLevelOverlap) {
800 this->sortByTargetValues();
801 Input.sortByTargetValues();
802 double Score = 0.0f, FuncLevelScore = 0.0f;
803 auto I = ValueData.begin();
804 auto IE = ValueData.end();
805 auto J = Input.ValueData.begin();
806 auto JE = Input.ValueData.end();
807 while (I != IE && J != JE) {
808 if (I->Value == J->Value) {
809 Score += OverlapStats::score(Val1: I->Count, Val2: J->Count,
810 Sum1: Overlap.Base.ValueCounts[ValueKind],
811 Sum2: Overlap.Test.ValueCounts[ValueKind]);
812 FuncLevelScore += OverlapStats::score(
813 Val1: I->Count, Val2: J->Count, Sum1: FuncLevelOverlap.Base.ValueCounts[ValueKind],
814 Sum2: FuncLevelOverlap.Test.ValueCounts[ValueKind]);
815 ++I;
816 } else if (I->Value < J->Value) {
817 ++I;
818 continue;
819 }
820 ++J;
821 }
822 Overlap.Overlap.ValueCounts[ValueKind] += Score;
823 FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
824}
825
826// Return false on mismatch.
827void InstrProfRecord::overlapValueProfData(uint32_t ValueKind,
828 InstrProfRecord &Other,
829 OverlapStats &Overlap,
830 OverlapStats &FuncLevelOverlap) {
831 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
832 assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
833 if (!ThisNumValueSites)
834 return;
835
836 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
837 getOrCreateValueSitesForKind(ValueKind);
838 MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
839 Other.getValueSitesForKind(ValueKind);
840 for (uint32_t I = 0; I < ThisNumValueSites; I++)
841 ThisSiteRecords[I].overlap(Input&: OtherSiteRecords[I], ValueKind, Overlap,
842 FuncLevelOverlap);
843}
844
845void InstrProfRecord::overlap(InstrProfRecord &Other, OverlapStats &Overlap,
846 OverlapStats &FuncLevelOverlap,
847 uint64_t ValueCutoff) {
848 // FuncLevel CountSum for other should already computed and nonzero.
849 assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
850 accumulateCounts(Sum&: FuncLevelOverlap.Base);
851 bool Mismatch = (Counts.size() != Other.Counts.size());
852
853 // Check if the value profiles mismatch.
854 if (!Mismatch) {
855 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
856 uint32_t ThisNumValueSites = getNumValueSites(ValueKind: Kind);
857 uint32_t OtherNumValueSites = Other.getNumValueSites(ValueKind: Kind);
858 if (ThisNumValueSites != OtherNumValueSites) {
859 Mismatch = true;
860 break;
861 }
862 }
863 }
864 if (Mismatch) {
865 Overlap.addOneMismatch(MismatchFunc: FuncLevelOverlap.Test);
866 return;
867 }
868
869 // Compute overlap for value counts.
870 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
871 overlapValueProfData(ValueKind: Kind, Other, Overlap, FuncLevelOverlap);
872
873 double Score = 0.0;
874 uint64_t MaxCount = 0;
875 // Compute overlap for edge counts.
876 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
877 Score += OverlapStats::score(Val1: Counts[I], Val2: Other.Counts[I],
878 Sum1: Overlap.Base.CountSum, Sum2: Overlap.Test.CountSum);
879 MaxCount = std::max(a: Other.Counts[I], b: MaxCount);
880 }
881 Overlap.Overlap.CountSum += Score;
882 Overlap.Overlap.NumEntries += 1;
883
884 if (MaxCount >= ValueCutoff) {
885 double FuncScore = 0.0;
886 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
887 FuncScore += OverlapStats::score(Val1: Counts[I], Val2: Other.Counts[I],
888 Sum1: FuncLevelOverlap.Base.CountSum,
889 Sum2: FuncLevelOverlap.Test.CountSum);
890 FuncLevelOverlap.Overlap.CountSum = FuncScore;
891 FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
892 FuncLevelOverlap.Valid = true;
893 }
894}
895
896void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
897 uint64_t Weight,
898 function_ref<void(instrprof_error)> Warn) {
899 this->sortByTargetValues();
900 Input.sortByTargetValues();
901 auto I = ValueData.begin();
902 auto IE = ValueData.end();
903 std::vector<InstrProfValueData> Merged;
904 Merged.reserve(n: std::max(a: ValueData.size(), b: Input.ValueData.size()));
905 for (const InstrProfValueData &J : Input.ValueData) {
906 while (I != IE && I->Value < J.Value) {
907 Merged.push_back(x: *I);
908 ++I;
909 }
910 if (I != IE && I->Value == J.Value) {
911 bool Overflowed;
912 I->Count = SaturatingMultiplyAdd(X: J.Count, Y: Weight, A: I->Count, ResultOverflowed: &Overflowed);
913 if (Overflowed)
914 Warn(instrprof_error::counter_overflow);
915 Merged.push_back(x: *I);
916 ++I;
917 continue;
918 }
919 Merged.push_back(x: J);
920 }
921 Merged.insert(position: Merged.end(), first: I, last: IE);
922 ValueData = std::move(Merged);
923}
924
925void InstrProfValueSiteRecord::scale(uint64_t N, uint64_t D,
926 function_ref<void(instrprof_error)> Warn) {
927 for (InstrProfValueData &I : ValueData) {
928 bool Overflowed;
929 I.Count = SaturatingMultiply(X: I.Count, Y: N, ResultOverflowed: &Overflowed) / D;
930 if (Overflowed)
931 Warn(instrprof_error::counter_overflow);
932 }
933}
934
935// Merge Value Profile data from Src record to this record for ValueKind.
936// Scale merged value counts by \p Weight.
937void InstrProfRecord::mergeValueProfData(
938 uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
939 function_ref<void(instrprof_error)> Warn) {
940 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
941 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
942 if (ThisNumValueSites != OtherNumValueSites) {
943 Warn(instrprof_error::value_site_count_mismatch);
944 return;
945 }
946 if (!ThisNumValueSites)
947 return;
948 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
949 getOrCreateValueSitesForKind(ValueKind);
950 MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
951 Src.getValueSitesForKind(ValueKind);
952 for (uint32_t I = 0; I < ThisNumValueSites; I++)
953 ThisSiteRecords[I].merge(Input&: OtherSiteRecords[I], Weight, Warn);
954}
955
956void InstrProfRecord::computeBlockUniformity() {
957 if (UniformCounts.empty())
958 return;
959
960 if (UniformCounts.size() != Counts.size()) {
961 UniformityBits.clear();
962 return;
963 }
964
965 UniformityBits.assign(n: (Counts.size() + 7) / 8, val: 0xFF);
966 for (size_t I = 0, E = Counts.size(); I < E; ++I) {
967 uint64_t TotalCount = Counts[I];
968 uint64_t UniformCount = UniformCounts[I];
969 uint64_t MinUniformCount = TotalCount - TotalCount / 10;
970 bool IsUniform = UniformCount >= MinUniformCount;
971 if (!IsUniform)
972 UniformityBits[I / 8] &= ~(1 << (I % 8));
973 }
974}
975
976static void mergeUniformityBits(std::vector<uint8_t> &Dst,
977 ArrayRef<uint8_t> Src) {
978 if (Dst.empty()) {
979 Dst.assign(first: Src.begin(), last: Src.end());
980 return;
981 }
982 if (Src.empty())
983 return;
984
985 if (Dst.size() != Src.size()) {
986 Dst.clear();
987 return;
988 }
989
990 for (size_t I = 0, E = Src.size(); I < E; ++I)
991 Dst[I] &= Src[I];
992}
993
994void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
995 function_ref<void(instrprof_error)> Warn) {
996 // If the number of counters doesn't match we either have bad data
997 // or a hash collision.
998 if (Counts.size() != Other.Counts.size()) {
999 Warn(instrprof_error::count_mismatch);
1000 return;
1001 }
1002
1003 computeBlockUniformity();
1004 Other.computeBlockUniformity();
1005
1006 // Special handling of the first count as the PseudoCount.
1007 CountPseudoKind OtherKind = Other.getCountPseudoKind();
1008 CountPseudoKind ThisKind = getCountPseudoKind();
1009 if (OtherKind != NotPseudo || ThisKind != NotPseudo) {
1010 // We don't allow the merge of a profile with pseudo counts and
1011 // a normal profile (i.e. without pesudo counts).
1012 // Profile supplimenation should be done after the profile merge.
1013 if (OtherKind == NotPseudo || ThisKind == NotPseudo) {
1014 Warn(instrprof_error::count_mismatch);
1015 return;
1016 }
1017 if (OtherKind == PseudoHot || ThisKind == PseudoHot)
1018 setPseudoCount(PseudoHot);
1019 else
1020 setPseudoCount(PseudoWarm);
1021 return;
1022 }
1023 OffloadDeviceWaveSize = Other.OffloadDeviceWaveSize;
1024 bool HasUniformCounts = !UniformCounts.empty();
1025 bool OtherHasUniformCounts = !Other.UniformCounts.empty();
1026 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
1027 bool Overflowed;
1028 uint64_t Value =
1029 SaturatingMultiplyAdd(X: Other.Counts[I], Y: Weight, A: Counts[I], ResultOverflowed: &Overflowed);
1030 if (Value > getInstrMaxCountValue()) {
1031 Value = getInstrMaxCountValue();
1032 Overflowed = true;
1033 }
1034 Counts[I] = Value;
1035 if (Overflowed)
1036 Warn(instrprof_error::counter_overflow);
1037 }
1038
1039 if (HasUniformCounts && OtherHasUniformCounts) {
1040 if (UniformCounts.size() != Other.UniformCounts.size()) {
1041 UniformCounts.clear();
1042 UniformityBits.clear();
1043 } else {
1044 for (size_t I = 0, E = Other.UniformCounts.size(); I < E; ++I) {
1045 bool Overflowed;
1046 UniformCounts[I] = SaturatingMultiplyAdd(X: Other.UniformCounts[I], Y: Weight,
1047 A: UniformCounts[I], ResultOverflowed: &Overflowed);
1048 if (UniformCounts[I] > getInstrMaxCountValue()) {
1049 UniformCounts[I] = getInstrMaxCountValue();
1050 Overflowed = true;
1051 }
1052 if (Overflowed)
1053 Warn(instrprof_error::counter_overflow);
1054 }
1055 computeBlockUniformity();
1056 }
1057 } else {
1058 UniformCounts.clear();
1059 mergeUniformityBits(Dst&: UniformityBits, Src: Other.UniformityBits);
1060 }
1061
1062 // If the number of bitmap bytes doesn't match we either have bad data
1063 // or a hash collision.
1064 if (BitmapBytes.size() != Other.BitmapBytes.size()) {
1065 Warn(instrprof_error::bitmap_mismatch);
1066 return;
1067 }
1068
1069 // Bitmap bytes are merged by simply ORing them together.
1070 for (size_t I = 0, E = Other.BitmapBytes.size(); I < E; ++I) {
1071 BitmapBytes[I] = Other.BitmapBytes[I] | BitmapBytes[I];
1072 }
1073
1074 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1075 mergeValueProfData(ValueKind: Kind, Src&: Other, Weight, Warn);
1076}
1077
1078void InstrProfRecord::scaleValueProfData(
1079 uint32_t ValueKind, uint64_t N, uint64_t D,
1080 function_ref<void(instrprof_error)> Warn) {
1081 for (auto &R : getValueSitesForKind(ValueKind))
1082 R.scale(N, D, Warn);
1083}
1084
1085void InstrProfRecord::scale(uint64_t N, uint64_t D,
1086 function_ref<void(instrprof_error)> Warn) {
1087 assert(D != 0 && "D cannot be 0");
1088 for (auto &Count : this->Counts) {
1089 bool Overflowed;
1090 Count = SaturatingMultiply(X: Count, Y: N, ResultOverflowed: &Overflowed) / D;
1091 if (Count > getInstrMaxCountValue()) {
1092 Count = getInstrMaxCountValue();
1093 Overflowed = true;
1094 }
1095 if (Overflowed)
1096 Warn(instrprof_error::counter_overflow);
1097 }
1098 for (auto &Count : this->UniformCounts) {
1099 bool Overflowed;
1100 Count = SaturatingMultiply(X: Count, Y: N, ResultOverflowed: &Overflowed) / D;
1101 if (Count > getInstrMaxCountValue()) {
1102 Count = getInstrMaxCountValue();
1103 Overflowed = true;
1104 }
1105 if (Overflowed)
1106 Warn(instrprof_error::counter_overflow);
1107 }
1108 computeBlockUniformity();
1109 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1110 scaleValueProfData(ValueKind: Kind, N, D, Warn);
1111}
1112
1113// Map indirect call target name hash to name string.
1114uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
1115 InstrProfSymtab *SymTab) {
1116 if (!SymTab)
1117 return Value;
1118
1119 if (ValueKind == IPVK_IndirectCallTarget)
1120 return SymTab->getFunctionHashFromAddress(Address: Value);
1121
1122 if (ValueKind == IPVK_VTableTarget)
1123 return SymTab->getVTableHashFromAddress(Address: Value);
1124
1125 return Value;
1126}
1127
1128void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
1129 ArrayRef<InstrProfValueData> VData,
1130 InstrProfSymtab *ValueMap) {
1131 // Remap values.
1132 std::vector<InstrProfValueData> RemappedVD;
1133 RemappedVD.reserve(n: VData.size());
1134 for (const auto &V : VData) {
1135 uint64_t NewValue = remapValue(Value: V.Value, ValueKind, SymTab: ValueMap);
1136 RemappedVD.push_back(x: {.Value: NewValue, .Count: V.Count});
1137 }
1138
1139 std::vector<InstrProfValueSiteRecord> &ValueSites =
1140 getOrCreateValueSitesForKind(ValueKind);
1141 assert(ValueSites.size() == Site);
1142
1143 // Add a new value site with remapped value profiling data.
1144 ValueSites.emplace_back(args: std::move(RemappedVD));
1145}
1146
1147void TemporalProfTraceTy::createBPFunctionNodes(
1148 ArrayRef<TemporalProfTraceTy> Traces, std::vector<BPFunctionNode> &Nodes,
1149 bool RemoveOutlierUNs) {
1150 using IDT = BPFunctionNode::IDT;
1151 using UtilityNodeT = BPFunctionNode::UtilityNodeT;
1152 UtilityNodeT MaxUN = 0;
1153 DenseMap<IDT, size_t> IdToFirstTimestamp;
1154 DenseMap<IDT, UtilityNodeT> IdToFirstUN;
1155 DenseMap<IDT, SmallVector<UtilityNodeT>> IdToUNs;
1156 // TODO: We need to use the Trace.Weight field to give more weight to more
1157 // important utilities
1158 for (auto &Trace : Traces) {
1159 size_t CutoffTimestamp = 1;
1160 for (size_t Timestamp = 0; Timestamp < Trace.FunctionNameRefs.size();
1161 Timestamp++) {
1162 IDT Id = Trace.FunctionNameRefs[Timestamp];
1163 auto [It, WasInserted] = IdToFirstTimestamp.try_emplace(Key: Id, Args&: Timestamp);
1164 if (!WasInserted)
1165 It->getSecond() = std::min<size_t>(a: It->getSecond(), b: Timestamp);
1166 if (Timestamp >= CutoffTimestamp) {
1167 ++MaxUN;
1168 CutoffTimestamp = 2 * Timestamp;
1169 }
1170 IdToFirstUN.try_emplace(Key: Id, Args&: MaxUN);
1171 }
1172 for (auto &[Id, FirstUN] : IdToFirstUN)
1173 for (auto UN = FirstUN; UN <= MaxUN; ++UN)
1174 IdToUNs[Id].push_back(Elt: UN);
1175 ++MaxUN;
1176 IdToFirstUN.clear();
1177 }
1178
1179 if (RemoveOutlierUNs) {
1180 DenseMap<UtilityNodeT, unsigned> UNFrequency;
1181 for (auto &[Id, UNs] : IdToUNs)
1182 for (auto &UN : UNs)
1183 ++UNFrequency[UN];
1184 // Filter out utility nodes that are too infrequent or too prevalent to make
1185 // BalancedPartitioning more effective.
1186 for (auto &[Id, UNs] : IdToUNs)
1187 llvm::erase_if(C&: UNs, P: [&](auto &UN) {
1188 unsigned Freq = UNFrequency[UN];
1189 return Freq <= 1 || 2 * Freq > IdToUNs.size();
1190 });
1191 }
1192
1193 for (auto &[Id, UNs] : IdToUNs)
1194 Nodes.emplace_back(args&: Id, args&: UNs);
1195
1196 // Since BalancedPartitioning is sensitive to the initial order, we explicitly
1197 // order nodes by their earliest timestamp.
1198 llvm::sort(C&: Nodes, Comp: [&](auto &L, auto &R) {
1199 return std::make_pair(IdToFirstTimestamp[L.Id], L.Id) <
1200 std::make_pair(IdToFirstTimestamp[R.Id], R.Id);
1201 });
1202}
1203
1204#define INSTR_PROF_COMMON_API_IMPL
1205#include "llvm/ProfileData/InstrProfData.inc"
1206
1207/*!
1208 * ValueProfRecordClosure Interface implementation for InstrProfRecord
1209 * class. These C wrappers are used as adaptors so that C++ code can be
1210 * invoked as callbacks.
1211 */
1212uint32_t getNumValueKindsInstrProf(const void *Record) {
1213 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
1214}
1215
1216uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
1217 return reinterpret_cast<const InstrProfRecord *>(Record)
1218 ->getNumValueSites(ValueKind: VKind);
1219}
1220
1221uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
1222 return reinterpret_cast<const InstrProfRecord *>(Record)
1223 ->getNumValueData(ValueKind: VKind);
1224}
1225
1226uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
1227 uint32_t S) {
1228 const auto *IPR = reinterpret_cast<const InstrProfRecord *>(R);
1229 return IPR->getValueArrayForSite(ValueKind: VK, Site: S).size();
1230}
1231
1232void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
1233 uint32_t K, uint32_t S) {
1234 const auto *IPR = reinterpret_cast<const InstrProfRecord *>(R);
1235 llvm::copy(Range: IPR->getValueArrayForSite(ValueKind: K, Site: S), Out: Dst);
1236}
1237
1238ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
1239 ValueProfData *VD = new (::operator new(TotalSizeInBytes)) ValueProfData();
1240 memset(s: VD, c: 0, n: TotalSizeInBytes);
1241 return VD;
1242}
1243
1244static ValueProfRecordClosure InstrProfRecordClosure = {
1245 .Record: nullptr,
1246 .GetNumValueKinds: getNumValueKindsInstrProf,
1247 .GetNumValueSites: getNumValueSitesInstrProf,
1248 .GetNumValueData: getNumValueDataInstrProf,
1249 .GetNumValueDataForSite: getNumValueDataForSiteInstrProf,
1250 .RemapValueData: nullptr,
1251 .GetValueForSite: getValueForSiteInstrProf,
1252 .AllocValueProfData: allocValueProfDataInstrProf};
1253
1254// Wrapper implementation using the closure mechanism.
1255uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
1256 auto Closure = InstrProfRecordClosure;
1257 Closure.Record = &Record;
1258 return getValueProfDataSize(Closure: &Closure);
1259}
1260
1261// Wrapper implementation using the closure mechanism.
1262std::unique_ptr<ValueProfData>
1263ValueProfData::serializeFrom(const InstrProfRecord &Record) {
1264 InstrProfRecordClosure.Record = &Record;
1265
1266 std::unique_ptr<ValueProfData> VPD(
1267 serializeValueProfDataFrom(Closure: &InstrProfRecordClosure, DstData: nullptr));
1268 return VPD;
1269}
1270
1271void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
1272 InstrProfSymtab *SymTab) {
1273 Record.reserveSites(ValueKind: Kind, NumValueSites);
1274
1275 InstrProfValueData *ValueData = getValueProfRecordValueData(This: this);
1276 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
1277 uint8_t ValueDataCount = this->SiteCountArray[VSite];
1278 ArrayRef<InstrProfValueData> VDs(ValueData, ValueDataCount);
1279 Record.addValueData(ValueKind: Kind, Site: VSite, VData: VDs, ValueMap: SymTab);
1280 ValueData += ValueDataCount;
1281 }
1282}
1283
1284// For writing/serializing, Old is the host endianness, and New is
1285// byte order intended on disk. For Reading/deserialization, Old
1286// is the on-disk source endianness, and New is the host endianness.
1287void ValueProfRecord::swapBytes(llvm::endianness Old, llvm::endianness New) {
1288 using namespace support;
1289
1290 if (Old == New)
1291 return;
1292
1293 if (llvm::endianness::native != Old) {
1294 sys::swapByteOrder<uint32_t>(Value&: NumValueSites);
1295 sys::swapByteOrder<uint32_t>(Value&: Kind);
1296 }
1297 uint32_t ND = getValueProfRecordNumValueData(This: this);
1298 InstrProfValueData *VD = getValueProfRecordValueData(This: this);
1299
1300 // No need to swap byte array: SiteCountArrray.
1301 for (uint32_t I = 0; I < ND; I++) {
1302 sys::swapByteOrder<uint64_t>(Value&: VD[I].Value);
1303 sys::swapByteOrder<uint64_t>(Value&: VD[I].Count);
1304 }
1305 if (llvm::endianness::native == Old) {
1306 sys::swapByteOrder<uint32_t>(Value&: NumValueSites);
1307 sys::swapByteOrder<uint32_t>(Value&: Kind);
1308 }
1309}
1310
1311void ValueProfData::deserializeTo(InstrProfRecord &Record,
1312 InstrProfSymtab *SymTab) {
1313 if (NumValueKinds == 0)
1314 return;
1315
1316 ValueProfRecord *VR = getFirstValueProfRecord(This: this);
1317 for (uint32_t K = 0; K < NumValueKinds; K++) {
1318 VR->deserializeTo(Record, SymTab);
1319 VR = getValueProfRecordNext(This: VR);
1320 }
1321}
1322
1323static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
1324 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
1325 ValueProfData());
1326}
1327
1328Error ValueProfData::checkIntegrity() {
1329 if (NumValueKinds > IPVK_Last + 1)
1330 return make_error<InstrProfError>(
1331 Args: instrprof_error::malformed, Args: "number of value profile kinds is invalid");
1332 // Total size needs to be multiple of quadword size.
1333 if (TotalSize % sizeof(uint64_t))
1334 return make_error<InstrProfError>(
1335 Args: instrprof_error::malformed, Args: "total size is not multiples of quardword");
1336
1337 ValueProfRecord *VR = getFirstValueProfRecord(This: this);
1338 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
1339 if (VR->Kind > IPVK_Last)
1340 return make_error<InstrProfError>(Args: instrprof_error::malformed,
1341 Args: "value kind is invalid");
1342 VR = getValueProfRecordNext(This: VR);
1343 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
1344 return make_error<InstrProfError>(
1345 Args: instrprof_error::malformed,
1346 Args: "value profile address is greater than total size");
1347 }
1348 return Error::success();
1349}
1350
1351Expected<std::unique_ptr<ValueProfData>>
1352ValueProfData::getValueProfData(const unsigned char *D,
1353 const unsigned char *const BufferEnd,
1354 llvm::endianness Endianness) {
1355 using namespace support;
1356
1357 if (D + sizeof(ValueProfData) > BufferEnd)
1358 return make_error<InstrProfError>(Args: instrprof_error::truncated);
1359
1360 const unsigned char *Header = D;
1361 uint32_t TotalSize = endian::readNext<uint32_t>(memory&: Header, endian: Endianness);
1362
1363 if (D + TotalSize > BufferEnd)
1364 return make_error<InstrProfError>(Args: instrprof_error::too_large);
1365
1366 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
1367 memcpy(dest: VPD.get(), src: D, n: TotalSize);
1368 // Byte swap.
1369 VPD->swapBytesToHost(Endianness);
1370
1371 Error E = VPD->checkIntegrity();
1372 if (E)
1373 return std::move(E);
1374
1375 return std::move(VPD);
1376}
1377
1378void ValueProfData::swapBytesToHost(llvm::endianness Endianness) {
1379 using namespace support;
1380
1381 if (Endianness == llvm::endianness::native)
1382 return;
1383
1384 sys::swapByteOrder<uint32_t>(Value&: TotalSize);
1385 sys::swapByteOrder<uint32_t>(Value&: NumValueKinds);
1386
1387 ValueProfRecord *VR = getFirstValueProfRecord(This: this);
1388 for (uint32_t K = 0; K < NumValueKinds; K++) {
1389 VR->swapBytes(Old: Endianness, New: llvm::endianness::native);
1390 VR = getValueProfRecordNext(This: VR);
1391 }
1392}
1393
1394void ValueProfData::swapBytesFromHost(llvm::endianness Endianness) {
1395 using namespace support;
1396
1397 if (Endianness == llvm::endianness::native)
1398 return;
1399
1400 ValueProfRecord *VR = getFirstValueProfRecord(This: this);
1401 for (uint32_t K = 0; K < NumValueKinds; K++) {
1402 ValueProfRecord *NVR = getValueProfRecordNext(This: VR);
1403 VR->swapBytes(Old: llvm::endianness::native, New: Endianness);
1404 VR = NVR;
1405 }
1406 sys::swapByteOrder<uint32_t>(Value&: TotalSize);
1407 sys::swapByteOrder<uint32_t>(Value&: NumValueKinds);
1408}
1409
1410void annotateValueSite(Module &M, Instruction &Inst,
1411 const InstrProfRecord &InstrProfR,
1412 InstrProfValueKind ValueKind, uint32_t SiteIdx,
1413 uint32_t MaxMDCount) {
1414 auto VDs = InstrProfR.getValueArrayForSite(ValueKind, Site: SiteIdx);
1415 if (VDs.empty())
1416 return;
1417 uint64_t Sum = 0;
1418 for (const InstrProfValueData &V : VDs)
1419 Sum = SaturatingAdd(X: Sum, Y: V.Count);
1420 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
1421}
1422
1423void annotateValueSite(Module &M, Instruction &Inst,
1424 ArrayRef<InstrProfValueData> VDs,
1425 uint64_t Sum, InstrProfValueKind ValueKind,
1426 uint32_t MaxMDCount) {
1427 if (VDs.empty())
1428 return;
1429 LLVMContext &Ctx = M.getContext();
1430 MDBuilder MDHelper(Ctx);
1431 SmallVector<Metadata *, 3> Vals;
1432 // Tag
1433 Vals.push_back(Elt: MDHelper.createString(Str: MDProfLabels::ValueProfile));
1434 // Value Kind
1435 Vals.push_back(Elt: MDHelper.createConstant(
1436 C: ConstantInt::get(Ty: Type::getInt32Ty(C&: Ctx), V: ValueKind)));
1437 // Total Count
1438 Vals.push_back(
1439 Elt: MDHelper.createConstant(C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: Sum)));
1440
1441 // Value Profile Data
1442 uint32_t MDCount = MaxMDCount;
1443 // Zero values might occur multiple times (e.g., multiple functions that
1444 // cannot be remapped). Deduplicate them to enforce the variant that
1445 // values are unique, which allows passes to make some simplifying
1446 // assumptions.
1447 // TODO(boomanaiden154): This fits more naturally in addValueData, but
1448 // preserving the current behavior is necessary for some error handling
1449 // paths. When that gets cleaned up, we should move this there.
1450 // TODO(boomanaiden154): We are also deduplicating non-zero values.
1451 // These are rare and should only come from corrupted profiles, so we
1452 // just skip them. Remove this when they are fixed properly in
1453 // llvm-profdata.
1454 uint64_t ZeroCount = 0;
1455 DenseSet<uint64_t> VisitedValues;
1456 for (const auto &VD : VDs) {
1457 auto [_, ValueInserted] = VisitedValues.insert(V: VD.Value);
1458 if (VD.Value != 0 && !ValueInserted)
1459 continue;
1460 if (VD.Value == 0) {
1461 ZeroCount += VD.Count;
1462 } else {
1463 Vals.push_back(Elt: MDHelper.createConstant(
1464 C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: VD.Value)));
1465 Vals.push_back(Elt: MDHelper.createConstant(
1466 C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: VD.Count)));
1467 }
1468 if (--MDCount == 0)
1469 break;
1470 }
1471 if (ZeroCount != 0) {
1472 Vals.push_back(
1473 Elt: MDHelper.createConstant(C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: 0)));
1474 Vals.push_back(Elt: MDHelper.createConstant(
1475 C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: ZeroCount)));
1476 }
1477 // Only add metadata if we have at least one value. Otherwise we will end
1478 // up adding invalid metadata in the case where the profile only has a
1479 // zero value with a zero count.
1480 if (Vals.size() >= 5)
1481 Inst.setMetadata(KindID: LLVMContext::MD_prof, Node: MDNode::get(Context&: Ctx, MDs: Vals));
1482}
1483
1484MDNode *mayHaveValueProfileOfKind(const Instruction &Inst,
1485 InstrProfValueKind ValueKind) {
1486 MDNode *MD = Inst.getMetadata(KindID: LLVMContext::MD_prof);
1487 if (!MD)
1488 return nullptr;
1489
1490 if (MD->getNumOperands() < 5)
1491 return nullptr;
1492
1493 MDString *Tag = cast<MDString>(Val: MD->getOperand(I: 0));
1494 if (!Tag || Tag->getString() != MDProfLabels::ValueProfile)
1495 return nullptr;
1496
1497 // Now check kind:
1498 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD: MD->getOperand(I: 1));
1499 if (!KindInt)
1500 return nullptr;
1501 if (KindInt->getZExtValue() != ValueKind)
1502 return nullptr;
1503
1504 return MD;
1505}
1506
1507SmallVector<InstrProfValueData, 4>
1508getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind,
1509 uint32_t MaxNumValueData, uint64_t &TotalC,
1510 bool GetNoICPValue) {
1511 // Four inline elements seem to work well in practice. With MaxNumValueData,
1512 // this array won't grow very big anyway.
1513 SmallVector<InstrProfValueData, 4> ValueData;
1514 MDNode *MD = mayHaveValueProfileOfKind(Inst, ValueKind);
1515 if (!MD)
1516 return ValueData;
1517 const unsigned NOps = MD->getNumOperands();
1518 // Get total count
1519 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD: MD->getOperand(I: 2));
1520 if (!TotalCInt)
1521 return ValueData;
1522 TotalC = TotalCInt->getZExtValue();
1523
1524 ValueData.reserve(N: (NOps - 3) / 2);
1525 for (unsigned I = 3; I < NOps; I += 2) {
1526 if (ValueData.size() >= MaxNumValueData)
1527 break;
1528 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD: MD->getOperand(I));
1529 ConstantInt *Count =
1530 mdconst::dyn_extract<ConstantInt>(MD: MD->getOperand(I: I + 1));
1531 if (!Value || !Count) {
1532 ValueData.clear();
1533 return ValueData;
1534 }
1535 uint64_t CntValue = Count->getZExtValue();
1536 if (!GetNoICPValue && (CntValue == NOMORE_ICP_MAGICNUM))
1537 continue;
1538 InstrProfValueData V;
1539 V.Value = Value->getZExtValue();
1540 V.Count = CntValue;
1541 ValueData.push_back(Elt: V);
1542 }
1543 return ValueData;
1544}
1545
1546bool needsComdatForCounter(const GlobalObject &GO, const Module &M) {
1547 if (GO.hasComdat())
1548 return true;
1549
1550 if (!M.getTargetTriple().supportsCOMDAT())
1551 return false;
1552
1553 // See createPGOFuncNameVar for more details. To avoid link errors, profile
1554 // counters for function with available_externally linkage needs to be changed
1555 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
1556 // created. Without using comdat, duplicate entries won't be removed by the
1557 // linker leading to increased data segement size and raw profile size. Even
1558 // worse, since the referenced counter from profile per-function data object
1559 // will be resolved to the common strong definition, the profile counts for
1560 // available_externally functions will end up being duplicated in raw profile
1561 // data. This can result in distorted profile as the counts of those dups
1562 // will be accumulated by the profile merger.
1563 GlobalValue::LinkageTypes Linkage = GO.getLinkage();
1564 if (Linkage != GlobalValue::ExternalWeakLinkage &&
1565 Linkage != GlobalValue::AvailableExternallyLinkage)
1566 return false;
1567
1568 return true;
1569}
1570
1571// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
1572bool isIRPGOFlagSet(const Module *M) {
1573 const GlobalVariable *IRInstrVar =
1574 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1575 if (!IRInstrVar || IRInstrVar->hasLocalLinkage())
1576 return false;
1577
1578 // For CSPGO+LTO, this variable might be marked as non-prevailing and we only
1579 // have the decl.
1580 if (IRInstrVar->isDeclaration())
1581 return true;
1582
1583 // Check if the flag is set.
1584 if (!IRInstrVar->hasInitializer())
1585 return false;
1586
1587 auto *InitVal = dyn_cast_or_null<ConstantInt>(Val: IRInstrVar->getInitializer());
1588 if (!InitVal)
1589 return false;
1590 return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
1591}
1592
1593// Check if we can safely rename this Comdat function.
1594bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
1595 if (F.getName().empty())
1596 return false;
1597 if (!needsComdatForCounter(GO: F, M: *(F.getParent())))
1598 return false;
1599 // Unsafe to rename the address-taken function (which can be used in
1600 // function comparison).
1601 if (CheckAddressTaken && F.hasAddressTaken())
1602 return false;
1603 // Only safe to do if this function may be discarded if it is not used
1604 // in the compilation unit.
1605 if (!GlobalValue::isDiscardableIfUnused(Linkage: F.getLinkage()))
1606 return false;
1607
1608 // For AvailableExternallyLinkage functions.
1609 if (!F.hasComdat()) {
1610 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
1611 return true;
1612 }
1613 return true;
1614}
1615
1616// Create the variable for the profile file name.
1617void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
1618 if (InstrProfileOutput.empty())
1619 return;
1620 Constant *ProfileNameConst =
1621 ConstantDataArray::getString(Context&: M.getContext(), Initializer: InstrProfileOutput, AddNull: true);
1622 GlobalVariable *ProfileNameVar = new GlobalVariable(
1623 M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
1624 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
1625 ProfileNameVar->setVisibility(GlobalValue::HiddenVisibility);
1626 Triple TT(M.getTargetTriple());
1627 if (TT.supportsCOMDAT()) {
1628 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
1629 ProfileNameVar->setComdat(M.getOrInsertComdat(
1630 Name: StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
1631 }
1632}
1633
1634Error OverlapStats::accumulateCounts(const std::string &BaseFilename,
1635 const std::string &TestFilename,
1636 bool IsCS) {
1637 auto GetProfileSum = [IsCS](const std::string &Filename,
1638 CountSumOrPercent &Sum) -> Error {
1639 // This function is only used from llvm-profdata that doesn't use any kind
1640 // of VFS. Just create a default RealFileSystem to read profiles.
1641 auto FS = vfs::getRealFileSystem();
1642 auto ReaderOrErr = InstrProfReader::create(Path: Filename, FS&: *FS);
1643 if (Error E = ReaderOrErr.takeError()) {
1644 return E;
1645 }
1646 auto Reader = std::move(ReaderOrErr.get());
1647 Reader->accumulateCounts(Sum, IsCS);
1648 return Error::success();
1649 };
1650 auto Ret = GetProfileSum(BaseFilename, Base);
1651 if (Ret)
1652 return Ret;
1653 Ret = GetProfileSum(TestFilename, Test);
1654 if (Ret)
1655 return Ret;
1656 this->BaseFilename = &BaseFilename;
1657 this->TestFilename = &TestFilename;
1658 Valid = true;
1659 return Error::success();
1660}
1661
1662void OverlapStats::addOneMismatch(const CountSumOrPercent &MismatchFunc) {
1663 Mismatch.NumEntries += 1;
1664 Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
1665 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1666 if (Test.ValueCounts[I] >= 1.0f)
1667 Mismatch.ValueCounts[I] +=
1668 MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
1669 }
1670}
1671
1672void OverlapStats::addOneUnique(const CountSumOrPercent &UniqueFunc) {
1673 Unique.NumEntries += 1;
1674 Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
1675 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1676 if (Test.ValueCounts[I] >= 1.0f)
1677 Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
1678 }
1679}
1680
1681void OverlapStats::dump(raw_fd_ostream &OS) const {
1682 if (!Valid)
1683 return;
1684
1685 const char *EntryName =
1686 (Level == ProgramLevel ? "functions" : "edge counters");
1687 if (Level == ProgramLevel) {
1688 OS << "Profile overlap information for base_profile: " << *BaseFilename
1689 << " and test_profile: " << *TestFilename << "\nProgram level:\n";
1690 } else {
1691 OS << "Function level:\n"
1692 << " Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
1693 }
1694
1695 OS << " # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
1696 if (Mismatch.NumEntries)
1697 OS << " # of " << EntryName << " mismatch: " << Mismatch.NumEntries
1698 << "\n";
1699 if (Unique.NumEntries)
1700 OS << " # of " << EntryName
1701 << " only in test_profile: " << Unique.NumEntries << "\n";
1702
1703 OS << " Edge profile overlap: " << format(Fmt: "%.3f%%", Vals: Overlap.CountSum * 100)
1704 << "\n";
1705 if (Mismatch.NumEntries)
1706 OS << " Mismatched count percentage (Edge): "
1707 << format(Fmt: "%.3f%%", Vals: Mismatch.CountSum * 100) << "\n";
1708 if (Unique.NumEntries)
1709 OS << " Percentage of Edge profile only in test_profile: "
1710 << format(Fmt: "%.3f%%", Vals: Unique.CountSum * 100) << "\n";
1711 OS << " Edge profile base count sum: " << format(Fmt: "%.0f", Vals: Base.CountSum)
1712 << "\n"
1713 << " Edge profile test count sum: " << format(Fmt: "%.0f", Vals: Test.CountSum)
1714 << "\n";
1715
1716 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1717 if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
1718 continue;
1719 char ProfileKindName[20] = {0};
1720 switch (I) {
1721 case IPVK_IndirectCallTarget:
1722 strncpy(dest: ProfileKindName, src: "IndirectCall", n: 19);
1723 break;
1724 case IPVK_MemOPSize:
1725 strncpy(dest: ProfileKindName, src: "MemOP", n: 19);
1726 break;
1727 case IPVK_VTableTarget:
1728 strncpy(dest: ProfileKindName, src: "VTable", n: 19);
1729 break;
1730 default:
1731 snprintf(s: ProfileKindName, maxlen: 19, format: "VP[%d]", I);
1732 break;
1733 }
1734 OS << " " << ProfileKindName
1735 << " profile overlap: " << format(Fmt: "%.3f%%", Vals: Overlap.ValueCounts[I] * 100)
1736 << "\n";
1737 if (Mismatch.NumEntries)
1738 OS << " Mismatched count percentage (" << ProfileKindName
1739 << "): " << format(Fmt: "%.3f%%", Vals: Mismatch.ValueCounts[I] * 100) << "\n";
1740 if (Unique.NumEntries)
1741 OS << " Percentage of " << ProfileKindName
1742 << " profile only in test_profile: "
1743 << format(Fmt: "%.3f%%", Vals: Unique.ValueCounts[I] * 100) << "\n";
1744 OS << " " << ProfileKindName
1745 << " profile base count sum: " << format(Fmt: "%.0f", Vals: Base.ValueCounts[I])
1746 << "\n"
1747 << " " << ProfileKindName
1748 << " profile test count sum: " << format(Fmt: "%.0f", Vals: Test.ValueCounts[I])
1749 << "\n";
1750 }
1751}
1752
1753namespace IndexedInstrProf {
1754Expected<Header> Header::readFromBuffer(const unsigned char *Buffer) {
1755 using namespace support;
1756 static_assert(std::is_standard_layout_v<Header>,
1757 "Use standard layout for Header for simplicity");
1758 Header H;
1759
1760 H.Magic = endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1761 // Check the magic number.
1762 if (H.Magic != IndexedInstrProf::Magic)
1763 return make_error<InstrProfError>(Args: instrprof_error::bad_magic);
1764
1765 // Read the version.
1766 H.Version = endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1767 if (H.getIndexedProfileVersion() >
1768 IndexedInstrProf::ProfVersion::CurrentVersion)
1769 return make_error<InstrProfError>(Args: instrprof_error::unsupported_version);
1770
1771 static_assert(IndexedInstrProf::ProfVersion::CurrentVersion == Version14,
1772 "Please update the reader as needed when a new field is added "
1773 "or when indexed profile version gets bumped.");
1774
1775 Buffer += sizeof(uint64_t); // Skip Header.Unused field.
1776 H.HashType = endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1777 H.HashOffset = endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1778 if (H.getIndexedProfileVersion() >= 8)
1779 H.MemProfOffset =
1780 endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1781 if (H.getIndexedProfileVersion() >= 9)
1782 H.BinaryIdOffset =
1783 endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1784 // Version 11 is handled by this condition.
1785 if (H.getIndexedProfileVersion() >= 10)
1786 H.TemporalProfTracesOffset =
1787 endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1788 if (H.getIndexedProfileVersion() >= 12)
1789 H.VTableNamesOffset =
1790 endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1791 return H;
1792}
1793
1794uint64_t Header::getIndexedProfileVersion() const {
1795 return GET_VERSION(Version);
1796}
1797
1798size_t Header::size() const {
1799 switch (getIndexedProfileVersion()) {
1800 // To retain backward compatibility, new fields must be appended to the end
1801 // of the header, and byte offset of existing fields shouldn't change when
1802 // indexed profile version gets incremented.
1803 static_assert(
1804 IndexedInstrProf::ProfVersion::CurrentVersion == Version14,
1805 "Please update the size computation below if a new field has "
1806 "been added to the header; for a version bump without new "
1807 "fields, add a case statement to fall through to the latest version.");
1808 case 14ull: // UniformityBits added in record data, no header change
1809 case 13ull:
1810 case 12ull:
1811 return 72;
1812 case 11ull:
1813 [[fallthrough]];
1814 case 10ull:
1815 return 64;
1816 case 9ull:
1817 return 56;
1818 case 8ull:
1819 return 48;
1820 default: // Version7 (when the backwards compatible header was introduced).
1821 return 40;
1822 }
1823}
1824
1825} // namespace IndexedInstrProf
1826
1827} // end namespace llvm
1828