LLVM 17.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"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Config/config.h"
21#include "llvm/IR/Constant.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/GlobalValue.h"
26#include "llvm/IR/Instruction.h"
27#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/MDBuilder.h"
29#include "llvm/IR/Metadata.h"
30#include "llvm/IR/Module.h"
31#include "llvm/IR/Type.h"
37#include "llvm/Support/Endian.h"
38#include "llvm/Support/Error.h"
40#include "llvm/Support/LEB128.h"
42#include "llvm/Support/Path.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstdint>
50#include <cstring>
51#include <memory>
52#include <string>
53#include <system_error>
54#include <type_traits>
55#include <utility>
56#include <vector>
57
58using namespace llvm;
59
61 "static-func-full-module-prefix", cl::init(true), cl::Hidden,
62 cl::desc("Use full module build paths in the profile counter names for "
63 "static functions."));
64
65// This option is tailored to users that have different top-level directory in
66// profile-gen and profile-use compilation. Users need to specific the number
67// of levels to strip. A value larger than the number of directories in the
68// source file will strip all the directory names and only leave the basename.
69//
70// Note current ThinLTO module importing for the indirect-calls assumes
71// the source directory name not being stripped. A non-zero option value here
72// can potentially prevent some inter-module indirect-call-promotions.
74 "static-func-strip-dirname-prefix", cl::init(0), cl::Hidden,
75 cl::desc("Strip specified level of directory name from source path in "
76 "the profile counter name for static functions."));
77
79 const std::string &ErrMsg = "") {
80 std::string Msg;
82
83 switch (Err) {
84 case instrprof_error::success:
85 OS << "success";
86 break;
87 case instrprof_error::eof:
88 OS << "end of File";
89 break;
90 case instrprof_error::unrecognized_format:
91 OS << "unrecognized instrumentation profile encoding format";
92 break;
93 case instrprof_error::bad_magic:
94 OS << "invalid instrumentation profile data (bad magic)";
95 break;
96 case instrprof_error::bad_header:
97 OS << "invalid instrumentation profile data (file header is corrupt)";
98 break;
99 case instrprof_error::unsupported_version:
100 OS << "unsupported instrumentation profile format version";
101 break;
102 case instrprof_error::unsupported_hash_type:
103 OS << "unsupported instrumentation profile hash type";
104 break;
105 case instrprof_error::too_large:
106 OS << "too much profile data";
107 break;
108 case instrprof_error::truncated:
109 OS << "truncated profile data";
110 break;
111 case instrprof_error::malformed:
112 OS << "malformed instrumentation profile data";
113 break;
114 case instrprof_error::missing_debug_info_for_correlation:
115 OS << "debug info for correlation is required";
116 break;
117 case instrprof_error::unexpected_debug_info_for_correlation:
118 OS << "debug info for correlation is not necessary";
119 break;
120 case instrprof_error::unable_to_correlate_profile:
121 OS << "unable to correlate profile";
122 break;
123 case instrprof_error::invalid_prof:
124 OS << "invalid profile created. Please file a bug "
125 "at: " BUG_REPORT_URL
126 " and include the profraw files that caused this error.";
127 break;
128 case instrprof_error::unknown_function:
129 OS << "no profile data available for function";
130 break;
131 case instrprof_error::hash_mismatch:
132 OS << "function control flow change detected (hash mismatch)";
133 break;
134 case instrprof_error::count_mismatch:
135 OS << "function basic block count change detected (counter mismatch)";
136 break;
137 case instrprof_error::counter_overflow:
138 OS << "counter overflow";
139 break;
140 case instrprof_error::value_site_count_mismatch:
141 OS << "function value site count change detected (counter mismatch)";
142 break;
143 case instrprof_error::compress_failed:
144 OS << "failed to compress data (zlib)";
145 break;
146 case instrprof_error::uncompress_failed:
147 OS << "failed to uncompress data (zlib)";
148 break;
149 case instrprof_error::empty_raw_profile:
150 OS << "empty raw profile file";
151 break;
152 case instrprof_error::zlib_unavailable:
153 OS << "profile uses zlib compression but the profile reader was built "
154 "without zlib support";
155 break;
156 case instrprof_error::raw_profile_version_mismatch:
157 OS << "raw profile version mismatch";
158 break;
159 }
160
161 // If optional error message is not empty, append it to the message.
162 if (!ErrMsg.empty())
163 OS << ": " << ErrMsg;
164
165 return OS.str();
166}
167
168namespace {
169
170// FIXME: This class is only here to support the transition to llvm::Error. It
171// will be removed once this transition is complete. Clients should prefer to
172// deal with the Error value directly, rather than converting to error_code.
173class InstrProfErrorCategoryType : public std::error_category {
174 const char *name() const noexcept override { return "llvm.instrprof"; }
175
176 std::string message(int IE) const override {
177 return getInstrProfErrString(static_cast<instrprof_error>(IE));
178 }
179};
180
181} // end anonymous namespace
182
183const std::error_category &llvm::instrprof_category() {
184 static InstrProfErrorCategoryType ErrorCategory;
185 return ErrorCategory;
186}
187
188namespace {
189
190const char *InstrProfSectNameCommon[] = {
191#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
192 SectNameCommon,
194};
195
196const char *InstrProfSectNameCoff[] = {
197#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
198 SectNameCoff,
200};
201
202const char *InstrProfSectNamePrefix[] = {
203#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
204 Prefix,
206};
207
208} // namespace
209
210namespace llvm {
211
213 "enable-name-compression",
214 cl::desc("Enable name/filename string compression"), cl::init(true));
215
218 bool AddSegmentInfo) {
219 std::string SectName;
220
221 if (OF == Triple::MachO && AddSegmentInfo)
222 SectName = InstrProfSectNamePrefix[IPSK];
223
224 if (OF == Triple::COFF)
225 SectName += InstrProfSectNameCoff[IPSK];
226 else
227 SectName += InstrProfSectNameCommon[IPSK];
228
229 if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
230 SectName += ",regular,live_support";
231
232 return SectName;
233}
234
236 if (IE == instrprof_error::success)
237 return;
238
239 if (FirstError == instrprof_error::success)
240 FirstError = IE;
241
242 switch (IE) {
244 ++NumHashMismatches;
245 break;
247 ++NumCountMismatches;
248 break;
250 ++NumCounterOverflows;
251 break;
253 ++NumValueSiteCountMismatches;
254 break;
255 default:
256 llvm_unreachable("Not a soft error");
257 }
258}
259
260std::string InstrProfError::message() const {
261 return getInstrProfErrString(Err, Msg);
262}
263
264char InstrProfError::ID = 0;
265
266std::string getPGOFuncName(StringRef RawFuncName,
268 StringRef FileName,
270 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
271}
272
273// Strip NumPrefix level of directory name from PathNameStr. If the number of
274// directory separators is less than NumPrefix, strip all the directories and
275// leave base file name only.
276static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
277 uint32_t Count = NumPrefix;
278 uint32_t Pos = 0, LastPos = 0;
279 for (auto & CI : PathNameStr) {
280 ++Pos;
282 LastPos = Pos;
283 --Count;
284 }
285 if (Count == 0)
286 break;
287 }
288 return PathNameStr.substr(LastPos);
289}
290
291// Return the PGOFuncName. This function has some special handling when called
292// in LTO optimization. The following only applies when calling in LTO passes
293// (when \c InLTO is true): LTO's internalization privatizes many global linkage
294// symbols. This happens after value profile annotation, but those internal
295// linkage functions should not have a source prefix.
296// Additionally, for ThinLTO mode, exported internal functions are promoted
297// and renamed. We need to ensure that the original internal PGO name is
298// used when computing the GUID that is compared against the profiled GUIDs.
299// To differentiate compiler generated internal symbols from original ones,
300// PGOFuncName meta data are created and attached to the original internal
301// symbols in the value profile annotation step
302// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
303// data, its original linkage must be non-internal.
304std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
305 if (!InLTO) {
306 StringRef FileName(F.getParent()->getSourceFileName());
307 uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
308 if (StripLevel < StaticFuncStripDirNamePrefix)
309 StripLevel = StaticFuncStripDirNamePrefix;
310 if (StripLevel)
311 FileName = stripDirPrefix(FileName, StripLevel);
312 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
313 }
314
315 // In LTO mode (when InLTO is true), first check if there is a meta data.
316 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
317 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
318 return S.str();
319 }
320
321 // If there is no meta data, the function must be a global before the value
322 // profile annotation pass. Its current linkage may be internal if it is
323 // internalized in LTO mode.
324 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
325}
326
328 if (FileName.empty())
329 return PGOFuncName;
330 // Drop the file name including ':'. See also getPGOFuncName.
331 if (PGOFuncName.startswith(FileName))
332 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
333 return PGOFuncName;
334}
335
336// \p FuncName is the string used as profile lookup key for the function. A
337// symbol is created to hold the name. Return the legalized symbol name.
338std::string getPGOFuncNameVarName(StringRef FuncName,
340 std::string VarName = std::string(getInstrProfNameVarPrefix());
341 VarName += FuncName;
342
343 if (!GlobalValue::isLocalLinkage(Linkage))
344 return VarName;
345
346 // Now fix up illegal chars in local VarName that may upset the assembler.
347 const char *InvalidChars = "-:<>/\"'";
348 size_t found = VarName.find_first_of(InvalidChars);
349 while (found != std::string::npos) {
350 VarName[found] = '_';
351 found = VarName.find_first_of(InvalidChars, found + 1);
352 }
353 return VarName;
354}
355
358 StringRef PGOFuncName) {
359 // We generally want to match the function's linkage, but available_externally
360 // and extern_weak both have the wrong semantics, and anything that doesn't
361 // need to link across compilation units doesn't need to be visible at all.
364 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
366 else if (Linkage == GlobalValue::InternalLinkage ||
369
370 auto *Value =
371 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
372 auto FuncNameVar =
373 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
374 getPGOFuncNameVarName(PGOFuncName, Linkage));
375
376 // Hide the symbol so that we correctly get a copy for each executable.
377 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
378 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
379
380 return FuncNameVar;
381}
382
384 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
385}
386
388 for (Function &F : M) {
389 // Function may not have a name: like using asm("") to overwrite the name.
390 // Ignore in this case.
391 if (!F.hasName())
392 continue;
393 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
394 if (Error E = addFuncName(PGOFuncName))
395 return E;
396 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
397 // In ThinLTO, local function may have been promoted to global and have
398 // suffix ".llvm." added to the function name. We need to add the
399 // stripped function name to the symbol table so that we can find a match
400 // from profile.
401 //
402 // We may have other suffixes similar as ".llvm." which are needed to
403 // be stripped before the matching, but ".__uniq." suffix which is used
404 // to differentiate internal linkage functions in different modules
405 // should be kept. Now this is the only suffix with the pattern ".xxx"
406 // which is kept before matching.
407 const std::string UniqSuffix = ".__uniq.";
408 auto pos = PGOFuncName.find(UniqSuffix);
409 // Search '.' after ".__uniq." if ".__uniq." exists, otherwise
410 // search '.' from the beginning.
411 if (pos != std::string::npos)
412 pos += UniqSuffix.length();
413 else
414 pos = 0;
415 pos = PGOFuncName.find('.', pos);
416 if (pos != std::string::npos && pos != 0) {
417 const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
418 if (Error E = addFuncName(OtherFuncName))
419 return E;
420 MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
421 }
422 }
423 Sorted = false;
424 finalizeSymtab();
425 return Error::success();
426}
427
429 finalizeSymtab();
430 auto It = partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) {
431 return A.first < Address;
432 });
433 // Raw function pointer collected by value profiler may be from
434 // external functions that are not instrumented. They won't have
435 // mapping data to be used by the deserializer. Force the value to
436 // be 0 in this case.
437 if (It != AddrToMD5Map.end() && It->first == Address)
438 return (uint64_t)It->second;
439 return 0;
440}
441
443 bool doCompression, std::string &Result) {
444 assert(!NameStrs.empty() && "No name data to emit");
445
446 uint8_t Header[16], *P = Header;
447 std::string UncompressedNameStrings =
448 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
449
450 assert(StringRef(UncompressedNameStrings)
451 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
452 "PGO name is invalid (contains separator token)");
453
454 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
455 P += EncLen;
456
457 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
458 EncLen = encodeULEB128(CompressedLen, P);
459 P += EncLen;
460 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
461 unsigned HeaderLen = P - &Header[0];
462 Result.append(HeaderStr, HeaderLen);
463 Result += InputStr;
464 return Error::success();
465 };
466
467 if (!doCompression) {
468 return WriteStringToResult(0, UncompressedNameStrings);
469 }
470
471 SmallVector<uint8_t, 128> CompressedNameStrings;
472 compression::zlib::compress(arrayRefFromStringRef(UncompressedNameStrings),
473 CompressedNameStrings,
475
476 return WriteStringToResult(CompressedNameStrings.size(),
477 toStringRef(CompressedNameStrings));
478}
479
481 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
482 StringRef NameStr =
483 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
484 return NameStr;
485}
486
488 std::string &Result, bool doCompression) {
489 std::vector<std::string> NameStrs;
490 for (auto *NameVar : NameVars) {
491 NameStrs.push_back(std::string(getPGOFuncNameVarInitializer(NameVar)));
492 }
494 NameStrs, compression::zlib::isAvailable() && doCompression, Result);
495}
496
498 const uint8_t *P = NameStrings.bytes_begin();
499 const uint8_t *EndP = NameStrings.bytes_end();
500 while (P < EndP) {
501 uint32_t N;
502 uint64_t UncompressedSize = decodeULEB128(P, &N);
503 P += N;
504 uint64_t CompressedSize = decodeULEB128(P, &N);
505 P += N;
506 bool isCompressed = (CompressedSize != 0);
507 SmallVector<uint8_t, 128> UncompressedNameStrings;
508 StringRef NameStrings;
509 if (isCompressed) {
511 return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
512
513 if (Error E = compression::zlib::decompress(ArrayRef(P, CompressedSize),
514 UncompressedNameStrings,
515 UncompressedSize)) {
516 consumeError(std::move(E));
517 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
518 }
519 P += CompressedSize;
520 NameStrings = toStringRef(UncompressedNameStrings);
521 } else {
522 NameStrings =
523 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
524 P += UncompressedSize;
525 }
526 // Now parse the name strings.
528 NameStrings.split(Names, getInstrProfNameSeparator());
529 for (StringRef &Name : Names)
530 if (Error E = Symtab.addFuncName(Name))
531 return E;
532
533 while (P < EndP && *P == 0)
534 P++;
535 }
536 return Error::success();
537}
538
540 uint64_t FuncSum = 0;
541 Sum.NumEntries += Counts.size();
542 for (uint64_t Count : Counts)
543 FuncSum += Count;
544 Sum.CountSum += FuncSum;
545
546 for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
547 uint64_t KindSum = 0;
548 uint32_t NumValueSites = getNumValueSites(VK);
549 for (size_t I = 0; I < NumValueSites; ++I) {
551 std::unique_ptr<InstrProfValueData[]> VD = getValueForSite(VK, I);
552 for (uint32_t V = 0; V < NV; V++)
553 KindSum += VD[V].Count;
554 }
555 Sum.ValueCounts[VK] += KindSum;
556 }
557}
558
560 uint32_t ValueKind,
561 OverlapStats &Overlap,
562 OverlapStats &FuncLevelOverlap) {
563 this->sortByTargetValues();
564 Input.sortByTargetValues();
565 double Score = 0.0f, FuncLevelScore = 0.0f;
566 auto I = ValueData.begin();
567 auto IE = ValueData.end();
568 auto J = Input.ValueData.begin();
569 auto JE = Input.ValueData.end();
570 while (I != IE && J != JE) {
571 if (I->Value == J->Value) {
572 Score += OverlapStats::score(I->Count, J->Count,
573 Overlap.Base.ValueCounts[ValueKind],
574 Overlap.Test.ValueCounts[ValueKind]);
575 FuncLevelScore += OverlapStats::score(
576 I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind],
577 FuncLevelOverlap.Test.ValueCounts[ValueKind]);
578 ++I;
579 } else if (I->Value < J->Value) {
580 ++I;
581 continue;
582 }
583 ++J;
584 }
585 Overlap.Overlap.ValueCounts[ValueKind] += Score;
586 FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
587}
588
589// Return false on mismatch.
592 OverlapStats &Overlap,
593 OverlapStats &FuncLevelOverlap) {
594 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
595 assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
596 if (!ThisNumValueSites)
597 return;
598
599 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
600 getOrCreateValueSitesForKind(ValueKind);
602 Other.getValueSitesForKind(ValueKind);
603 for (uint32_t I = 0; I < ThisNumValueSites; I++)
604 ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap,
605 FuncLevelOverlap);
606}
607
609 OverlapStats &FuncLevelOverlap,
610 uint64_t ValueCutoff) {
611 // FuncLevel CountSum for other should already computed and nonzero.
612 assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
613 accumulateCounts(FuncLevelOverlap.Base);
614 bool Mismatch = (Counts.size() != Other.Counts.size());
615
616 // Check if the value profiles mismatch.
617 if (!Mismatch) {
618 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
619 uint32_t ThisNumValueSites = getNumValueSites(Kind);
620 uint32_t OtherNumValueSites = Other.getNumValueSites(Kind);
621 if (ThisNumValueSites != OtherNumValueSites) {
622 Mismatch = true;
623 break;
624 }
625 }
626 }
627 if (Mismatch) {
628 Overlap.addOneMismatch(FuncLevelOverlap.Test);
629 return;
630 }
631
632 // Compute overlap for value counts.
633 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
634 overlapValueProfData(Kind, Other, Overlap, FuncLevelOverlap);
635
636 double Score = 0.0;
637 uint64_t MaxCount = 0;
638 // Compute overlap for edge counts.
639 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
640 Score += OverlapStats::score(Counts[I], Other.Counts[I],
641 Overlap.Base.CountSum, Overlap.Test.CountSum);
642 MaxCount = std::max(Other.Counts[I], MaxCount);
643 }
644 Overlap.Overlap.CountSum += Score;
645 Overlap.Overlap.NumEntries += 1;
646
647 if (MaxCount >= ValueCutoff) {
648 double FuncScore = 0.0;
649 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
650 FuncScore += OverlapStats::score(Counts[I], Other.Counts[I],
651 FuncLevelOverlap.Base.CountSum,
652 FuncLevelOverlap.Test.CountSum);
653 FuncLevelOverlap.Overlap.CountSum = FuncScore;
654 FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
655 FuncLevelOverlap.Valid = true;
656 }
657}
658
660 uint64_t Weight,
661 function_ref<void(instrprof_error)> Warn) {
662 this->sortByTargetValues();
663 Input.sortByTargetValues();
664 auto I = ValueData.begin();
665 auto IE = ValueData.end();
666 for (const InstrProfValueData &J : Input.ValueData) {
667 while (I != IE && I->Value < J.Value)
668 ++I;
669 if (I != IE && I->Value == J.Value) {
670 bool Overflowed;
671 I->Count = SaturatingMultiplyAdd(J.Count, Weight, I->Count, &Overflowed);
672 if (Overflowed)
674 ++I;
675 continue;
676 }
677 ValueData.insert(I, J);
678 }
679}
680
682 function_ref<void(instrprof_error)> Warn) {
683 for (InstrProfValueData &I : ValueData) {
684 bool Overflowed;
685 I.Count = SaturatingMultiply(I.Count, N, &Overflowed) / D;
686 if (Overflowed)
688 }
689}
690
691// Merge Value Profile data from Src record to this record for ValueKind.
692// Scale merged value counts by \p Weight.
693void InstrProfRecord::mergeValueProfData(
694 uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
695 function_ref<void(instrprof_error)> Warn) {
696 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
697 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
698 if (ThisNumValueSites != OtherNumValueSites) {
700 return;
701 }
702 if (!ThisNumValueSites)
703 return;
704 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
705 getOrCreateValueSitesForKind(ValueKind);
707 Src.getValueSitesForKind(ValueKind);
708 for (uint32_t I = 0; I < ThisNumValueSites; I++)
709 ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
710}
711
713 function_ref<void(instrprof_error)> Warn) {
714 // If the number of counters doesn't match we either have bad data
715 // or a hash collision.
716 if (Counts.size() != Other.Counts.size()) {
718 return;
719 }
720
721 // Special handling of the first count as the PseudoCount.
722 CountPseudoKind OtherKind = Other.getCountPseudoKind();
724 if (OtherKind != NotPseudo || ThisKind != NotPseudo) {
725 // We don't allow the merge of a profile with pseudo counts and
726 // a normal profile (i.e. without pesudo counts).
727 // Profile supplimenation should be done after the profile merge.
728 if (OtherKind == NotPseudo || ThisKind == NotPseudo) {
730 return;
731 }
732 if (OtherKind == PseudoHot || ThisKind == PseudoHot)
734 else
736 return;
737 }
738
739 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
740 bool Overflowed;
742 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
745 Overflowed = true;
746 }
747 Counts[I] = Value;
748 if (Overflowed)
750 }
751
752 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
753 mergeValueProfData(Kind, Other, Weight, Warn);
754}
755
756void InstrProfRecord::scaleValueProfData(
757 uint32_t ValueKind, uint64_t N, uint64_t D,
758 function_ref<void(instrprof_error)> Warn) {
759 for (auto &R : getValueSitesForKind(ValueKind))
760 R.scale(N, D, Warn);
761}
762
764 function_ref<void(instrprof_error)> Warn) {
765 assert(D != 0 && "D cannot be 0");
766 for (auto &Count : this->Counts) {
767 bool Overflowed;
768 Count = SaturatingMultiply(Count, N, &Overflowed) / D;
769 if (Count > getInstrMaxCountValue()) {
770 Count = getInstrMaxCountValue();
771 Overflowed = true;
772 }
773 if (Overflowed)
775 }
776 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
777 scaleValueProfData(Kind, N, D, Warn);
778}
779
780// Map indirect call target name hash to name string.
781uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
782 InstrProfSymtab *SymTab) {
783 if (!SymTab)
784 return Value;
785
786 if (ValueKind == IPVK_IndirectCallTarget)
787 return SymTab->getFunctionHashFromAddress(Value);
788
789 return Value;
790}
791
793 InstrProfValueData *VData, uint32_t N,
795 for (uint32_t I = 0; I < N; I++) {
796 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
797 }
798 std::vector<InstrProfValueSiteRecord> &ValueSites =
799 getOrCreateValueSitesForKind(ValueKind);
800 if (N == 0)
801 ValueSites.emplace_back();
802 else
803 ValueSites.emplace_back(VData, VData + N);
804}
805
806#define INSTR_PROF_COMMON_API_IMPL
808
809/*!
810 * ValueProfRecordClosure Interface implementation for InstrProfRecord
811 * class. These C wrappers are used as adaptors so that C++ code can be
812 * invoked as callbacks.
813 */
815 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
816}
817
819 return reinterpret_cast<const InstrProfRecord *>(Record)
820 ->getNumValueSites(VKind);
821}
822
824 return reinterpret_cast<const InstrProfRecord *>(Record)
825 ->getNumValueData(VKind);
826}
827
829 uint32_t S) {
830 return reinterpret_cast<const InstrProfRecord *>(R)
831 ->getNumValueDataForSite(VK, S);
832}
833
834void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
835 uint32_t K, uint32_t S) {
836 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
837}
838
839ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
840 ValueProfData *VD =
841 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
842 memset(VD, 0, TotalSizeInBytes);
843 return VD;
844}
845
846static ValueProfRecordClosure InstrProfRecordClosure = {
847 nullptr,
852 nullptr,
855
856// Wrapper implementation using the closure mechanism.
857uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
858 auto Closure = InstrProfRecordClosure;
859 Closure.Record = &Record;
860 return getValueProfDataSize(&Closure);
861}
862
863// Wrapper implementation using the closure mechanism.
864std::unique_ptr<ValueProfData>
865ValueProfData::serializeFrom(const InstrProfRecord &Record) {
867
868 std::unique_ptr<ValueProfData> VPD(
869 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
870 return VPD;
871}
872
873void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
874 InstrProfSymtab *SymTab) {
875 Record.reserveSites(Kind, NumValueSites);
876
877 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
878 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
879 uint8_t ValueDataCount = this->SiteCountArray[VSite];
880 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, SymTab);
881 ValueData += ValueDataCount;
882 }
883}
884
885// For writing/serializing, Old is the host endianness, and New is
886// byte order intended on disk. For Reading/deserialization, Old
887// is the on-disk source endianness, and New is the host endianness.
888void ValueProfRecord::swapBytes(support::endianness Old,
890 using namespace support;
891
892 if (Old == New)
893 return;
894
895 if (getHostEndianness() != Old) {
896 sys::swapByteOrder<uint32_t>(NumValueSites);
897 sys::swapByteOrder<uint32_t>(Kind);
898 }
899 uint32_t ND = getValueProfRecordNumValueData(this);
900 InstrProfValueData *VD = getValueProfRecordValueData(this);
901
902 // No need to swap byte array: SiteCountArrray.
903 for (uint32_t I = 0; I < ND; I++) {
904 sys::swapByteOrder<uint64_t>(VD[I].Value);
905 sys::swapByteOrder<uint64_t>(VD[I].Count);
906 }
907 if (getHostEndianness() == Old) {
908 sys::swapByteOrder<uint32_t>(NumValueSites);
909 sys::swapByteOrder<uint32_t>(Kind);
910 }
911}
912
913void ValueProfData::deserializeTo(InstrProfRecord &Record,
914 InstrProfSymtab *SymTab) {
915 if (NumValueKinds == 0)
916 return;
917
918 ValueProfRecord *VR = getFirstValueProfRecord(this);
919 for (uint32_t K = 0; K < NumValueKinds; K++) {
920 VR->deserializeTo(Record, SymTab);
921 VR = getValueProfRecordNext(VR);
922 }
923}
924
925template <class T>
926static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
927 using namespace support;
928
929 if (Orig == little)
930 return endian::readNext<T, little, unaligned>(D);
931 else
932 return endian::readNext<T, big, unaligned>(D);
933}
934
935static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
936 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
937 ValueProfData());
938}
939
940Error ValueProfData::checkIntegrity() {
941 if (NumValueKinds > IPVK_Last + 1)
942 return make_error<InstrProfError>(
943 instrprof_error::malformed, "number of value profile kinds is invalid");
944 // Total size needs to be multiple of quadword size.
945 if (TotalSize % sizeof(uint64_t))
946 return make_error<InstrProfError>(
947 instrprof_error::malformed, "total size is not multiples of quardword");
948
949 ValueProfRecord *VR = getFirstValueProfRecord(this);
950 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
951 if (VR->Kind > IPVK_Last)
952 return make_error<InstrProfError>(instrprof_error::malformed,
953 "value kind is invalid");
954 VR = getValueProfRecordNext(VR);
955 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
956 return make_error<InstrProfError>(
958 "value profile address is greater than total size");
959 }
960 return Error::success();
961}
962
964ValueProfData::getValueProfData(const unsigned char *D,
965 const unsigned char *const BufferEnd,
966 support::endianness Endianness) {
967 using namespace support;
968
969 if (D + sizeof(ValueProfData) > BufferEnd)
970 return make_error<InstrProfError>(instrprof_error::truncated);
971
972 const unsigned char *Header = D;
973 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
974 if (D + TotalSize > BufferEnd)
975 return make_error<InstrProfError>(instrprof_error::too_large);
976
977 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
978 memcpy(VPD.get(), D, TotalSize);
979 // Byte swap.
980 VPD->swapBytesToHost(Endianness);
981
982 Error E = VPD->checkIntegrity();
983 if (E)
984 return std::move(E);
985
986 return std::move(VPD);
987}
988
989void ValueProfData::swapBytesToHost(support::endianness Endianness) {
990 using namespace support;
991
992 if (Endianness == getHostEndianness())
993 return;
994
995 sys::swapByteOrder<uint32_t>(TotalSize);
996 sys::swapByteOrder<uint32_t>(NumValueKinds);
997
998 ValueProfRecord *VR = getFirstValueProfRecord(this);
999 for (uint32_t K = 0; K < NumValueKinds; K++) {
1000 VR->swapBytes(Endianness, getHostEndianness());
1001 VR = getValueProfRecordNext(VR);
1002 }
1003}
1004
1005void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
1006 using namespace support;
1007
1008 if (Endianness == getHostEndianness())
1009 return;
1010
1011 ValueProfRecord *VR = getFirstValueProfRecord(this);
1012 for (uint32_t K = 0; K < NumValueKinds; K++) {
1013 ValueProfRecord *NVR = getValueProfRecordNext(VR);
1014 VR->swapBytes(getHostEndianness(), Endianness);
1015 VR = NVR;
1016 }
1017 sys::swapByteOrder<uint32_t>(TotalSize);
1018 sys::swapByteOrder<uint32_t>(NumValueKinds);
1019}
1020
1022 const InstrProfRecord &InstrProfR,
1023 InstrProfValueKind ValueKind, uint32_t SiteIdx,
1024 uint32_t MaxMDCount) {
1025 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
1026 if (!NV)
1027 return;
1028
1029 uint64_t Sum = 0;
1030 std::unique_ptr<InstrProfValueData[]> VD =
1031 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
1032
1033 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
1034 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
1035}
1036
1039 uint64_t Sum, InstrProfValueKind ValueKind,
1040 uint32_t MaxMDCount) {
1041 LLVMContext &Ctx = M.getContext();
1042 MDBuilder MDHelper(Ctx);
1044 // Tag
1045 Vals.push_back(MDHelper.createString("VP"));
1046 // Value Kind
1047 Vals.push_back(MDHelper.createConstant(
1048 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
1049 // Total Count
1050 Vals.push_back(
1051 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
1052
1053 // Value Profile Data
1054 uint32_t MDCount = MaxMDCount;
1055 for (auto &VD : VDs) {
1056 Vals.push_back(MDHelper.createConstant(
1057 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
1058 Vals.push_back(MDHelper.createConstant(
1059 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
1060 if (--MDCount == 0)
1061 break;
1062 }
1063 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
1064}
1065
1067 InstrProfValueKind ValueKind,
1068 uint32_t MaxNumValueData,
1069 InstrProfValueData ValueData[],
1070 uint32_t &ActualNumValueData, uint64_t &TotalC,
1071 bool GetNoICPValue) {
1072 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
1073 if (!MD)
1074 return false;
1075
1076 unsigned NOps = MD->getNumOperands();
1077
1078 if (NOps < 5)
1079 return false;
1080
1081 // Operand 0 is a string tag "VP":
1082 MDString *Tag = cast<MDString>(MD->getOperand(0));
1083 if (!Tag)
1084 return false;
1085
1086 if (!Tag->getString().equals("VP"))
1087 return false;
1088
1089 // Now check kind:
1090 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
1091 if (!KindInt)
1092 return false;
1093 if (KindInt->getZExtValue() != ValueKind)
1094 return false;
1095
1096 // Get total count
1097 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
1098 if (!TotalCInt)
1099 return false;
1100 TotalC = TotalCInt->getZExtValue();
1101
1102 ActualNumValueData = 0;
1103
1104 for (unsigned I = 3; I < NOps; I += 2) {
1105 if (ActualNumValueData >= MaxNumValueData)
1106 break;
1107 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
1108 ConstantInt *Count =
1109 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
1110 if (!Value || !Count)
1111 return false;
1112 uint64_t CntValue = Count->getZExtValue();
1113 if (!GetNoICPValue && (CntValue == NOMORE_ICP_MAGICNUM))
1114 continue;
1115 ValueData[ActualNumValueData].Value = Value->getZExtValue();
1116 ValueData[ActualNumValueData].Count = CntValue;
1117 ActualNumValueData++;
1118 }
1119 return true;
1120}
1121
1123 return F.getMetadata(getPGOFuncNameMetadataName());
1124}
1125
1127 // Only for internal linkage functions.
1128 if (PGOFuncName == F.getName())
1129 return;
1130 // Don't create duplicated meta-data.
1132 return;
1133 LLVMContext &C = F.getContext();
1134 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
1135 F.setMetadata(getPGOFuncNameMetadataName(), N);
1136}
1137
1138bool needsComdatForCounter(const Function &F, const Module &M) {
1139 if (F.hasComdat())
1140 return true;
1141
1142 if (!Triple(M.getTargetTriple()).supportsCOMDAT())
1143 return false;
1144
1145 // See createPGOFuncNameVar for more details. To avoid link errors, profile
1146 // counters for function with available_externally linkage needs to be changed
1147 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
1148 // created. Without using comdat, duplicate entries won't be removed by the
1149 // linker leading to increased data segement size and raw profile size. Even
1150 // worse, since the referenced counter from profile per-function data object
1151 // will be resolved to the common strong definition, the profile counts for
1152 // available_externally functions will end up being duplicated in raw profile
1153 // data. This can result in distorted profile as the counts of those dups
1154 // will be accumulated by the profile merger.
1155 GlobalValue::LinkageTypes Linkage = F.getLinkage();
1156 if (Linkage != GlobalValue::ExternalWeakLinkage &&
1158 return false;
1159
1160 return true;
1161}
1162
1163// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
1164bool isIRPGOFlagSet(const Module *M) {
1165 auto IRInstrVar =
1166 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1167 if (!IRInstrVar || IRInstrVar->hasLocalLinkage())
1168 return false;
1169
1170 // For CSPGO+LTO, this variable might be marked as non-prevailing and we only
1171 // have the decl.
1172 if (IRInstrVar->isDeclaration())
1173 return true;
1174
1175 // Check if the flag is set.
1176 if (!IRInstrVar->hasInitializer())
1177 return false;
1178
1179 auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
1180 if (!InitVal)
1181 return false;
1182 return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
1183}
1184
1185// Check if we can safely rename this Comdat function.
1186bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
1187 if (F.getName().empty())
1188 return false;
1189 if (!needsComdatForCounter(F, *(F.getParent())))
1190 return false;
1191 // Unsafe to rename the address-taken function (which can be used in
1192 // function comparison).
1193 if (CheckAddressTaken && F.hasAddressTaken())
1194 return false;
1195 // Only safe to do if this function may be discarded if it is not used
1196 // in the compilation unit.
1197 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
1198 return false;
1199
1200 // For AvailableExternallyLinkage functions.
1201 if (!F.hasComdat()) {
1203 return true;
1204 }
1205 return true;
1206}
1207
1208// Create the variable for the profile file name.
1209void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
1210 if (InstrProfileOutput.empty())
1211 return;
1212 Constant *ProfileNameConst =
1213 ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true);
1214 GlobalVariable *ProfileNameVar = new GlobalVariable(
1215 M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
1216 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
1218 Triple TT(M.getTargetTriple());
1219 if (TT.supportsCOMDAT()) {
1221 ProfileNameVar->setComdat(M.getOrInsertComdat(
1222 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
1223 }
1224}
1225
1226Error OverlapStats::accumulateCounts(const std::string &BaseFilename,
1227 const std::string &TestFilename,
1228 bool IsCS) {
1229 auto getProfileSum = [IsCS](const std::string &Filename,
1230 CountSumOrPercent &Sum) -> Error {
1231 // This function is only used from llvm-profdata that doesn't use any kind
1232 // of VFS. Just create a default RealFileSystem to read profiles.
1233 auto FS = vfs::getRealFileSystem();
1234 auto ReaderOrErr = InstrProfReader::create(Filename, *FS);
1235 if (Error E = ReaderOrErr.takeError()) {
1236 return E;
1237 }
1238 auto Reader = std::move(ReaderOrErr.get());
1239 Reader->accumulateCounts(Sum, IsCS);
1240 return Error::success();
1241 };
1242 auto Ret = getProfileSum(BaseFilename, Base);
1243 if (Ret)
1244 return Ret;
1245 Ret = getProfileSum(TestFilename, Test);
1246 if (Ret)
1247 return Ret;
1248 this->BaseFilename = &BaseFilename;
1249 this->TestFilename = &TestFilename;
1250 Valid = true;
1251 return Error::success();
1252}
1253
1255 Mismatch.NumEntries += 1;
1256 Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
1257 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1258 if (Test.ValueCounts[I] >= 1.0f)
1260 MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
1261 }
1262}
1263
1265 Unique.NumEntries += 1;
1266 Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
1267 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1268 if (Test.ValueCounts[I] >= 1.0f)
1269 Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
1270 }
1271}
1272
1274 if (!Valid)
1275 return;
1276
1277 const char *EntryName =
1278 (Level == ProgramLevel ? "functions" : "edge counters");
1279 if (Level == ProgramLevel) {
1280 OS << "Profile overlap infomation for base_profile: " << *BaseFilename
1281 << " and test_profile: " << *TestFilename << "\nProgram level:\n";
1282 } else {
1283 OS << "Function level:\n"
1284 << " Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
1285 }
1286
1287 OS << " # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
1288 if (Mismatch.NumEntries)
1289 OS << " # of " << EntryName << " mismatch: " << Mismatch.NumEntries
1290 << "\n";
1291 if (Unique.NumEntries)
1292 OS << " # of " << EntryName
1293 << " only in test_profile: " << Unique.NumEntries << "\n";
1294
1295 OS << " Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100)
1296 << "\n";
1297 if (Mismatch.NumEntries)
1298 OS << " Mismatched count percentage (Edge): "
1299 << format("%.3f%%", Mismatch.CountSum * 100) << "\n";
1300 if (Unique.NumEntries)
1301 OS << " Percentage of Edge profile only in test_profile: "
1302 << format("%.3f%%", Unique.CountSum * 100) << "\n";
1303 OS << " Edge profile base count sum: " << format("%.0f", Base.CountSum)
1304 << "\n"
1305 << " Edge profile test count sum: " << format("%.0f", Test.CountSum)
1306 << "\n";
1307
1308 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1309 if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
1310 continue;
1311 char ProfileKindName[20];
1312 switch (I) {
1313 case IPVK_IndirectCallTarget:
1314 strncpy(ProfileKindName, "IndirectCall", 19);
1315 break;
1316 case IPVK_MemOPSize:
1317 strncpy(ProfileKindName, "MemOP", 19);
1318 break;
1319 default:
1320 snprintf(ProfileKindName, 19, "VP[%d]", I);
1321 break;
1322 }
1323 OS << " " << ProfileKindName
1324 << " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100)
1325 << "\n";
1326 if (Mismatch.NumEntries)
1327 OS << " Mismatched count percentage (" << ProfileKindName
1328 << "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n";
1329 if (Unique.NumEntries)
1330 OS << " Percentage of " << ProfileKindName
1331 << " profile only in test_profile: "
1332 << format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n";
1333 OS << " " << ProfileKindName
1334 << " profile base count sum: " << format("%.0f", Base.ValueCounts[I])
1335 << "\n"
1336 << " " << ProfileKindName
1337 << " profile test count sum: " << format("%.0f", Test.ValueCounts[I])
1338 << "\n";
1339 }
1340}
1341
1342namespace IndexedInstrProf {
1343// A C++14 compatible version of the offsetof macro.
1344template <typename T1, typename T2>
1345inline size_t constexpr offsetOf(T1 T2::*Member) {
1346 constexpr T2 Object{};
1347 return size_t(&(Object.*Member)) - size_t(&Object);
1348}
1349
1350static inline uint64_t read(const unsigned char *Buffer, size_t Offset) {
1351 return *reinterpret_cast<const uint64_t *>(Buffer + Offset);
1352}
1353
1355 using namespace support;
1356 return endian::byte_swap<uint64_t, little>(Version);
1357}
1358
1359Expected<Header> Header::readFromBuffer(const unsigned char *Buffer) {
1360 using namespace support;
1361 static_assert(std::is_standard_layout_v<Header>,
1362 "The header should be standard layout type since we use offset "
1363 "of fields to read.");
1364 Header H;
1365
1366 H.Magic = read(Buffer, offsetOf(&Header::Magic));
1367 // Check the magic number.
1368 uint64_t Magic = endian::byte_swap<uint64_t, little>(H.Magic);
1370 return make_error<InstrProfError>(instrprof_error::bad_magic);
1371
1372 // Read the version.
1373 H.Version = read(Buffer, offsetOf(&Header::Version));
1374 if (GET_VERSION(H.formatVersion()) >
1376 return make_error<InstrProfError>(instrprof_error::unsupported_version);
1377
1378 switch (GET_VERSION(H.formatVersion())) {
1379 // When a new field is added in the header add a case statement here to
1380 // populate it.
1381 static_assert(
1383 "Please update the reading code below if a new field has been added, "
1384 "if not add a case statement to fall through to the latest version.");
1385 case 10ull:
1386 H.TemporalProfTracesOffset =
1388 [[fallthrough]];
1389 case 9ull:
1390 H.BinaryIdOffset = read(Buffer, offsetOf(&Header::BinaryIdOffset));
1391 [[fallthrough]];
1392 case 8ull:
1393 H.MemProfOffset = read(Buffer, offsetOf(&Header::MemProfOffset));
1394 [[fallthrough]];
1395 default: // Version7 (when the backwards compatible header was introduced).
1396 H.HashType = read(Buffer, offsetOf(&Header::HashType));
1397 H.HashOffset = read(Buffer, offsetOf(&Header::HashOffset));
1398 }
1399
1400 return H;
1401}
1402
1403size_t Header::size() const {
1404 switch (GET_VERSION(formatVersion())) {
1405 // When a new field is added to the header add a case statement here to
1406 // compute the size as offset of the new field + size of the new field. This
1407 // relies on the field being added to the end of the list.
1409 "Please update the size computation below if a new field has "
1410 "been added to the header, if not add a case statement to "
1411 "fall through to the latest version.");
1412 case 10ull:
1415 case 9ull:
1417 case 8ull:
1419 default: // Version7 (when the backwards compatible header was introduced).
1421 }
1422}
1423
1424} // namespace IndexedInstrProf
1425
1426} // end namespace llvm
aarch64 promote const
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")
#define LLVM_ATTRIBUTE_UNUSED
Definition: Compiler.h:172
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::string Name
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:78
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define H(x, y, z)
Definition: MD5.cpp:57
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
Definition: SMEABIPass.cpp:49
raw_pwrite_stream & OS
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
@ Names
Definition: TextStubV5.cpp:106
Defines the virtual file system interface vfs::FileSystem.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:152
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
iterator begin() const
Definition: ArrayRef.h:151
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:158
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2925
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
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:145
This is an important base class in LLVM.
Definition: Constant.h:41
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
static ErrorSuccess success()
Create a success value.
Definition: Error.h:330
Tagged union holding either a T or a Error.
Definition: Error.h:470
void setComdat(Comdat *C)
Definition: Globals.cpp:196
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:404
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:532
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:591
bool isDiscardableIfUnused() const
Definition: GlobalValue.h:543
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:64
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:250
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e....
Definition: Globals.cpp:168
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:50
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:48
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:52
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:49
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:57
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:51
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
static char ID
Definition: InstrProf.h:380
std::string message() const override
Return the error message as a string.
Definition: InstrProf.cpp:260
static Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const InstrProfCorrelator *Correlator=nullptr)
Factory method to create an appropriately typed reader for the given instrprof file.
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
Definition: InstrProf.h:459
uint64_t getFunctionHashFromAddress(uint64_t Address)
Return a function's hash, or 0, if the function isn't in this SymTab.
Definition: InstrProf.cpp:428
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
Error addFuncName(StringRef FuncName)
Update the symtab by adding FuncName to the table.
Definition: InstrProf.h:520
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:275
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1521
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition: MDBuilder.cpp:24
MDString * createString(StringRef Str)
Return the given string as metadata.
Definition: MDBuilder.cpp:20
Metadata node.
Definition: Metadata.h:950
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1303
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1416
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1309
A single uniqued string.
Definition: Metadata.h:611
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:499
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:305
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
void addError(instrprof_error IE)
Track a soft error (IE) and increment its associated counter.
Definition: InstrProf.cpp:235
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:698
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:222
const unsigned char * bytes_end() const
Definition: StringRef.h:118
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:569
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:607
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
bool startswith(StringRef Prefix) const
Definition: StringRef.h:261
const unsigned char * bytes_begin() const
Definition: StringRef.h:115
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool supportsCOMDAT() const
Tests whether the target supports comdat.
Definition: Triple.h:976
ObjectFormatType
Definition: Triple.h:280
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
See the file comment.
Definition: ValueMap.h:84
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
An efficient, type-erasing, non-owning reference to a callable.
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:454
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:642
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
static uint64_t read(const unsigned char *Buffer, size_t Offset)
Definition: InstrProf.cpp:1350
const uint64_t Magic
Definition: InstrProf.h:1038
size_t constexpr offsetOf(T1 T2::*Member)
Definition: InstrProf.cpp:1345
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
void compress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &CompressedBuffer, int Level=DefaultCompression)
Error decompress(ArrayRef< uint8_t > Input, uint8_t *Output, size_t &UncompressedSize)
constexpr int BestSizeCompression
Definition: Compression.h:39
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
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:602
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.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:406
bool getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, InstrProfValueData ValueData[], uint32_t &ActualNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst which is annotated with value profile meta data.
Definition: InstrProf.cpp:1066
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition: InstrProf.h:90
Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab)
NameStrings is a string composed of one of more sub-strings encoded in the format described above.
Definition: InstrProf.cpp:497
std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Return the modified name for function F suitable to be used the key for profile lookup.
Definition: InstrProf.cpp:304
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
Definition: InstrProf.cpp:1126
StringRef getPGOFuncNameMetadataName()
Definition: InstrProf.h:272
void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst, uint32_t K, uint32_t S)
Definition: InstrProf.cpp:834
cl::opt< bool > DoInstrProfNameCompression
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
Definition: InstrProf.cpp:327
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition: STLExtras.h:2076
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:128
MDNode * getPGOFuncNameMetadata(const Function &F)
Return the PGOFuncName meta data associated with a function.
Definition: InstrProf.cpp:1122
static std::unique_ptr< ValueProfData > allocValueProfData(uint32_t TotalSize)
Definition: InstrProf.cpp:935
static T swapToHostOrder(const unsigned char *&D, support::endianness Orig)
Definition: InstrProf.cpp:926
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:216
uint64_t getInstrMaxCountValue()
Return the max count value. We reserver a few large values for special use.
Definition: InstrProf.h:64
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
Definition: InstrProf.cpp:383
void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
Definition: InstrProf.cpp:1021
InstrProfSectKind
Definition: InstrProf.h:58
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
Definition: InstrProf.cpp:480
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:658
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition: InstrProf.h:169
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
support::endianness getHostEndianness()
Definition: InstrProf.h:1004
instrprof_error
Definition: InstrProf.h:310
InstrProfValueKind
Definition: InstrProf.h:244
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:612
const std::error_category & instrprof_category()
Definition: InstrProf.cpp:183
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:2011
bool needsComdatForCounter(const Function &F, const Module &M)
Check if we can use Comdat for profile variables.
Definition: InstrProf.cpp:1138
uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind)
Definition: InstrProf.cpp:818
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:1186
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
Definition: InstrProf.cpp:1209
Error collectPGOFuncNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (function PGO names) NameStrs, the method generates a combined string Resul...
Definition: InstrProf.cpp:442
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:80
uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK, uint32_t S)
Definition: InstrProf.cpp:828
static ValueProfRecordClosure InstrProfRecordClosure
Definition: InstrProf.cpp:846
std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
Definition: InstrProf.cpp:338
static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix)
Definition: InstrProf.cpp:276
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
Definition: InstrProf.cpp:1164
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1043
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:56
uint32_t getNumValueKindsInstrProf(const void *Record)
ValueProfRecordClosure Interface implementation for InstrProfRecord class.
Definition: InstrProf.cpp:814
ValueProfData * allocValueProfDataInstrProf(size_t TotalSizeInBytes)
Definition: InstrProf.cpp:839
uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind)
Definition: InstrProf.cpp:823
#define N
double ValueCounts[IPVK_Last - IPVK_First+1]
Definition: InstrProf.h:652
uint64_t formatVersion() const
Definition: InstrProf.cpp:1354
static Expected< Header > readFromBuffer(const unsigned char *Buffer)
Definition: InstrProf.cpp:1359
Profiling information for a single function.
Definition: InstrProf.h:743
void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap of value profile counts.
Definition: InstrProf.cpp:590
std::vector< uint64_t > Counts
Definition: InstrProf.h:744
CountPseudoKind getCountPseudoKind() const
Definition: InstrProf.h:849
void accumulateCounts(CountSumOrPercent &Sum) const
Compute the sums of all counts and store in Sum.
Definition: InstrProf.cpp:539
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition: InstrProf.h:958
void setPseudoCount(CountPseudoKind Kind)
Definition: InstrProf.h:857
void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
Definition: InstrProf.cpp:712
void addValueData(uint32_t ValueKind, uint32_t Site, InstrProfValueData *VData, uint32_t N, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
Definition: InstrProf.cpp:792
uint32_t getNumValueDataForSite(uint32_t ValueKind, uint32_t Site) const
Return the number of value data collected for ValueKind at profiling site: Site.
Definition: InstrProf.h:962
void overlap(InstrProfRecord &Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff)
Compute the overlap b/w this IntrprofRecord and Other.
Definition: InstrProf.cpp:608
std::unique_ptr< InstrProfValueData[]> getValueForSite(uint32_t ValueKind, uint32_t Site, uint64_t *TotalC=nullptr) const
Return the array of profiled values at Site.
Definition: InstrProf.h:968
void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by a factor of (N / D).
Definition: InstrProf.cpp:763
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition: InstrProf.h:721
void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight.
Definition: InstrProf.cpp:659
void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap b/w this record and Input record.
Definition: InstrProf.cpp:559
std::list< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition: InstrProf.h:713
void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts by N (Numerator) / D (Denominator).
Definition: InstrProf.cpp:681
void addOneMismatch(const CountSumOrPercent &MismatchFunc)
Definition: InstrProf.cpp:1254
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
Definition: InstrProf.h:696
Error accumulateCounts(const std::string &BaseFilename, const std::string &TestFilename, bool IsCS)
Definition: InstrProf.cpp:1226
void dump(raw_fd_ostream &OS) const
Definition: InstrProf.cpp:1273
CountSumOrPercent Overlap
Definition: InstrProf.h:670
CountSumOrPercent Base
Definition: InstrProf.h:666
uint64_t FuncHash
Definition: InstrProf.h:677
void addOneUnique(const CountSumOrPercent &UniqueFunc)
Definition: InstrProf.cpp:1264
const std::string * BaseFilename
Definition: InstrProf.h:674
const std::string * TestFilename
Definition: InstrProf.h:675
CountSumOrPercent Unique
Definition: InstrProf.h:672
CountSumOrPercent Mismatch
Definition: InstrProf.h:671
StringRef FuncName
Definition: InstrProf.h:676
OverlapStatsLevel Level
Definition: InstrProf.h:673
CountSumOrPercent Test
Definition: InstrProf.h:668