LLVM 24.0.0git
InstrProf.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/ArrayRef.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"
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"
31#include "llvm/IR/Type.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/Endian.h"
40#include "llvm/Support/Error.h"
42#include "llvm/Support/LEB128.h"
44#include "llvm/Support/Path.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
66 "static-func-full-module-prefix", cl::init(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.
79 "static-func-strip-dirname-prefix", cl::init(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
84 const std::string &ErrMsg = "") {
85 std::string Msg;
87
88 switch (Err) {
90 OS << "success";
91 break;
93 OS << "end of File";
94 break;
96 OS << "unrecognized instrumentation profile encoding format";
97 break;
99 OS << "invalid instrumentation profile data (bad magic)";
100 break;
102 OS << "invalid instrumentation profile data (file header is corrupt)";
103 break;
105 OS << "unsupported instrumentation profile format version";
106 break;
108 OS << "unsupported instrumentation profile hash type";
109 break;
111 OS << "too much profile data";
112 break;
114 OS << "truncated profile data";
115 break;
117 OS << "malformed instrumentation profile data";
118 break;
120 OS << "debug info/binary for correlation is required";
121 break;
123 OS << "debug info/binary for correlation is not necessary";
124 break;
126 OS << "unable to correlate profile";
127 break;
129 OS << "invalid profile created. Please file a bug "
130 "at: " BUG_REPORT_URL
131 " and include the profraw files that caused this error.";
132 break;
134 OS << "no profile data available for function";
135 break;
137 OS << "function control flow change detected (hash mismatch)";
138 break;
140 OS << "function basic block count change detected (counter mismatch)";
141 break;
143 OS << "function bitmap size change detected (bitmap size mismatch)";
144 break;
146 OS << "counter overflow";
147 break;
149 OS << "function value site count change detected (counter mismatch)";
150 break;
152 OS << "failed to compress data (zlib)";
153 break;
155 OS << "failed to uncompress data (zlib)";
156 break;
158 OS << "empty raw profile file";
159 break;
161 OS << "profile uses zlib compression but the profile reader was built "
162 "without zlib support";
163 break;
165 OS << "raw profile version mismatch";
166 break;
168 OS << "excessively large counter value suggests corrupted profile data";
169 break;
171 OS << "cannot merge single-byte-coverage profiles with count "
172 "(non-coverage) profiles";
173 break;
174 }
175
176 // If optional error message is not empty, append it to the message.
177 if (!ErrMsg.empty())
178 OS << ": " << ErrMsg;
179
180 return OS.str();
181}
182
183namespace {
184
185// FIXME: This class is only here to support the transition to llvm::Error. It
186// will be removed once this transition is complete. Clients should prefer to
187// deal with the Error value directly, rather than converting to error_code.
188class InstrProfErrorCategoryType : public std::error_category {
189 const char *name() const noexcept override { return "llvm.instrprof"; }
190
191 std::string message(int IE) const override {
192 return getInstrProfErrString(static_cast<instrprof_error>(IE));
193 }
194};
195
196} // end anonymous namespace
197
198const std::error_category &llvm::instrprof_category() {
199 static InstrProfErrorCategoryType ErrorCategory;
200 return ErrorCategory;
201}
202
203namespace {
204
205const char *InstrProfSectNameCommon[] = {
206#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
207 SectNameCommon,
209};
210
211const char *InstrProfSectNameCoff[] = {
212#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
213 SectNameCoff,
215};
216
217const char *InstrProfSectNamePrefix[] = {
218#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
219 Prefix,
221};
222
223} // namespace
224
225namespace llvm {
226
228 "enable-name-compression",
229 cl::desc("Enable name/filename string compression"), cl::init(true));
230
232 "enable-vtable-value-profiling", cl::init(false),
233 cl::desc("If true, the virtual table address will be instrumented to know "
234 "the types of a C++ pointer. The information is used in indirect "
235 "call promotion to do selective vtable-based comparison."));
236
238 "enable-vtable-profile-use", cl::init(false),
239 cl::desc("If ThinLTO and WPD is enabled and this option is true, vtable "
240 "profiles will be used by ICP pass for more efficient indirect "
241 "call sequence. If false, type profiles won't be used."));
242
245 bool AddSegmentInfo) {
246 std::string SectName;
247
248 if (OF == Triple::MachO && AddSegmentInfo)
249 SectName = InstrProfSectNamePrefix[IPSK];
250
251 if (OF == Triple::COFF)
252 SectName += InstrProfSectNameCoff[IPSK];
253 else
254 SectName += InstrProfSectNameCommon[IPSK];
255
256 if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
257 SectName += ",regular,live_support";
258
259 return SectName;
260}
261
262std::string InstrProfError::message() const {
263 return getInstrProfErrString(Err, Msg);
264}
265
266char InstrProfError::ID = 0;
267
270
273
274uint64_t ProfOStream::tell() const { return OS.tell(); }
278
280 using namespace support;
281
282 if (IsFDOStream) {
283 raw_fd_ostream &FDOStream = static_cast<raw_fd_ostream &>(OS);
284 const uint64_t LastPos = FDOStream.tell();
285 for (const auto &K : P) {
286 FDOStream.seek(K.Pos);
287 for (uint64_t Elem : K.D)
288 write(Elem);
289 }
290 // Reset the stream to the last position after patching so that users
291 // don't accidentally overwrite data. This makes it consistent with
292 // the string stream below which replaces the data directly.
293 FDOStream.seek(LastPos);
294 } else {
295 raw_string_ostream &SOStream = static_cast<raw_string_ostream &>(OS);
296 std::string &Data = SOStream.str(); // with flush
297 for (const auto &K : P) {
298 for (int I = 0, E = K.D.size(); I != E; I++) {
299 uint64_t Bytes =
301 Data.replace(K.Pos + I * sizeof(uint64_t), sizeof(uint64_t),
302 (const char *)&Bytes, sizeof(uint64_t));
303 }
304 }
305 }
306}
307
309 StringRef FileName,
310 [[maybe_unused]] uint64_t Version) {
311 // Value names may be prefixed with a binary '1' to indicate
312 // that the backend should not modify the symbols due to any platform
313 // naming convention. Do not include that '1' in the PGO profile name.
314 if (Name[0] == '\1')
315 Name = Name.substr(1);
316
317 std::string NewName = std::string(Name);
319 // For local symbols, prepend the main file name to distinguish them.
320 // Do not include the full path in the file name since there's no guarantee
321 // that it will stay the same, e.g., if the files are checked out from
322 // version control in different locations.
323 if (FileName.empty())
324 NewName = NewName.insert(0, "<unknown>:");
325 else
326 NewName = NewName.insert(0, FileName.str() + ":");
327 }
328 return NewName;
329}
330
331// Strip NumPrefix level of directory name from PathNameStr. If the number of
332// directory separators is less than NumPrefix, strip all the directories and
333// leave base file name only.
334static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
335 uint32_t Count = NumPrefix;
336 uint32_t Pos = 0, LastPos = 0;
337 for (const auto &CI : PathNameStr) {
338 ++Pos;
340 LastPos = Pos;
341 --Count;
342 }
343 if (Count == 0)
344 break;
345 }
346 return PathNameStr.substr(LastPos);
347}
348
350 StringRef FileName(GO.getParent()->getSourceFileName());
351 uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
352 if (StripLevel < StaticFuncStripDirNamePrefix)
353 StripLevel = StaticFuncStripDirNamePrefix;
354 if (StripLevel)
355 FileName = stripDirPrefix(FileName, StripLevel);
356 return FileName;
357}
358
359// The PGO name has the format [<filepath>;]<mangled-name> where <filepath>; is
360// provided if linkage is local and is used to discriminate possibly identical
361// mangled names. ";" is used because it is unlikely to be found in either
362// <filepath> or <mangled-name>.
363//
364// Older compilers used getPGOFuncName() which has the format
365// [<filepath>:]<mangled-name>. This caused trouble for Objective-C functions
366// which commonly have :'s in their names. We still need to compute this name to
367// lookup functions from profiles built by older compilers.
368static std::string
371 StringRef FileName) {
372 return GlobalValue::getGlobalIdentifier(GO.getName(), Linkage, FileName);
373}
374
375static std::optional<std::string> lookupPGONameFromMetadata(MDNode *MD) {
376 if (MD != nullptr) {
377 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
378 return S.str();
379 }
380 return {};
381}
382
383// Returns the PGO object name. This function has some special handling
384// when called in LTO optimization. The following only applies when calling in
385// LTO passes (when \c InLTO is true): LTO's internalization privatizes many
386// global linkage symbols. This happens after value profile annotation, but
387// those internal linkage functions should not have a source prefix.
388// Additionally, for ThinLTO mode, exported internal functions are promoted
389// and renamed. We need to ensure that the original internal PGO name is
390// used when computing the GUID that is compared against the profiled GUIDs.
391// To differentiate compiler generated internal symbols from original ones,
392// PGOFuncName meta data are created and attached to the original internal
393// symbols in the value profile annotation step
394// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
395// data, its original linkage must be non-internal.
396static std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO,
397 MDNode *PGONameMetadata) {
398 if (!InLTO) {
399 auto FileName = getStrippedSourceFileName(GO);
400 return getIRPGONameForGlobalObject(GO, GO.getLinkage(), FileName);
401 }
402
403 // In LTO mode (when InLTO is true), first check if there is a meta data.
404 if (auto IRPGOFuncName = lookupPGONameFromMetadata(PGONameMetadata))
405 return *IRPGOFuncName;
406
407 // If there is no meta data, the function must be a global before the value
408 // profile annotation pass. Its current linkage may be internal if it is
409 // internalized in LTO mode.
411}
412
413// Returns the IRPGO function name and does special handling when called
414// in LTO optimization. See the comments of `getIRPGOObjectName` for details.
415std::string getIRPGOFuncName(const Function &F, bool InLTO) {
417}
418
419// Please use getIRPGOFuncName for LLVM IR instrumentation. This function is
420// for front-end (Clang, etc) instrumentation.
421// The implementation is kept for profile matching from older profiles.
422// This is similar to `getIRPGOFuncName` except that this function calls
423// 'getPGOFuncName' to get a name and `getIRPGOFuncName` calls
424// 'getIRPGONameForGlobalObject'. See the difference between two callees in the
425// comments of `getIRPGONameForGlobalObject`.
426std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
427 if (!InLTO) {
428 auto FileName = getStrippedSourceFileName(F);
429 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
430 }
431
432 // In LTO mode (when InLTO is true), first check if there is a meta data.
433 if (auto PGOFuncName = lookupPGONameFromMetadata(getPGOFuncNameMetadata(F)))
434 return *PGOFuncName;
435
436 // If there is no meta data, the function must be a global before the value
437 // profile annotation pass. Its current linkage may be internal if it is
438 // internalized in LTO mode.
439 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
440}
441
442std::string getPGOName(const GlobalVariable &V, bool InLTO) {
443 // PGONameMetadata should be set by compiler at profile use time
444 // and read by symtab creation to look up symbols corresponding to
445 // a MD5 hash.
446 return getIRPGOObjectName(V, InLTO, V.getMetadata(getPGONameMetadataName()));
447}
448
449// See getIRPGOObjectName() for a discription of the format.
450std::pair<StringRef, StringRef> getParsedIRPGOName(StringRef IRPGOName) {
451 auto [FileName, MangledName] = IRPGOName.split(GlobalIdentifierDelimiter);
452 if (MangledName.empty())
453 return std::make_pair(StringRef(), IRPGOName);
454 return std::make_pair(FileName, MangledName);
455}
456
458 if (FileName.empty())
459 return PGOFuncName;
460 // Drop the file name including ':' or ';'. See getIRPGONameForGlobalObject as
461 // well.
462 if (PGOFuncName.starts_with(FileName))
463 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
464 return PGOFuncName;
465}
466
467// \p FuncName is the string used as profile lookup key for the function. A
468// symbol is created to hold the name. Return the legalized symbol name.
469std::string getPGOFuncNameVarName(StringRef FuncName,
471 std::string VarName = std::string(getInstrProfNameVarPrefix());
472 VarName += FuncName;
473
474 if (!GlobalValue::isLocalLinkage(Linkage))
475 return VarName;
476
477 // Now fix up illegal chars in local VarName that may upset the assembler.
478 const char InvalidChars[] = "-:;<>/\"'";
479 size_t FoundPos = VarName.find_first_of(InvalidChars);
480 while (FoundPos != std::string::npos) {
481 VarName[FoundPos] = '_';
482 FoundPos = VarName.find_first_of(InvalidChars, FoundPos + 1);
483 }
484 return VarName;
485}
486
487bool isGPUProfTarget(const Module &M) {
488 const Triple &T = M.getTargetTriple();
489 return T.isGPU();
490}
491
493 // Hide the symbol so that we correctly get a copy for each executable.
494 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
496}
497
500 StringRef PGOFuncName) {
501 // We generally want to match the function's linkage, but available_externally
502 // and extern_weak both have the wrong semantics, and anything that doesn't
503 // need to link across compilation units doesn't need to be visible at all.
506 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
508 else if (Linkage == GlobalValue::InternalLinkage ||
511
512 auto *Value =
513 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
514 auto *FuncNameVar =
515 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
516 getPGOFuncNameVarName(PGOFuncName, Linkage));
517
518 setPGOFuncVisibility(M, FuncNameVar);
519 return FuncNameVar;
520}
521
523 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
524}
525
526Error InstrProfSymtab::create(Module &M, bool InLTO, bool AddCanonical) {
527 for (Function &F : M) {
528 // Function may not have a name: like using asm("") to overwrite the name.
529 // Ignore in this case.
530 if (!F.hasName())
531 continue;
532 auto IRPGOFuncName = getIRPGOFuncName(F, InLTO);
533 if (Error E = addFuncWithName(F, IRPGOFuncName, AddCanonical))
534 return E;
535 // Also use getPGOFuncName() so that we can find records from older profiles
536 auto PGOFuncName = getPGOFuncName(F, InLTO);
537 if (PGOFuncName != IRPGOFuncName)
538 if (Error E = addFuncWithName(F, PGOFuncName, AddCanonical))
539 return E;
540 }
541
542 for (GlobalVariable &G : M.globals()) {
543 if (!G.hasName() || !G.hasMetadata(LLVMContext::MD_type))
544 continue;
545 if (Error E = addVTableWithName(G, getPGOName(G, InLTO)))
546 return E;
547 }
548
549 Sorted = false;
550 finalizeSymtab();
551 return Error::success();
552}
553
554Error InstrProfSymtab::addVTableWithName(GlobalVariable &VTable,
555 StringRef VTablePGOName) {
556 auto NameToGUIDMap = [&](StringRef Name) -> Error {
557 if (Error E = addSymbolName(Name))
558 return E;
559
560 bool Inserted = true;
561 std::tie(std::ignore, Inserted) = MD5VTableMap.try_emplace(
563 if (!Inserted)
564 LLVM_DEBUG(dbgs() << "GUID conflict within one module");
565 return Error::success();
566 };
567 if (Error E = NameToGUIDMap(VTablePGOName))
568 return E;
569
570 StringRef CanonicalName = getCanonicalName(VTablePGOName);
571 if (CanonicalName != VTablePGOName)
572 return NameToGUIDMap(CanonicalName);
573
574 return Error::success();
575}
576
578 std::function<Error(StringRef)> NameCallback) {
579 const uint8_t *P = NameStrings.bytes_begin();
580 const uint8_t *EndP = NameStrings.bytes_end();
581 while (P < EndP) {
582 uint32_t N;
583 uint64_t UncompressedSize = decodeULEB128(P, &N);
584 P += N;
585 uint64_t CompressedSize = decodeULEB128(P, &N);
586 P += N;
587 const bool IsCompressed = (CompressedSize != 0);
588 SmallVector<uint8_t, 128> UncompressedNameStrings;
589 StringRef NameStrings;
590 if (IsCompressed) {
593
594 if (Error E = compression::zlib::decompress(ArrayRef(P, CompressedSize),
595 UncompressedNameStrings,
596 UncompressedSize)) {
597 consumeError(std::move(E));
599 }
600 P += CompressedSize;
601 NameStrings = toStringRef(UncompressedNameStrings);
602 } else {
603 NameStrings =
604 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
605 P += UncompressedSize;
606 }
607 // Now parse the name strings.
609 NameStrings.split(Names, getInstrProfNameSeparator());
610 for (StringRef &Name : Names)
611 if (Error E = NameCallback(Name))
612 return E;
613
614 while (P < EndP && *P == 0)
615 P++;
616 }
617 return Error::success();
618}
619
621 return readAndDecodeStrings(NameStrings,
622 [&](StringRef S) { return addFuncName(S); });
623}
624
626 StringRef VTableNameStrings) {
628 FuncNameStrings, [&](StringRef S) { return addFuncName(S); }))
629 return E;
630
631 return readAndDecodeStrings(VTableNameStrings,
632 [&](StringRef S) { return addVTableName(S); });
633}
636 StringRef CompressedVTableStrings) {
637 return readAndDecodeStrings(CompressedVTableStrings,
638 [&](StringRef S) { return addVTableName(S); });
639}
640
642 // In ThinLTO, local function may have been promoted to global and have
643 // suffix ".llvm." added to the function name. We need to add the
644 // stripped function name to the symbol table so that we can find a match
645 // from profile.
646 //
647 // ".__uniq." suffix is used to differentiate internal linkage functions in
648 // different modules and should be kept. This is the only suffix with the
649 // pattern ".xxx" which is kept before matching, other suffixes ".llvm." and
650 // ".part" will be stripped.
651 //
652 // Leverage the common canonicalization logic from FunctionSamples. Instead of
653 // removing all suffixes except ".__uniq.", explicitly specify the ones to be
654 // removed. This avoids the issue of colliding the canonical names of
655 // coroutine function with its await suspend wrappers or with its post-split
656 // clones. i.e. coro function foo, its wrappers
657 // (foo.__await_suspend_wrapper__init, and foo.__await_suspend_wrapper__final)
658 // and its post-split clones (foo.resume, foo.cleanup) are all canonicalized
659 // to "foo" otherwise, which can make the symtab lookup return unexpected
660 // result.
661 const SmallVector<StringRef> SuffixesToRemove{".llvm.", ".part."};
662 return FunctionSamples::getCanonicalFnName(PGOName, SuffixesToRemove);
663}
664
665Error InstrProfSymtab::addFuncWithName(Function &F, StringRef PGOFuncName,
666 bool AddCanonical) {
667 auto NameToGUIDMap = [&](StringRef Name) -> Error {
668 if (Error E = addFuncName(Name))
669 return E;
670 MD5FuncMap.emplace_back(Function::getGUIDAssumingExternalLinkage(Name), &F);
671 return Error::success();
672 };
673 if (Error E = NameToGUIDMap(PGOFuncName))
674 return E;
675
676 if (!AddCanonical)
678
679 StringRef CanonicalFuncName = getCanonicalName(PGOFuncName);
680 if (CanonicalFuncName != PGOFuncName)
681 return NameToGUIDMap(CanonicalFuncName);
682
683 return Error::success();
684}
685
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(Address, 0);
690}
691
693 finalizeSymtab();
694 auto It = partition_point(AddrToMD5Map, [=](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
707 SmallVector<StringRef, 0> Sorted(NameTab.keys());
708 llvm::sort(Sorted);
709 for (StringRef S : Sorted)
710 OS << S << '\n';
711}
712
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(NameStrs.begin(), NameStrs.end(), 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(UncompressedNameStrings.length(), P);
726 P += EncLen;
727
728 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
729 EncLen = encodeULEB128(CompressedLen, P);
730 P += EncLen;
731 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
732 unsigned HeaderLen = P - &Header[0];
733 Result.append(HeaderStr, 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(arrayRefFromStringRef(UncompressedNameStrings),
744 CompressedNameStrings,
746
747 return WriteStringToResult(CompressedNameStrings.size(),
748 toStringRef(CompressedNameStrings));
749}
750
752 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
753 StringRef NameStr =
754 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
755 return NameStr;
756}
757
759 std::string &Result, bool DoCompression) {
760 std::vector<std::string> NameStrs;
761 for (auto *NameVar : NameVars) {
762 NameStrs.push_back(std::string(getPGOFuncNameVarInitializer(NameVar)));
763 }
765 NameStrs, compression::zlib::isAvailable() && DoCompression, Result);
766}
767
769 std::string &Result, bool DoCompression) {
770 std::vector<std::string> VTableNameStrs;
771 for (auto *VTable : VTables)
772 VTableNameStrs.push_back(getPGOName(*VTable));
774 VTableNameStrs, compression::zlib::isAvailable() && DoCompression,
775 Result);
776}
777
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;
788 for (size_t I = 0; I < NumValueSites; ++I) {
789 for (const auto &V : getValueArrayForSite(VK, I))
790 KindSum += V.Count;
791 }
792 Sum.ValueCounts[VK] += KindSum;
793 }
794}
795
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(I->Count, J->Count,
810 Overlap.Base.ValueCounts[ValueKind],
811 Overlap.Test.ValueCounts[ValueKind]);
812 FuncLevelScore += OverlapStats::score(
813 I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind],
814 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.
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);
839 Other.getValueSitesForKind(ValueKind);
840 for (uint32_t I = 0; I < ThisNumValueSites; I++)
841 ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap,
842 FuncLevelOverlap);
843}
844
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(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(Kind);
857 uint32_t OtherNumValueSites = Other.getNumValueSites(Kind);
858 if (ThisNumValueSites != OtherNumValueSites) {
859 Mismatch = true;
860 break;
861 }
862 }
863 }
864 if (Mismatch) {
865 Overlap.addOneMismatch(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(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(Counts[I], Other.Counts[I],
878 Overlap.Base.CountSum, Overlap.Test.CountSum);
879 MaxCount = std::max(Other.Counts[I], 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(Counts[I], Other.Counts[I],
888 FuncLevelOverlap.Base.CountSum,
889 FuncLevelOverlap.Test.CountSum);
890 FuncLevelOverlap.Overlap.CountSum = FuncScore;
891 FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
892 FuncLevelOverlap.Valid = true;
893 }
894}
895
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(std::max(ValueData.size(), Input.ValueData.size()));
905 for (const InstrProfValueData &J : Input.ValueData) {
906 while (I != IE && I->Value < J.Value) {
907 Merged.push_back(*I);
908 ++I;
909 }
910 if (I != IE && I->Value == J.Value) {
911 bool Overflowed;
912 I->Count = SaturatingMultiplyAdd(J.Count, Weight, I->Count, &Overflowed);
913 if (Overflowed)
915 Merged.push_back(*I);
916 ++I;
917 continue;
918 }
919 Merged.push_back(J);
920 }
921 Merged.insert(Merged.end(), I, IE);
922 ValueData = std::move(Merged);
923}
924
926 function_ref<void(instrprof_error)> Warn) {
927 for (InstrProfValueData &I : ValueData) {
928 bool Overflowed;
929 I.Count = SaturatingMultiply(I.Count, N, &Overflowed) / D;
930 if (Overflowed)
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) {
944 return;
945 }
946 if (!ThisNumValueSites)
947 return;
948 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
949 getOrCreateValueSitesForKind(ValueKind);
951 Src.getValueSitesForKind(ValueKind);
952 for (uint32_t I = 0; I < ThisNumValueSites; I++)
953 ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
954}
955
957 if (UniformCounts.empty())
958 return;
959
960 if (UniformCounts.size() != Counts.size()) {
961 UniformityBits.clear();
962 return;
963 }
964
965 UniformityBits.assign((Counts.size() + 7) / 8, 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(Src.begin(), 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
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()) {
1000 return;
1001 }
1002
1004 Other.computeBlockUniformity();
1005
1006 // Special handling of the first count as the PseudoCount.
1007 CountPseudoKind OtherKind = Other.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) {
1015 return;
1016 }
1017 if (OtherKind == PseudoHot || ThisKind == PseudoHot)
1019 else
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(Other.Counts[I], Weight, Counts[I], &Overflowed);
1030 if (Value > getInstrMaxCountValue()) {
1032 Overflowed = true;
1033 }
1034 Counts[I] = Value;
1035 if (Overflowed)
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(Other.UniformCounts[I], Weight,
1047 UniformCounts[I], &Overflowed);
1050 Overflowed = true;
1051 }
1052 if (Overflowed)
1054 }
1056 }
1057 } else {
1058 UniformCounts.clear();
1059 mergeUniformityBits(UniformityBits, 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()) {
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(Kind, 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
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(Count, N, &Overflowed) / D;
1091 if (Count > getInstrMaxCountValue()) {
1093 Overflowed = true;
1094 }
1095 if (Overflowed)
1097 }
1098 for (auto &Count : this->UniformCounts) {
1099 bool Overflowed;
1100 Count = SaturatingMultiply(Count, N, &Overflowed) / D;
1101 if (Count > getInstrMaxCountValue()) {
1103 Overflowed = true;
1104 }
1105 if (Overflowed)
1107 }
1109 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1110 scaleValueProfData(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(Value);
1121
1122 if (ValueKind == IPVK_VTableTarget)
1123 return SymTab->getVTableHashFromAddress(Value);
1124
1125 return Value;
1126}
1127
1131 // Remap values.
1132 std::vector<InstrProfValueData> RemappedVD;
1133 RemappedVD.reserve(VData.size());
1134 for (const auto &V : VData) {
1135 uint64_t NewValue = remapValue(V.Value, ValueKind, ValueMap);
1136 RemappedVD.push_back({NewValue, 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(std::move(RemappedVD));
1145}
1146
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;
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(Id, Timestamp);
1164 if (!WasInserted)
1165 It->getSecond() = std::min<size_t>(It->getSecond(), Timestamp);
1166 if (Timestamp >= CutoffTimestamp) {
1167 ++MaxUN;
1168 CutoffTimestamp = 2 * Timestamp;
1169 }
1170 IdToFirstUN.try_emplace(Id, MaxUN);
1171 }
1172 for (auto &[Id, FirstUN] : IdToFirstUN)
1173 for (auto UN = FirstUN; UN <= MaxUN; ++UN)
1174 IdToUNs[Id].push_back(UN);
1175 ++MaxUN;
1176 IdToFirstUN.clear();
1177 }
1178
1179 if (RemoveOutlierUNs) {
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(UNs, [&](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(Id, UNs);
1195
1196 // Since BalancedPartitioning is sensitive to the initial order, we explicitly
1197 // order nodes by their earliest timestamp.
1198 llvm::sort(Nodes, [&](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
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 */
1213 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
1214}
1215
1217 return reinterpret_cast<const InstrProfRecord *>(Record)
1218 ->getNumValueSites(VKind);
1219}
1220
1222 return reinterpret_cast<const InstrProfRecord *>(Record)
1223 ->getNumValueData(VKind);
1224}
1225
1227 uint32_t S) {
1228 const auto *IPR = reinterpret_cast<const InstrProfRecord *>(R);
1229 return IPR->getValueArrayForSite(VK, 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(IPR->getValueArrayForSite(K, S), Dst);
1236}
1237
1239 ValueProfData *VD = new (::operator new(TotalSizeInBytes)) ValueProfData();
1240 memset(VD, 0, TotalSizeInBytes);
1241 return VD;
1242}
1243
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);
1259}
1260
1261// Wrapper implementation using the closure mechanism.
1262std::unique_ptr<ValueProfData>
1263ValueProfData::serializeFrom(const InstrProfRecord &Record) {
1265
1266 std::unique_ptr<ValueProfData> VPD(
1268 return VPD;
1269}
1270
1271void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
1272 InstrProfSymtab *SymTab) {
1273 Record.reserveSites(Kind, NumValueSites);
1274
1275 InstrProfValueData *ValueData = getValueProfRecordValueData(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(Kind, VSite, VDs, 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) {
1296 }
1297 uint32_t ND = getValueProfRecordNumValueData(this);
1298 InstrProfValueData *VD = getValueProfRecordValueData(this);
1299
1300 // No need to swap byte array: SiteCountArrray.
1301 for (uint32_t I = 0; I < ND; I++) {
1304 }
1305 if (llvm::endianness::native == Old) {
1308 }
1309}
1310
1311void ValueProfData::deserializeTo(InstrProfRecord &Record,
1312 InstrProfSymtab *SymTab) {
1313 if (NumValueKinds == 0)
1314 return;
1315
1316 ValueProfRecord *VR = getFirstValueProfRecord(this);
1317 for (uint32_t K = 0; K < NumValueKinds; K++) {
1318 VR->deserializeTo(Record, SymTab);
1319 VR = getValueProfRecordNext(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)
1331 instrprof_error::malformed, "number of value profile kinds is invalid");
1332 // Total size needs to be multiple of quadword size.
1333 if (TotalSize % sizeof(uint64_t))
1335 instrprof_error::malformed, "total size is not multiples of quardword");
1336
1337 ValueProfRecord *VR = getFirstValueProfRecord(this);
1338 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
1339 if (VR->Kind > IPVK_Last)
1341 "value kind is invalid");
1342 VR = getValueProfRecordNext(VR);
1343 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
1346 "value profile address is greater than total size");
1347 }
1348 return Error::success();
1349}
1350
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)
1359
1360 const unsigned char *Header = D;
1361 uint32_t TotalSize = endian::readNext<uint32_t>(Header, Endianness);
1362
1363 if (D + TotalSize > BufferEnd)
1365
1366 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
1367 memcpy(VPD.get(), D, 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
1386
1387 ValueProfRecord *VR = getFirstValueProfRecord(this);
1388 for (uint32_t K = 0; K < NumValueKinds; K++) {
1389 VR->swapBytes(Endianness, llvm::endianness::native);
1390 VR = getValueProfRecordNext(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);
1401 for (uint32_t K = 0; K < NumValueKinds; K++) {
1402 ValueProfRecord *NVR = getValueProfRecordNext(VR);
1403 VR->swapBytes(llvm::endianness::native, Endianness);
1404 VR = NVR;
1405 }
1408}
1409
1411 const InstrProfRecord &InstrProfR,
1412 InstrProfValueKind ValueKind, uint32_t SiteIdx,
1413 uint32_t MaxMDCount) {
1414 auto VDs = InstrProfR.getValueArrayForSite(ValueKind, SiteIdx);
1415 if (VDs.empty())
1416 return;
1417 uint64_t Sum = 0;
1418 for (const InstrProfValueData &V : VDs)
1419 Sum = SaturatingAdd(Sum, V.Count);
1420 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
1421}
1422
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);
1432 // Tag
1434 // Value Kind
1435 Vals.push_back(MDHelper.createConstant(
1436 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
1437 // Total Count
1438 Vals.push_back(
1439 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), 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(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(MDHelper.createConstant(
1464 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
1465 Vals.push_back(MDHelper.createConstant(
1466 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
1467 }
1468 if (--MDCount == 0)
1469 break;
1470 }
1471 if (ZeroCount != 0) {
1472 Vals.push_back(
1473 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), 0)));
1474 Vals.push_back(MDHelper.createConstant(
1475 ConstantInt::get(Type::getInt64Ty(Ctx), 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(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
1482}
1483
1485 InstrProfValueKind ValueKind) {
1486 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
1487 if (!MD)
1488 return nullptr;
1489
1490 if (MD->getNumOperands() < 5)
1491 return nullptr;
1492
1494 if (!Tag || Tag->getString() != MDProfLabels::ValueProfile)
1495 return nullptr;
1496
1497 // Now check kind:
1499 if (!KindInt)
1500 return nullptr;
1501 if (KindInt->getZExtValue() != ValueKind)
1502 return nullptr;
1503
1504 return MD;
1505}
1506
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.
1514 MDNode *MD = mayHaveValueProfileOfKind(Inst, ValueKind);
1515 if (!MD)
1516 return ValueData;
1517 const unsigned NOps = MD->getNumOperands();
1518 // Get total count
1520 if (!TotalCInt)
1521 return ValueData;
1522 TotalC = TotalCInt->getZExtValue();
1523
1524 ValueData.reserve((NOps - 3) / 2);
1525 for (unsigned I = 3; I < NOps; I += 2) {
1526 if (ValueData.size() >= MaxNumValueData)
1527 break;
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(V);
1542 }
1543 return ValueData;
1544}
1545
1547 return F.getMetadata(getPGOFuncNameMetadataName());
1548}
1549
1550static void createPGONameMetadata(GlobalObject &GO, StringRef MetadataName,
1551 StringRef PGOName) {
1552 // Only for internal linkage functions or global variables. The name is not
1553 // the same as PGO name for these global objects.
1554 if (GO.getName() == PGOName)
1555 return;
1556
1557 // Don't create duplicated metadata.
1558 if (GO.getMetadata(MetadataName))
1559 return;
1560
1561 LLVMContext &C = GO.getContext();
1562 MDNode *N = MDNode::get(C, MDString::get(C, PGOName));
1563 GO.setMetadata(MetadataName, N);
1564}
1565
1567 return createPGONameMetadata(F, getPGOFuncNameMetadataName(), PGOFuncName);
1568}
1569
1571 return createPGONameMetadata(GO, getPGONameMetadataName(), PGOName);
1572}
1573
1574bool needsComdatForCounter(const GlobalObject &GO, const Module &M) {
1575 if (GO.hasComdat())
1576 return true;
1577
1578 if (!M.getTargetTriple().supportsCOMDAT())
1579 return false;
1580
1581 // See createPGOFuncNameVar for more details. To avoid link errors, profile
1582 // counters for function with available_externally linkage needs to be changed
1583 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
1584 // created. Without using comdat, duplicate entries won't be removed by the
1585 // linker leading to increased data segement size and raw profile size. Even
1586 // worse, since the referenced counter from profile per-function data object
1587 // will be resolved to the common strong definition, the profile counts for
1588 // available_externally functions will end up being duplicated in raw profile
1589 // data. This can result in distorted profile as the counts of those dups
1590 // will be accumulated by the profile merger.
1592 if (Linkage != GlobalValue::ExternalWeakLinkage &&
1594 return false;
1595
1596 return true;
1597}
1598
1599// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
1600bool isIRPGOFlagSet(const Module *M) {
1601 const GlobalVariable *IRInstrVar =
1602 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1603 if (!IRInstrVar || IRInstrVar->hasLocalLinkage())
1604 return false;
1605
1606 // For CSPGO+LTO, this variable might be marked as non-prevailing and we only
1607 // have the decl.
1608 if (IRInstrVar->isDeclaration())
1609 return true;
1610
1611 // Check if the flag is set.
1612 if (!IRInstrVar->hasInitializer())
1613 return false;
1614
1615 auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
1616 if (!InitVal)
1617 return false;
1618 return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
1619}
1620
1621// Check if we can safely rename this Comdat function.
1622bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
1623 if (F.getName().empty())
1624 return false;
1625 if (!needsComdatForCounter(F, *(F.getParent())))
1626 return false;
1627 // Unsafe to rename the address-taken function (which can be used in
1628 // function comparison).
1629 if (CheckAddressTaken && F.hasAddressTaken())
1630 return false;
1631 // Only safe to do if this function may be discarded if it is not used
1632 // in the compilation unit.
1633 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
1634 return false;
1635
1636 // For AvailableExternallyLinkage functions.
1637 if (!F.hasComdat()) {
1639 return true;
1640 }
1641 return true;
1642}
1643
1644// Create the variable for the profile file name.
1645void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
1646 if (InstrProfileOutput.empty())
1647 return;
1648 Constant *ProfileNameConst =
1649 ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true);
1650 GlobalVariable *ProfileNameVar = new GlobalVariable(
1651 M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
1654 Triple TT(M.getTargetTriple());
1655 if (TT.supportsCOMDAT()) {
1657 ProfileNameVar->setComdat(M.getOrInsertComdat(
1659 }
1660}
1661
1663 const std::string &TestFilename,
1664 bool IsCS) {
1665 auto GetProfileSum = [IsCS](const std::string &Filename,
1666 CountSumOrPercent &Sum) -> Error {
1667 // This function is only used from llvm-profdata that doesn't use any kind
1668 // of VFS. Just create a default RealFileSystem to read profiles.
1669 auto FS = vfs::getRealFileSystem();
1670 auto ReaderOrErr = InstrProfReader::create(Filename, *FS);
1671 if (Error E = ReaderOrErr.takeError()) {
1672 return E;
1673 }
1674 auto Reader = std::move(ReaderOrErr.get());
1675 Reader->accumulateCounts(Sum, IsCS);
1676 return Error::success();
1677 };
1678 auto Ret = GetProfileSum(BaseFilename, Base);
1679 if (Ret)
1680 return Ret;
1681 Ret = GetProfileSum(TestFilename, Test);
1682 if (Ret)
1683 return Ret;
1684 this->BaseFilename = &BaseFilename;
1685 this->TestFilename = &TestFilename;
1686 Valid = true;
1687 return Error::success();
1688}
1689
1691 Mismatch.NumEntries += 1;
1692 Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
1693 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1694 if (Test.ValueCounts[I] >= 1.0f)
1695 Mismatch.ValueCounts[I] +=
1696 MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
1697 }
1698}
1699
1701 Unique.NumEntries += 1;
1702 Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
1703 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1704 if (Test.ValueCounts[I] >= 1.0f)
1705 Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
1706 }
1707}
1708
1710 if (!Valid)
1711 return;
1712
1713 const char *EntryName =
1714 (Level == ProgramLevel ? "functions" : "edge counters");
1715 if (Level == ProgramLevel) {
1716 OS << "Profile overlap information for base_profile: " << *BaseFilename
1717 << " and test_profile: " << *TestFilename << "\nProgram level:\n";
1718 } else {
1719 OS << "Function level:\n"
1720 << " Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
1721 }
1722
1723 OS << " # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
1724 if (Mismatch.NumEntries)
1725 OS << " # of " << EntryName << " mismatch: " << Mismatch.NumEntries
1726 << "\n";
1727 if (Unique.NumEntries)
1728 OS << " # of " << EntryName
1729 << " only in test_profile: " << Unique.NumEntries << "\n";
1730
1731 OS << " Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100)
1732 << "\n";
1733 if (Mismatch.NumEntries)
1734 OS << " Mismatched count percentage (Edge): "
1735 << format("%.3f%%", Mismatch.CountSum * 100) << "\n";
1736 if (Unique.NumEntries)
1737 OS << " Percentage of Edge profile only in test_profile: "
1738 << format("%.3f%%", Unique.CountSum * 100) << "\n";
1739 OS << " Edge profile base count sum: " << format("%.0f", Base.CountSum)
1740 << "\n"
1741 << " Edge profile test count sum: " << format("%.0f", Test.CountSum)
1742 << "\n";
1743
1744 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1745 if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
1746 continue;
1747 char ProfileKindName[20] = {0};
1748 switch (I) {
1749 case IPVK_IndirectCallTarget:
1750 strncpy(ProfileKindName, "IndirectCall", 19);
1751 break;
1752 case IPVK_MemOPSize:
1753 strncpy(ProfileKindName, "MemOP", 19);
1754 break;
1755 case IPVK_VTableTarget:
1756 strncpy(ProfileKindName, "VTable", 19);
1757 break;
1758 default:
1759 snprintf(ProfileKindName, 19, "VP[%d]", I);
1760 break;
1761 }
1762 OS << " " << ProfileKindName
1763 << " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100)
1764 << "\n";
1765 if (Mismatch.NumEntries)
1766 OS << " Mismatched count percentage (" << ProfileKindName
1767 << "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n";
1768 if (Unique.NumEntries)
1769 OS << " Percentage of " << ProfileKindName
1770 << " profile only in test_profile: "
1771 << format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n";
1772 OS << " " << ProfileKindName
1773 << " profile base count sum: " << format("%.0f", Base.ValueCounts[I])
1774 << "\n"
1775 << " " << ProfileKindName
1776 << " profile test count sum: " << format("%.0f", Test.ValueCounts[I])
1777 << "\n";
1778 }
1779}
1780
1781namespace IndexedInstrProf {
1782Expected<Header> Header::readFromBuffer(const unsigned char *Buffer) {
1783 using namespace support;
1784 static_assert(std::is_standard_layout_v<Header>,
1785 "Use standard layout for Header for simplicity");
1786 Header H;
1787
1789 // Check the magic number.
1790 if (H.Magic != IndexedInstrProf::Magic)
1792
1793 // Read the version.
1795 if (H.getIndexedProfileVersion() >
1798
1800 "Please update the reader as needed when a new field is added "
1801 "or when indexed profile version gets bumped.");
1802
1803 Buffer += sizeof(uint64_t); // Skip Header.Unused field.
1806 if (H.getIndexedProfileVersion() >= 8)
1807 H.MemProfOffset =
1809 if (H.getIndexedProfileVersion() >= 9)
1810 H.BinaryIdOffset =
1812 // Version 11 is handled by this condition.
1813 if (H.getIndexedProfileVersion() >= 10)
1814 H.TemporalProfTracesOffset =
1816 if (H.getIndexedProfileVersion() >= 12)
1817 H.VTableNamesOffset =
1819 return H;
1820}
1821
1825
1826size_t Header::size() const {
1827 switch (getIndexedProfileVersion()) {
1828 // To retain backward compatibility, new fields must be appended to the end
1829 // of the header, and byte offset of existing fields shouldn't change when
1830 // indexed profile version gets incremented.
1831 static_assert(
1833 "Please update the size computation below if a new field has "
1834 "been added to the header; for a version bump without new "
1835 "fields, add a case statement to fall through to the latest version.");
1836 case 14ull: // UniformityBits added in record data, no header change
1837 case 13ull:
1838 case 12ull:
1839 return 72;
1840 case 11ull:
1841 [[fallthrough]];
1842 case 10ull:
1843 return 64;
1844 case 9ull:
1845 return 56;
1846 case 8ull:
1847 return 48;
1848 default: // Version7 (when the backwards compatible header was introduced).
1849 return 40;
1850 }
1851}
1852
1853} // namespace IndexedInstrProf
1854
1855} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define _
Module.h This file contains the declarations for the Module class.
static cl::opt< bool > StaticFuncFullModulePrefix("static-func-full-module-prefix", cl::init(true), cl::Hidden, cl::desc("Use full module build paths in the profile counter names for " "static functions."))
static cl::opt< unsigned > StaticFuncStripDirNamePrefix("static-func-strip-dirname-prefix", cl::init(0), cl::Hidden, cl::desc("Strip specified level of directory name from source path in " "the profile counter name for static functions."))
static std::string getInstrProfErrString(instrprof_error Err, const std::string &ErrMsg="")
Definition InstrProf.cpp:83
#define INSTR_PROF_QUOTE(x)
#define GET_VERSION(V)
#define INSTR_PROF_PROFILE_NAME_VAR
#define INSTR_PROF_RAW_VERSION_VAR
#define VARIANT_MASK_IR_PROF
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
This file contains the declarations for metadata subclasses.
#define T
static constexpr StringLiteral Filename
#define P(N)
This file contains the declarations for profiling metadata utility functions.
const char * Msg
static const char * name
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Defines the virtual file system interface vfs::FileSystem.
The Input class is used to parse a yaml document into in-memory structs and vectors.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This is an important base class in LLVM.
Definition Constant.h:43
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
unsigned size() const
Definition DenseMap.h:172
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
bool hasComdat() const
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
void setLinkage(LinkageTypes LT)
Module * getParent()
Get the module that this global value is contained inside of...
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:234
void setVisibility(VisibilityTypes V)
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
std::string message() const override
Return the error message as a string.
static LLVM_ABI Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const InstrProfCorrelator *Correlator=nullptr, const object::BuildIDFetcher *BIDFetcher=nullptr, const InstrProfCorrelator::ProfCorrelatorKind BIDFetcherCorrelatorKind=InstrProfCorrelator::ProfCorrelatorKind::NONE, std::function< void(Error)> Warn=nullptr)
Factory method to create an appropriately typed reader for the given instrprof file.
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition InstrProf.h:518
static LLVM_ABI StringRef getCanonicalName(StringRef PGOName)
Error addSymbolName(StringRef SymbolName)
Definition InstrProf.h:648
Error addVTableName(StringRef VTableName)
Adds VTableName as a known symbol, and inserts it to a map that tracks all vtable names.
Definition InstrProf.h:670
LLVM_ABI void dumpNames(raw_ostream &OS) const
Dump the symbols in this table.
LLVM_ABI Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
Error addFuncName(StringRef FuncName)
The method name is kept since there are many callers.
Definition InstrProf.h:666
LLVM_ABI Error initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames)
Initialize 'this' with the set of vtable names encoded in CompressedVTableNames.
LLVM_ABI uint64_t getVTableHashFromAddress(uint64_t Address) const
Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
LLVM_ABI uint64_t getFunctionHashFromAddress(uint64_t Address) const
Return a function's hash, or 0, if the function isn't in this SymTab.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition MDBuilder.cpp:25
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
Definition MDBuilder.cpp:21
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
A single uniqued string.
Definition Metadata.h:722
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:615
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
const std::string & getSourceFileName() const
Get the module's original source file name.
Definition Module.h:305
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
raw_ostream & OS
Definition InstrProf.h:87
LLVM_ABI uint64_t tell() const
LLVM_ABI void writeByte(uint8_t V)
LLVM_ABI void patch(ArrayRef< PatchItem > P)
LLVM_ABI void write32(uint32_t V)
support::endian::Writer LE
Definition InstrProf.h:88
LLVM_ABI ProfOStream(raw_fd_ostream &FD)
LLVM_ABI void write(uint64_t V)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
const unsigned char * bytes_end() const
Definition StringRef.h:125
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
const unsigned char * bytes_begin() const
Definition StringRef.h:122
unsigned size() const
Definition Trace.h:96
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:310
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
See the file comment.
Definition ValueMap.h:84
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
An efficient, type-erasing, non-owning reference to a callable.
A raw_ostream that writes to a file descriptor.
uint64_t seek(uint64_t off)
Flushes the stream and repositions the underlying file descriptor position to the offset specified fr...
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
uint64_t tell() const
tell - Return the current offset with the file.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
const uint64_t Magic
Definition InstrProf.h:1193
initializer< Ty > init(const Ty &Val)
LLVM_ABI void compress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &CompressedBuffer, int Level=DefaultCompression)
LLVM_ABI Error decompress(ArrayRef< uint8_t > Input, uint8_t *Output, size_t &UncompressedSize)
LLVM_ABI bool isAvailable()
constexpr int BestSizeCompression
Definition Compression.h:40
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:696
value_type byte_swap(value_type value, endianness endian)
Definition Endian.h:44
value_type readNext(const CharT *&memory, endianness endian)
Read a value of a particular endianness from a buffer, and increment the buffer past that value.
Definition Endian.h:81
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition Path.cpp:618
void swapByteOrder(T &Value)
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition InstrProf.h:131
LLVM_ABI std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Please use getIRPGOFuncName for LLVM IR instrumentation.
LLVM_ABI void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
LLVM_ABI std::string getIRPGOFuncName(const Function &F, bool InLTO=false)
StringRef getPGOFuncNameMetadataName()
Definition InstrProf.h:353
RelativeUniformCounterPtr ValuesPtrExpr NumValueSites[IPVK_Last+1]
Definition InstrProf.h:95
void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst, uint32_t K, uint32_t S)
LLVM_ABI cl::opt< bool > DoInstrProfNameCompression
LLVM_ABI StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2129
uint64_t decodeULEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a ULEB128 value.
Definition LEB128.h:130
LLVM_ABI void createPGONameMetadata(GlobalObject &GO, StringRef PGOName)
Create the PGOName metadata if a global object's PGO name is different from its mangled name.
INSTR_PROF_VISIBILITY ValueProfRecord * getValueProfRecordNext(ValueProfRecord *VPR)
Use this method to advance to the next This ValueProfRecord.
LLVM_ABI std::pair< StringRef, StringRef > getParsedIRPGOName(StringRef IRPGOName)
LLVM_ABI MDNode * getPGOFuncNameMetadata(const Function &F)
Return the PGOFuncName meta data associated with a function.
static std::unique_ptr< ValueProfData > allocValueProfData(uint32_t TotalSize)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr UniformCountersBegin(uintptr_t) UniformCountersBegin -(uintptr_t) DataBegin struct llvm::ValueProfData ValueProfData
This is the header of the data structure that defines the on-disk layout of the value profile data of...
MDNode * mayHaveValueProfileOfKind(const Instruction &Inst, InstrProfValueKind ValueKind)
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
cl::opt< bool > EnableVTableProfileUse("enable-vtable-profile-use", cl::init(false), cl::desc("If ThinLTO and WPD is enabled and this option is true, vtable " "profiles will be used by ICP pass for more efficient indirect " "call sequence. If false, type profiles won't be used."))
uint64_t getInstrMaxCountValue()
Return the max count value. We reserver a few large values for special use.
Definition InstrProf.h:97
LLVM_ABI bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI std::string getPGOName(const GlobalVariable &V, bool InLTO=false)
LLVM_ABI GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
INSTR_PROF_VISIBILITY uint32_t getValueProfDataSize(ValueProfRecordClosure *Closure)
Return the total size in bytes of the on-disk value profile data given the data stored in Record.
LLVM_ABI Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
InstrProfSectKind
Definition InstrProf.h:91
LLVM_ABI Error readAndDecodeStrings(StringRef NameStrings, std::function< Error(StringRef)> NameCallback)
NameStrings is a string composed of one or more possibly encoded sub-strings.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition MathExtras.h:685
INSTR_PROF_VISIBILITY ValueProfRecord * getFirstValueProfRecord(ValueProfData *VPD)
Return the first ValueProfRecord instance.
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition InstrProf.h:225
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
INSTR_PROF_VISIBILITY ValueProfData * serializeValueProfDataFrom(ValueProfRecordClosure *Closure, ValueProfData *DstData)
Extract value profile data of a function from the Closure and serialize the data into DstData if it i...
INSTR_PROF_VISIBILITY InstrProfValueData * getValueProfRecordValueData(ValueProfRecord *VPR)
Return the pointer to the start of value data array.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:94
static std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO, MDNode *PGONameMetadata)
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Other
Any other memory.
Definition ModRef.h:68
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
instrprof_error
Definition InstrProf.h:410
InstrProfValueKind
Definition InstrProf.h:323
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
Definition MathExtras.h:639
LLVM_ABI const std::error_category & instrprof_category()
LLVM_ABI Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
static StringRef getStrippedSourceFileName(const GlobalObject &GO)
ArrayRef(const T &OneElt) -> ArrayRef< T >
uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind)
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
LLVM_ABI bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
constexpr char GlobalIdentifierDelimiter
Definition GlobalValue.h:47
LLVM_ABI Error collectGlobalObjectNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (names of global objects like functions or, virtual tables) NameStrs,...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
void setPGOFuncVisibility(Module &M, GlobalVariable *FuncNameVar)
INSTR_PROF_VISIBILITY INSTR_PROF_INLINE uint32_t getValueProfRecordNumValueData(ValueProfRecord *This)
Return the total number of value data for This record.
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition LEB128.h:79
uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK, uint32_t S)
static ValueProfRecordClosure InstrProfRecordClosure
LLVM_ABI std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix)
static void mergeUniformityBits(std::vector< uint8_t > &Dst, ArrayRef< uint8_t > Src)
endianness
Definition bit.h:71
static std::optional< std::string > lookupPGONameFromMetadata(MDNode *MD)
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:610
LLVM_ABI bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
LLVM_ABI bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
StringRef getPGONameMetadataName()
Definition InstrProf.h:355
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
const uint64_t NOMORE_ICP_MAGICNUM
Magic number in the value profile metadata showing a target has been promoted for the instruction and...
Definition Metadata.h:59
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
uint32_t getNumValueKindsInstrProf(const void *Record)
ValueProfRecordClosure Interface implementation for InstrProfRecord class.
ValueProfData * allocValueProfDataInstrProf(size_t TotalSizeInBytes)
uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind)
static std::string getIRPGONameForGlobalObject(const GlobalObject &GO, GlobalValue::LinkageTypes Linkage, StringRef FileName)
cl::opt< bool > EnableVTableValueProfiling("enable-vtable-value-profiling", cl::init(false), cl::desc("If true, the virtual table address will be instrumented to know " "the types of a C++ pointer. The information is used in indirect " "call promotion to do selective vtable-based comparison."))
#define N
std::array< double, IPVK_Last - IPVK_First+1 > ValueCounts
Definition InstrProf.h:819
LLVM_ABI uint64_t getIndexedProfileVersion() const
LLVM_ABI size_t size() const
static LLVM_ABI Expected< Header > readFromBuffer(const unsigned char *Buffer)
Profiling information for a single function.
Definition InstrProf.h:907
LLVM_ABI void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap of value profile counts.
std::vector< uint64_t > Counts
Definition InstrProf.h:908
ArrayRef< InstrProfValueData > getValueArrayForSite(uint32_t ValueKind, uint32_t Site) const
Return the array of profiled values at Site.
Definition InstrProf.h:1153
uint16_t OffloadDeviceWaveSize
Definition InstrProf.h:917
CountPseudoKind getCountPseudoKind() const
Definition InstrProf.h:1036
LLVM_ABI void accumulateCounts(CountSumOrPercent &Sum) const
Compute the sums of all counts and store in Sum.
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition InstrProf.h:1148
std::vector< uint64_t > UniformCounts
For AMDGPU offload profiling: raw or merged uniform counters.
Definition InstrProf.h:912
void setPseudoCount(CountPseudoKind Kind)
Definition InstrProf.h:1044
LLVM_ABI void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
LLVM_ABI void addValueData(uint32_t ValueKind, uint32_t Site, ArrayRef< InstrProfValueData > VData, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
std::vector< uint8_t > UniformityBits
For AMDGPU offload profiling: 1 bit per basic block indicating whether the block is usually entered w...
Definition InstrProf.h:916
LLVM_ABI void overlap(InstrProfRecord &Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff)
Compute the overlap b/w this IntrprofRecord and Other.
std::vector< uint8_t > BitmapBytes
Definition InstrProf.h:909
LLVM_ABI void computeBlockUniformity()
Recompute uniformity metadata from raw uniform counters, when present.
LLVM_ABI void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by a factor of (N / D).
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition InstrProf.h:884
std::vector< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition InstrProf.h:877
LLVM_ABI void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight.
LLVM_ABI void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap b/w this record and Input record.
LLVM_ABI void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts by N (Numerator) / D (Denominator).
static LLVM_ABI const char * ValueProfile
LLVM_ABI void addOneMismatch(const CountSumOrPercent &MismatchFunc)
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
Definition InstrProf.h:860
LLVM_ABI Error accumulateCounts(const std::string &BaseFilename, const std::string &TestFilename, bool IsCS)
LLVM_ABI void dump(raw_fd_ostream &OS) const
CountSumOrPercent Overlap
Definition InstrProf.h:836
CountSumOrPercent Base
Definition InstrProf.h:832
LLVM_ABI void addOneUnique(const CountSumOrPercent &UniqueFunc)
const std::string * BaseFilename
Definition InstrProf.h:840
const std::string * TestFilename
Definition InstrProf.h:841
CountSumOrPercent Unique
Definition InstrProf.h:838
CountSumOrPercent Mismatch
Definition InstrProf.h:837
StringRef FuncName
Definition InstrProf.h:842
OverlapStatsLevel Level
Definition InstrProf.h:839
CountSumOrPercent Test
Definition InstrProf.h:834
static LLVM_ABI void createBPFunctionNodes(ArrayRef< TemporalProfTraceTy > Traces, std::vector< BPFunctionNode > &Nodes, bool RemoveOutlierUNs=true)
Use a set of temporal profile traces to create a list of balanced partitioning function nodes used by...
This is the header of the data structure that defines the on-disk layout of the value profile data of...
Definition InstrProf.h:477
uint32_t NumValueKinds
Definition InstrProf.h:491