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/IR/Constants.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/IR/GlobalVariable.h"
19 #include "llvm/ProfileData/InstrProf.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/ManagedStatic.h"
26 class InstrProfErrorCategoryType : public std::error_category {
27 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
28 std::string message(int IE) const override {
29 instrprof_error E = static_cast<instrprof_error>(IE);
31 case instrprof_error::success:
33 case instrprof_error::eof:
35 case instrprof_error::unrecognized_format:
36 return "Unrecognized instrumentation profile encoding format";
37 case instrprof_error::bad_magic:
38 return "Invalid instrumentation profile data (bad magic)";
39 case instrprof_error::bad_header:
40 return "Invalid instrumentation profile data (file header is corrupt)";
41 case instrprof_error::unsupported_version:
42 return "Unsupported instrumentation profile format version";
43 case instrprof_error::unsupported_hash_type:
44 return "Unsupported instrumentation profile hash type";
45 case instrprof_error::too_large:
46 return "Too much profile data";
47 case instrprof_error::truncated:
48 return "Truncated profile data";
49 case instrprof_error::malformed:
50 return "Malformed instrumentation profile data";
51 case instrprof_error::unknown_function:
52 return "No profile data available for function";
53 case instrprof_error::hash_mismatch:
54 return "Function control flow change detected (hash mismatch)";
55 case instrprof_error::count_mismatch:
56 return "Function basic block count change detected (counter mismatch)";
57 case instrprof_error::counter_overflow:
58 return "Counter overflow";
59 case instrprof_error::value_site_count_mismatch:
60 return "Function value site count change detected (counter mismatch)";
62 llvm_unreachable("A value of instrprof_error has no message.");
67 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
69 const std::error_category &llvm::instrprof_category() {
70 return *ErrorCategory;
75 std::string getPGOFuncName(StringRef RawFuncName,
76 GlobalValue::LinkageTypes Linkage,
78 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
80 // Function names may be prefixed with a binary '1' to indicate
81 // that the backend should not modify the symbols due to any platform
82 // naming convention. Do not include that '1' in the PGO profile name.
83 if (RawFuncName[0] == '\1')
84 RawFuncName = RawFuncName.substr(1);
86 std::string FuncName = RawFuncName;
87 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
88 // For local symbols, prepend the main file name to distinguish them.
89 // Do not include the full path in the file name since there's no guarantee
90 // that it will stay the same, e.g., if the files are checked out from
91 // version control in different locations.
93 FuncName = FuncName.insert(0, "<unknown>:");
95 FuncName = FuncName.insert(0, FileName.str() + ":");
100 std::string getPGOFuncName(const Function &F, uint64_t Version) {
101 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
105 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
106 if (FileName.empty())
108 // Drop the file name including ':'. See also getPGOFuncName.
109 if (PGOFuncName.startswith(FileName))
110 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
114 // \p FuncName is the string used as profile lookup key for the function. A
115 // symbol is created to hold the name. Return the legalized symbol name.
116 static std::string getPGOFuncNameVarName(StringRef FuncName,
117 GlobalValue::LinkageTypes Linkage) {
118 std::string VarName = getInstrProfNameVarPrefix();
121 if (!GlobalValue::isLocalLinkage(Linkage))
124 // Now fix up illegal chars in local VarName that may upset the assembler.
125 const char *InvalidChars = "-:<>\"'";
126 size_t found = VarName.find_first_of(InvalidChars);
127 while (found != std::string::npos) {
128 VarName[found] = '_';
129 found = VarName.find_first_of(InvalidChars, found + 1);
134 GlobalVariable *createPGOFuncNameVar(Module &M,
135 GlobalValue::LinkageTypes Linkage,
136 StringRef FuncName) {
138 // We generally want to match the function's linkage, but available_externally
139 // and extern_weak both have the wrong semantics, and anything that doesn't
140 // need to link across compilation units doesn't need to be visible at all.
141 if (Linkage == GlobalValue::ExternalWeakLinkage)
142 Linkage = GlobalValue::LinkOnceAnyLinkage;
143 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
144 Linkage = GlobalValue::LinkOnceODRLinkage;
145 else if (Linkage == GlobalValue::InternalLinkage ||
146 Linkage == GlobalValue::ExternalLinkage)
147 Linkage = GlobalValue::PrivateLinkage;
149 auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
151 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
152 getPGOFuncNameVarName(FuncName, Linkage));
154 // Hide the symbol so that we correctly get a copy for each executable.
155 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
156 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
161 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
162 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
166 InstrProfValueSiteRecord::mergeValueData(InstrProfValueSiteRecord &Input,
168 this->sortByTargetValues();
169 Input.sortByTargetValues();
170 auto I = ValueData.begin();
171 auto IE = ValueData.end();
172 instrprof_error Result = instrprof_error::success;
173 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
175 while (I != IE && I->Value < J->Value)
177 if (I != IE && I->Value == J->Value) {
178 uint64_t JCount = J->Count;
181 JCount = SaturatingMultiply(JCount, Weight, &Overflowed);
183 Result = instrprof_error::counter_overflow;
185 I->Count = SaturatingAdd(I->Count, JCount, &Overflowed);
187 Result = instrprof_error::counter_overflow;
191 ValueData.insert(I, *J);
196 // Merge Value Profile data from Src record to this record for ValueKind.
197 // Scale merged value counts by \p Weight.
198 instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
199 InstrProfRecord &Src,
201 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
202 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
203 if (ThisNumValueSites != OtherNumValueSites)
204 return instrprof_error::value_site_count_mismatch;
205 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
206 getValueSitesForKind(ValueKind);
207 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
208 Src.getValueSitesForKind(ValueKind);
209 instrprof_error Result = instrprof_error::success;
210 for (uint32_t I = 0; I < ThisNumValueSites; I++)
212 ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I], Weight));
216 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
218 // If the number of counters doesn't match we either have bad data
219 // or a hash collision.
220 if (Counts.size() != Other.Counts.size())
221 return instrprof_error::count_mismatch;
223 instrprof_error Result = instrprof_error::success;
225 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
227 uint64_t OtherCount = Other.Counts[I];
229 OtherCount = SaturatingMultiply(OtherCount, Weight, &Overflowed);
231 Result = instrprof_error::counter_overflow;
233 Counts[I] = SaturatingAdd(Counts[I], OtherCount, &Overflowed);
235 Result = instrprof_error::counter_overflow;
238 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
239 MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
243 // Map indirect call target name hash to name string.
244 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
245 ValueMapType *HashKeys) {
249 case IPVK_IndirectCallTarget: {
251 std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
252 [](const std::pair<uint64_t, const char *> &LHS,
253 uint64_t RHS) { return LHS.first < RHS; });
254 if (Result != HashKeys->end())
255 Value = (uint64_t)Result->second;
262 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
266 Name = StrTab->insertString(Name);
267 for (auto &VSite : IndirectCallSites)
268 for (auto &VData : VSite.ValueData)
269 VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
272 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
273 InstrProfValueData *VData, uint32_t N,
274 ValueMapType *HashKeys) {
275 for (uint32_t I = 0; I < N; I++) {
276 VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
278 std::vector<InstrProfValueSiteRecord> &ValueSites =
279 getValueSitesForKind(ValueKind);
281 ValueSites.push_back(InstrProfValueSiteRecord());
283 ValueSites.emplace_back(VData, VData + N);
286 #define INSTR_PROF_COMMON_API_IMPL
287 #include "llvm/ProfileData/InstrProfData.inc"
290 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
291 * class. These C wrappers are used as adaptors so that C++ code can be
292 * invoked as callbacks.
294 uint32_t getNumValueKindsInstrProf(const void *Record) {
295 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
298 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
299 return reinterpret_cast<const InstrProfRecord *>(Record)
300 ->getNumValueSites(VKind);
303 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
304 return reinterpret_cast<const InstrProfRecord *>(Record)
305 ->getNumValueData(VKind);
308 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
310 return reinterpret_cast<const InstrProfRecord *>(R)
311 ->getNumValueDataForSite(VK, S);
314 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
315 uint32_t K, uint32_t S,
316 uint64_t (*Mapper)(uint32_t, uint64_t)) {
317 return reinterpret_cast<const InstrProfRecord *>(R)
318 ->getValueForSite(Dst, K, S, Mapper);
321 uint64_t stringToHash(uint32_t ValueKind, uint64_t Value) {
323 case IPVK_IndirectCallTarget:
324 return IndexedInstrProf::ComputeHash((const char *)Value);
327 llvm_unreachable("value kind not handled !");
332 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
334 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
335 memset(VD, 0, TotalSizeInBytes);
339 static ValueProfRecordClosure InstrProfRecordClosure = {
341 getNumValueKindsInstrProf,
342 getNumValueSitesInstrProf,
343 getNumValueDataInstrProf,
344 getNumValueDataForSiteInstrProf,
346 getValueForSiteInstrProf,
347 allocValueProfDataInstrProf};
349 // Wrapper implementation using the closure mechanism.
350 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
351 InstrProfRecordClosure.Record = &Record;
352 return getValueProfDataSize(&InstrProfRecordClosure);
355 // Wrapper implementation using the closure mechanism.
356 std::unique_ptr<ValueProfData>
357 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
358 InstrProfRecordClosure.Record = &Record;
360 std::unique_ptr<ValueProfData> VPD(
361 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
365 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
366 InstrProfRecord::ValueMapType *VMap) {
367 Record.reserveSites(Kind, NumValueSites);
369 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
370 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
371 uint8_t ValueDataCount = this->SiteCountArray[VSite];
372 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
373 ValueData += ValueDataCount;
377 // For writing/serializing, Old is the host endianness, and New is
378 // byte order intended on disk. For Reading/deserialization, Old
379 // is the on-disk source endianness, and New is the host endianness.
380 void ValueProfRecord::swapBytes(support::endianness Old,
381 support::endianness New) {
382 using namespace support;
386 if (getHostEndianness() != Old) {
387 sys::swapByteOrder<uint32_t>(NumValueSites);
388 sys::swapByteOrder<uint32_t>(Kind);
390 uint32_t ND = getValueProfRecordNumValueData(this);
391 InstrProfValueData *VD = getValueProfRecordValueData(this);
393 // No need to swap byte array: SiteCountArrray.
394 for (uint32_t I = 0; I < ND; I++) {
395 sys::swapByteOrder<uint64_t>(VD[I].Value);
396 sys::swapByteOrder<uint64_t>(VD[I].Count);
398 if (getHostEndianness() == Old) {
399 sys::swapByteOrder<uint32_t>(NumValueSites);
400 sys::swapByteOrder<uint32_t>(Kind);
404 void ValueProfData::deserializeTo(InstrProfRecord &Record,
405 InstrProfRecord::ValueMapType *VMap) {
406 if (NumValueKinds == 0)
409 ValueProfRecord *VR = getFirstValueProfRecord(this);
410 for (uint32_t K = 0; K < NumValueKinds; K++) {
411 VR->deserializeTo(Record, VMap);
412 VR = getValueProfRecordNext(VR);
417 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
418 using namespace support;
420 return endian::readNext<T, little, unaligned>(D);
422 return endian::readNext<T, big, unaligned>(D);
425 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
426 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
430 instrprof_error ValueProfData::checkIntegrity() {
431 if (NumValueKinds > IPVK_Last + 1)
432 return instrprof_error::malformed;
433 // Total size needs to be mulltiple of quadword size.
434 if (TotalSize % sizeof(uint64_t))
435 return instrprof_error::malformed;
437 ValueProfRecord *VR = getFirstValueProfRecord(this);
438 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
439 if (VR->Kind > IPVK_Last)
440 return instrprof_error::malformed;
441 VR = getValueProfRecordNext(VR);
442 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
443 return instrprof_error::malformed;
445 return instrprof_error::success;
448 ErrorOr<std::unique_ptr<ValueProfData>>
449 ValueProfData::getValueProfData(const unsigned char *D,
450 const unsigned char *const BufferEnd,
451 support::endianness Endianness) {
452 using namespace support;
453 if (D + sizeof(ValueProfData) > BufferEnd)
454 return instrprof_error::truncated;
456 const unsigned char *Header = D;
457 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
458 if (D + TotalSize > BufferEnd)
459 return instrprof_error::too_large;
461 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
462 memcpy(VPD.get(), D, TotalSize);
464 VPD->swapBytesToHost(Endianness);
466 instrprof_error EC = VPD->checkIntegrity();
467 if (EC != instrprof_error::success)
470 return std::move(VPD);
473 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
474 using namespace support;
475 if (Endianness == getHostEndianness())
478 sys::swapByteOrder<uint32_t>(TotalSize);
479 sys::swapByteOrder<uint32_t>(NumValueKinds);
481 ValueProfRecord *VR = getFirstValueProfRecord(this);
482 for (uint32_t K = 0; K < NumValueKinds; K++) {
483 VR->swapBytes(Endianness, getHostEndianness());
484 VR = getValueProfRecordNext(VR);
488 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
489 using namespace support;
490 if (Endianness == getHostEndianness())
493 ValueProfRecord *VR = getFirstValueProfRecord(this);
494 for (uint32_t K = 0; K < NumValueKinds; K++) {
495 ValueProfRecord *NVR = getValueProfRecordNext(VR);
496 VR->swapBytes(getHostEndianness(), Endianness);
499 sys::swapByteOrder<uint32_t>(TotalSize);
500 sys::swapByteOrder<uint32_t>(NumValueKinds);