1 //=-- InstrProf.cpp - Instrumented profiling format support -----------------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for clang's instrumentation based PGO and
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ProfileData/InstrProf.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/GlobalVariable.h"
20 #include "llvm/IR/MDBuilder.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/Compression.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/Path.h"
30 static cl::opt<bool> StaticFuncFullModulePrefix(
31 "static-func-full-module-prefix", cl::init(false),
32 cl::desc("Use full module build paths in the profile counter names for "
33 "static functions."));
36 std::string getInstrProfErrString(instrprof_error Err) {
38 case instrprof_error::success:
40 case instrprof_error::eof:
42 case instrprof_error::unrecognized_format:
43 return "Unrecognized instrumentation profile encoding format";
44 case instrprof_error::bad_magic:
45 return "Invalid instrumentation profile data (bad magic)";
46 case instrprof_error::bad_header:
47 return "Invalid instrumentation profile data (file header is corrupt)";
48 case instrprof_error::unsupported_version:
49 return "Unsupported instrumentation profile format version";
50 case instrprof_error::unsupported_hash_type:
51 return "Unsupported instrumentation profile hash type";
52 case instrprof_error::too_large:
53 return "Too much profile data";
54 case instrprof_error::truncated:
55 return "Truncated profile data";
56 case instrprof_error::malformed:
57 return "Malformed instrumentation profile data";
58 case instrprof_error::unknown_function:
59 return "No profile data available for function";
60 case instrprof_error::hash_mismatch:
61 return "Function control flow change detected (hash mismatch)";
62 case instrprof_error::count_mismatch:
63 return "Function basic block count change detected (counter mismatch)";
64 case instrprof_error::counter_overflow:
65 return "Counter overflow";
66 case instrprof_error::value_site_count_mismatch:
67 return "Function value site count change detected (counter mismatch)";
68 case instrprof_error::compress_failed:
69 return "Failed to compress data (zlib)";
70 case instrprof_error::uncompress_failed:
71 return "Failed to uncompress data (zlib)";
73 llvm_unreachable("A value of instrprof_error has no message.");
76 // FIXME: This class is only here to support the transition to llvm::Error. It
77 // will be removed once this transition is complete. Clients should prefer to
78 // deal with the Error value directly, rather than converting to error_code.
79 class InstrProfErrorCategoryType : public std::error_category {
80 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
81 std::string message(int IE) const override {
82 return getInstrProfErrString(static_cast<instrprof_error>(IE));
85 } // end anonymous namespace
87 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
89 const std::error_category &llvm::instrprof_category() {
90 return *ErrorCategory;
95 void SoftInstrProfErrors::addError(instrprof_error IE) {
96 if (IE == instrprof_error::success)
99 if (FirstError == instrprof_error::success)
103 case instrprof_error::hash_mismatch:
106 case instrprof_error::count_mismatch:
107 ++NumCountMismatches;
109 case instrprof_error::counter_overflow:
110 ++NumCounterOverflows;
112 case instrprof_error::value_site_count_mismatch:
113 ++NumValueSiteCountMismatches;
116 llvm_unreachable("Not a soft error");
120 std::string InstrProfError::message() const {
121 return getInstrProfErrString(Err);
124 char InstrProfError::ID = 0;
126 std::string getPGOFuncName(StringRef RawFuncName,
127 GlobalValue::LinkageTypes Linkage,
129 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
130 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
133 // Return the PGOFuncName. This function has some special handling when called
134 // in LTO optimization. The following only applies when calling in LTO passes
135 // (when \c InLTO is true): LTO's internalization privatizes many global linkage
136 // symbols. This happens after value profile annotation, but those internal
137 // linkage functions should not have a source prefix.
138 // To differentiate compiler generated internal symbols from original ones,
139 // PGOFuncName meta data are created and attached to the original internal
140 // symbols in the value profile annotation step
141 // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
142 // data, its original linkage must be non-internal.
143 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
145 StringRef FileName = (StaticFuncFullModulePrefix
146 ? F.getParent()->getName()
147 : sys::path::filename(F.getParent()->getName()));
148 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
151 // In LTO mode (when InLTO is true), first check if there is a meta data.
152 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
153 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
157 // If there is no meta data, the function must be a global before the value
158 // profile annotation pass. Its current linkage may be internal if it is
159 // internalized in LTO mode.
160 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
163 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
164 if (FileName.empty())
166 // Drop the file name including ':'. See also getPGOFuncName.
167 if (PGOFuncName.startswith(FileName))
168 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
172 // \p FuncName is the string used as profile lookup key for the function. A
173 // symbol is created to hold the name. Return the legalized symbol name.
174 std::string getPGOFuncNameVarName(StringRef FuncName,
175 GlobalValue::LinkageTypes Linkage) {
176 std::string VarName = getInstrProfNameVarPrefix();
179 if (!GlobalValue::isLocalLinkage(Linkage))
182 // Now fix up illegal chars in local VarName that may upset the assembler.
183 const char *InvalidChars = "-:<>/\"'";
184 size_t found = VarName.find_first_of(InvalidChars);
185 while (found != std::string::npos) {
186 VarName[found] = '_';
187 found = VarName.find_first_of(InvalidChars, found + 1);
192 GlobalVariable *createPGOFuncNameVar(Module &M,
193 GlobalValue::LinkageTypes Linkage,
194 StringRef PGOFuncName) {
196 // We generally want to match the function's linkage, but available_externally
197 // and extern_weak both have the wrong semantics, and anything that doesn't
198 // need to link across compilation units doesn't need to be visible at all.
199 if (Linkage == GlobalValue::ExternalWeakLinkage)
200 Linkage = GlobalValue::LinkOnceAnyLinkage;
201 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
202 Linkage = GlobalValue::LinkOnceODRLinkage;
203 else if (Linkage == GlobalValue::InternalLinkage ||
204 Linkage == GlobalValue::ExternalLinkage)
205 Linkage = GlobalValue::PrivateLinkage;
208 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
210 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
211 getPGOFuncNameVarName(PGOFuncName, Linkage));
213 // Hide the symbol so that we correctly get a copy for each executable.
214 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
215 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
220 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
221 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
224 void InstrProfSymtab::create(Module &M, bool InLTO) {
225 for (Function &F : M) {
226 // Function may not have a name: like using asm("") to overwrite the name.
227 // Ignore in this case.
230 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
231 addFuncName(PGOFuncName);
232 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
238 Error collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
239 bool doCompression, std::string &Result) {
240 assert(NameStrs.size() && "No name data to emit");
242 uint8_t Header[16], *P = Header;
243 std::string UncompressedNameStrings =
244 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
246 assert(StringRef(UncompressedNameStrings)
247 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
248 "PGO name is invalid (contains separator token)");
250 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
253 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
254 EncLen = encodeULEB128(CompressedLen, P);
256 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
257 unsigned HeaderLen = P - &Header[0];
258 Result.append(HeaderStr, HeaderLen);
260 return Error::success();
263 if (!doCompression) {
264 return WriteStringToResult(0, UncompressedNameStrings);
267 SmallString<128> CompressedNameStrings;
268 zlib::Status Success =
269 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
270 zlib::BestSizeCompression);
272 if (Success != zlib::StatusOK)
273 return make_error<InstrProfError>(instrprof_error::compress_failed);
275 return WriteStringToResult(CompressedNameStrings.size(),
276 CompressedNameStrings);
279 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
280 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
282 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
286 Error collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
287 std::string &Result, bool doCompression) {
288 std::vector<std::string> NameStrs;
289 for (auto *NameVar : NameVars) {
290 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
292 return collectPGOFuncNameStrings(
293 NameStrs, zlib::isAvailable() && doCompression, Result);
296 Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
297 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
298 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
302 uint64_t UncompressedSize = decodeULEB128(P, &N);
304 uint64_t CompressedSize = decodeULEB128(P, &N);
306 bool isCompressed = (CompressedSize != 0);
307 SmallString<128> UncompressedNameStrings;
308 StringRef NameStrings;
310 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
312 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
313 UncompressedSize) != zlib::StatusOK)
314 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
316 NameStrings = StringRef(UncompressedNameStrings.data(),
317 UncompressedNameStrings.size());
320 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
321 P += UncompressedSize;
323 // Now parse the name strings.
324 SmallVector<StringRef, 0> Names;
325 NameStrings.split(Names, getInstrProfNameSeparator());
326 for (StringRef &Name : Names)
327 Symtab.addFuncName(Name);
329 while (P < EndP && *P == 0)
332 Symtab.finalizeSymtab();
333 return Error::success();
336 void InstrProfValueSiteRecord::merge(SoftInstrProfErrors &SIPE,
337 InstrProfValueSiteRecord &Input,
339 this->sortByTargetValues();
340 Input.sortByTargetValues();
341 auto I = ValueData.begin();
342 auto IE = ValueData.end();
343 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
345 while (I != IE && I->Value < J->Value)
347 if (I != IE && I->Value == J->Value) {
349 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
351 SIPE.addError(instrprof_error::counter_overflow);
355 ValueData.insert(I, *J);
359 void InstrProfValueSiteRecord::scale(SoftInstrProfErrors &SIPE,
361 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
363 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
365 SIPE.addError(instrprof_error::counter_overflow);
369 // Merge Value Profile data from Src record to this record for ValueKind.
370 // Scale merged value counts by \p Weight.
371 void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
372 InstrProfRecord &Src,
374 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
375 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
376 if (ThisNumValueSites != OtherNumValueSites) {
377 SIPE.addError(instrprof_error::value_site_count_mismatch);
380 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
381 getValueSitesForKind(ValueKind);
382 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
383 Src.getValueSitesForKind(ValueKind);
384 for (uint32_t I = 0; I < ThisNumValueSites; I++)
385 ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
388 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
389 // If the number of counters doesn't match we either have bad data
390 // or a hash collision.
391 if (Counts.size() != Other.Counts.size()) {
392 SIPE.addError(instrprof_error::count_mismatch);
396 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
399 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
401 SIPE.addError(instrprof_error::counter_overflow);
404 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
405 mergeValueProfData(Kind, Other, Weight);
408 void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
409 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
410 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
411 getValueSitesForKind(ValueKind);
412 for (uint32_t I = 0; I < ThisNumValueSites; I++)
413 ThisSiteRecords[I].scale(SIPE, Weight);
416 void InstrProfRecord::scale(uint64_t Weight) {
417 for (auto &Count : this->Counts) {
419 Count = SaturatingMultiply(Count, Weight, &Overflowed);
421 SIPE.addError(instrprof_error::counter_overflow);
423 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
424 scaleValueProfData(Kind, Weight);
427 // Map indirect call target name hash to name string.
428 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
429 ValueMapType *ValueMap) {
433 case IPVK_IndirectCallTarget: {
435 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
436 [](const std::pair<uint64_t, uint64_t> &LHS,
437 uint64_t RHS) { return LHS.first < RHS; });
438 // Raw function pointer collected by value profiler may be from
439 // external functions that are not instrumented. They won't have
440 // mapping data to be used by the deserializer. Force the value to
441 // be 0 in this case.
442 if (Result != ValueMap->end() && Result->first == Value)
443 Value = (uint64_t)Result->second;
452 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
453 InstrProfValueData *VData, uint32_t N,
454 ValueMapType *ValueMap) {
455 for (uint32_t I = 0; I < N; I++) {
456 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
458 std::vector<InstrProfValueSiteRecord> &ValueSites =
459 getValueSitesForKind(ValueKind);
461 ValueSites.emplace_back();
463 ValueSites.emplace_back(VData, VData + N);
466 #define INSTR_PROF_COMMON_API_IMPL
467 #include "llvm/ProfileData/InstrProfData.inc"
470 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
471 * class. These C wrappers are used as adaptors so that C++ code can be
472 * invoked as callbacks.
474 uint32_t getNumValueKindsInstrProf(const void *Record) {
475 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
478 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
479 return reinterpret_cast<const InstrProfRecord *>(Record)
480 ->getNumValueSites(VKind);
483 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
484 return reinterpret_cast<const InstrProfRecord *>(Record)
485 ->getNumValueData(VKind);
488 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
490 return reinterpret_cast<const InstrProfRecord *>(R)
491 ->getNumValueDataForSite(VK, S);
494 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
495 uint32_t K, uint32_t S) {
496 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
499 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
501 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
502 memset(VD, 0, TotalSizeInBytes);
506 static ValueProfRecordClosure InstrProfRecordClosure = {
508 getNumValueKindsInstrProf,
509 getNumValueSitesInstrProf,
510 getNumValueDataInstrProf,
511 getNumValueDataForSiteInstrProf,
513 getValueForSiteInstrProf,
514 allocValueProfDataInstrProf};
516 // Wrapper implementation using the closure mechanism.
517 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
518 InstrProfRecordClosure.Record = &Record;
519 return getValueProfDataSize(&InstrProfRecordClosure);
522 // Wrapper implementation using the closure mechanism.
523 std::unique_ptr<ValueProfData>
524 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
525 InstrProfRecordClosure.Record = &Record;
527 std::unique_ptr<ValueProfData> VPD(
528 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
532 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
533 InstrProfRecord::ValueMapType *VMap) {
534 Record.reserveSites(Kind, NumValueSites);
536 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
537 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
538 uint8_t ValueDataCount = this->SiteCountArray[VSite];
539 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
540 ValueData += ValueDataCount;
544 // For writing/serializing, Old is the host endianness, and New is
545 // byte order intended on disk. For Reading/deserialization, Old
546 // is the on-disk source endianness, and New is the host endianness.
547 void ValueProfRecord::swapBytes(support::endianness Old,
548 support::endianness New) {
549 using namespace support;
553 if (getHostEndianness() != Old) {
554 sys::swapByteOrder<uint32_t>(NumValueSites);
555 sys::swapByteOrder<uint32_t>(Kind);
557 uint32_t ND = getValueProfRecordNumValueData(this);
558 InstrProfValueData *VD = getValueProfRecordValueData(this);
560 // No need to swap byte array: SiteCountArrray.
561 for (uint32_t I = 0; I < ND; I++) {
562 sys::swapByteOrder<uint64_t>(VD[I].Value);
563 sys::swapByteOrder<uint64_t>(VD[I].Count);
565 if (getHostEndianness() == Old) {
566 sys::swapByteOrder<uint32_t>(NumValueSites);
567 sys::swapByteOrder<uint32_t>(Kind);
571 void ValueProfData::deserializeTo(InstrProfRecord &Record,
572 InstrProfRecord::ValueMapType *VMap) {
573 if (NumValueKinds == 0)
576 ValueProfRecord *VR = getFirstValueProfRecord(this);
577 for (uint32_t K = 0; K < NumValueKinds; K++) {
578 VR->deserializeTo(Record, VMap);
579 VR = getValueProfRecordNext(VR);
584 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
585 using namespace support;
587 return endian::readNext<T, little, unaligned>(D);
589 return endian::readNext<T, big, unaligned>(D);
592 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
593 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
597 Error ValueProfData::checkIntegrity() {
598 if (NumValueKinds > IPVK_Last + 1)
599 return make_error<InstrProfError>(instrprof_error::malformed);
600 // Total size needs to be mulltiple of quadword size.
601 if (TotalSize % sizeof(uint64_t))
602 return make_error<InstrProfError>(instrprof_error::malformed);
604 ValueProfRecord *VR = getFirstValueProfRecord(this);
605 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
606 if (VR->Kind > IPVK_Last)
607 return make_error<InstrProfError>(instrprof_error::malformed);
608 VR = getValueProfRecordNext(VR);
609 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
610 return make_error<InstrProfError>(instrprof_error::malformed);
612 return Error::success();
615 Expected<std::unique_ptr<ValueProfData>>
616 ValueProfData::getValueProfData(const unsigned char *D,
617 const unsigned char *const BufferEnd,
618 support::endianness Endianness) {
619 using namespace support;
620 if (D + sizeof(ValueProfData) > BufferEnd)
621 return make_error<InstrProfError>(instrprof_error::truncated);
623 const unsigned char *Header = D;
624 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
625 if (D + TotalSize > BufferEnd)
626 return make_error<InstrProfError>(instrprof_error::too_large);
628 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
629 memcpy(VPD.get(), D, TotalSize);
631 VPD->swapBytesToHost(Endianness);
633 Error E = VPD->checkIntegrity();
637 return std::move(VPD);
640 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
641 using namespace support;
642 if (Endianness == getHostEndianness())
645 sys::swapByteOrder<uint32_t>(TotalSize);
646 sys::swapByteOrder<uint32_t>(NumValueKinds);
648 ValueProfRecord *VR = getFirstValueProfRecord(this);
649 for (uint32_t K = 0; K < NumValueKinds; K++) {
650 VR->swapBytes(Endianness, getHostEndianness());
651 VR = getValueProfRecordNext(VR);
655 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
656 using namespace support;
657 if (Endianness == getHostEndianness())
660 ValueProfRecord *VR = getFirstValueProfRecord(this);
661 for (uint32_t K = 0; K < NumValueKinds; K++) {
662 ValueProfRecord *NVR = getValueProfRecordNext(VR);
663 VR->swapBytes(getHostEndianness(), Endianness);
666 sys::swapByteOrder<uint32_t>(TotalSize);
667 sys::swapByteOrder<uint32_t>(NumValueKinds);
670 void annotateValueSite(Module &M, Instruction &Inst,
671 const InstrProfRecord &InstrProfR,
672 InstrProfValueKind ValueKind, uint32_t SiteIdx,
673 uint32_t MaxMDCount) {
674 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
679 std::unique_ptr<InstrProfValueData[]> VD =
680 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
682 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
683 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
686 void annotateValueSite(Module &M, Instruction &Inst,
687 ArrayRef<InstrProfValueData> VDs,
688 uint64_t Sum, InstrProfValueKind ValueKind,
689 uint32_t MaxMDCount) {
690 LLVMContext &Ctx = M.getContext();
691 MDBuilder MDHelper(Ctx);
692 SmallVector<Metadata *, 3> Vals;
694 Vals.push_back(MDHelper.createString("VP"));
696 Vals.push_back(MDHelper.createConstant(
697 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
700 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
702 // Value Profile Data
703 uint32_t MDCount = MaxMDCount;
704 for (auto &VD : VDs) {
705 Vals.push_back(MDHelper.createConstant(
706 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
707 Vals.push_back(MDHelper.createConstant(
708 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
712 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
715 bool getValueProfDataFromInst(const Instruction &Inst,
716 InstrProfValueKind ValueKind,
717 uint32_t MaxNumValueData,
718 InstrProfValueData ValueData[],
719 uint32_t &ActualNumValueData, uint64_t &TotalC) {
720 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
724 unsigned NOps = MD->getNumOperands();
729 // Operand 0 is a string tag "VP":
730 MDString *Tag = cast<MDString>(MD->getOperand(0));
734 if (!Tag->getString().equals("VP"))
738 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
741 if (KindInt->getZExtValue() != ValueKind)
745 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
748 TotalC = TotalCInt->getZExtValue();
750 ActualNumValueData = 0;
752 for (unsigned I = 3; I < NOps; I += 2) {
753 if (ActualNumValueData >= MaxNumValueData)
755 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
757 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
758 if (!Value || !Count)
760 ValueData[ActualNumValueData].Value = Value->getZExtValue();
761 ValueData[ActualNumValueData].Count = Count->getZExtValue();
762 ActualNumValueData++;
767 MDNode *getPGOFuncNameMetadata(const Function &F) {
768 return F.getMetadata(getPGOFuncNameMetadataName());
771 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
772 // Only for internal linkage functions.
773 if (PGOFuncName == F.getName())
775 // Don't create duplicated meta-data.
776 if (getPGOFuncNameMetadata(F))
778 LLVMContext &C = F.getContext();
779 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
780 F.setMetadata(getPGOFuncNameMetadataName(), N);
783 } // end namespace llvm