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