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 // \p FuncName is the string used as profile lookup key for the function. A
106 // symbol is created to hold the name. Return the legalized symbol name.
107 static std::string getPGOFuncNameVarName(StringRef FuncName,
108 GlobalValue::LinkageTypes Linkage) {
109 std::string VarName = getInstrProfNameVarPrefix();
112 if (!GlobalValue::isLocalLinkage(Linkage))
115 // Now fix up illegal chars in local VarName that may upset the assembler.
116 const char *InvalidChars = "-:<>\"'";
117 size_t found = VarName.find_first_of(InvalidChars);
118 while (found != std::string::npos) {
119 VarName[found] = '_';
120 found = VarName.find_first_of(InvalidChars, found + 1);
125 GlobalVariable *createPGOFuncNameVar(Module &M,
126 GlobalValue::LinkageTypes Linkage,
127 StringRef FuncName) {
129 // We generally want to match the function's linkage, but available_externally
130 // and extern_weak both have the wrong semantics, and anything that doesn't
131 // need to link across compilation units doesn't need to be visible at all.
132 if (Linkage == GlobalValue::ExternalWeakLinkage)
133 Linkage = GlobalValue::LinkOnceAnyLinkage;
134 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
135 Linkage = GlobalValue::LinkOnceODRLinkage;
136 else if (Linkage == GlobalValue::InternalLinkage ||
137 Linkage == GlobalValue::ExternalLinkage)
138 Linkage = GlobalValue::PrivateLinkage;
140 auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
142 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
143 getPGOFuncNameVarName(FuncName, Linkage));
145 // Hide the symbol so that we correctly get a copy for each executable.
146 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
147 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
152 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
153 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
156 #define INSTR_PROF_COMMON_API_IMPL
157 #include "llvm/ProfileData/InstrProfData.inc"
161 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
162 * class. These C wrappers are used as adaptors so that C++ code can be
163 * invoked as callbacks.
165 uint32_t getNumValueKindsInstrProf(const void *Record) {
166 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
169 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
170 return reinterpret_cast<const InstrProfRecord *>(Record)
171 ->getNumValueSites(VKind);
174 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
175 return reinterpret_cast<const InstrProfRecord *>(Record)
176 ->getNumValueData(VKind);
179 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
181 return reinterpret_cast<const InstrProfRecord *>(R)
182 ->getNumValueDataForSite(VK, S);
185 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
186 uint32_t K, uint32_t S,
187 uint64_t (*Mapper)(uint32_t, uint64_t)) {
188 return reinterpret_cast<const InstrProfRecord *>(R)
189 ->getValueForSite(Dst, K, S, Mapper);
192 uint64_t stringToHash(uint32_t ValueKind, uint64_t Value) {
194 case IPVK_IndirectCallTarget:
195 return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType,
196 (const char *)Value);
199 llvm_unreachable("value kind not handled !");
204 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
205 return (ValueProfData *)(new (::operator new(TotalSizeInBytes))
209 static ValueProfRecordClosure InstrProfRecordClosure = {
211 getNumValueKindsInstrProf,
212 getNumValueSitesInstrProf,
213 getNumValueDataInstrProf,
214 getNumValueDataForSiteInstrProf,
216 getValueForSiteInstrProf,
217 allocValueProfDataInstrProf
220 // Wrapper implementation using the closure mechanism.
221 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
222 InstrProfRecordClosure.Record = &Record;
223 return getValueProfDataSize(&InstrProfRecordClosure);
226 // Wrapper implementation using the closure mechanism.
227 std::unique_ptr<ValueProfData>
228 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
229 InstrProfRecordClosure.Record = &Record;
231 std::unique_ptr<ValueProfData> VPD(
232 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
236 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
237 InstrProfRecord::ValueMapType *VMap) {
238 Record.reserveSites(Kind, NumValueSites);
240 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
241 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
242 uint8_t ValueDataCount = this->SiteCountArray[VSite];
243 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
244 ValueData += ValueDataCount;
248 // For writing/serializing, Old is the host endianness, and New is
249 // byte order intended on disk. For Reading/deserialization, Old
250 // is the on-disk source endianness, and New is the host endianness.
251 void ValueProfRecord::swapBytes(support::endianness Old,
252 support::endianness New) {
253 using namespace support;
257 if (getHostEndianness() != Old) {
258 sys::swapByteOrder<uint32_t>(NumValueSites);
259 sys::swapByteOrder<uint32_t>(Kind);
261 uint32_t ND = getValueProfRecordNumValueData(this);
262 InstrProfValueData *VD = getValueProfRecordValueData(this);
264 // No need to swap byte array: SiteCountArrray.
265 for (uint32_t I = 0; I < ND; I++) {
266 sys::swapByteOrder<uint64_t>(VD[I].Value);
267 sys::swapByteOrder<uint64_t>(VD[I].Count);
269 if (getHostEndianness() == Old) {
270 sys::swapByteOrder<uint32_t>(NumValueSites);
271 sys::swapByteOrder<uint32_t>(Kind);
275 void ValueProfData::deserializeTo(InstrProfRecord &Record,
276 InstrProfRecord::ValueMapType *VMap) {
277 if (NumValueKinds == 0)
280 ValueProfRecord *VR = getFirstValueProfRecord(this);
281 for (uint32_t K = 0; K < NumValueKinds; K++) {
282 VR->deserializeTo(Record, VMap);
283 VR = getValueProfRecordNext(VR);
288 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
289 using namespace support;
291 return endian::readNext<T, little, unaligned>(D);
293 return endian::readNext<T, big, unaligned>(D);
296 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
297 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
301 instrprof_error ValueProfData::checkIntegrity() {
302 if (NumValueKinds > IPVK_Last + 1)
303 return instrprof_error::malformed;
304 // Total size needs to be mulltiple of quadword size.
305 if (TotalSize % sizeof(uint64_t))
306 return instrprof_error::malformed;
308 ValueProfRecord *VR = getFirstValueProfRecord(this);
309 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
310 if (VR->Kind > IPVK_Last)
311 return instrprof_error::malformed;
312 VR = getValueProfRecordNext(VR);
313 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
314 return instrprof_error::malformed;
316 return instrprof_error::success;
319 ErrorOr<std::unique_ptr<ValueProfData>>
320 ValueProfData::getValueProfData(const unsigned char *D,
321 const unsigned char *const BufferEnd,
322 support::endianness Endianness) {
323 using namespace support;
324 if (D + sizeof(ValueProfData) > BufferEnd)
325 return instrprof_error::truncated;
327 const unsigned char *Header = D;
328 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
329 if (D + TotalSize > BufferEnd)
330 return instrprof_error::too_large;
332 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
333 memcpy(VPD.get(), D, TotalSize);
335 VPD->swapBytesToHost(Endianness);
337 instrprof_error EC = VPD->checkIntegrity();
338 if (EC != instrprof_error::success)
341 return std::move(VPD);
344 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
345 using namespace support;
346 if (Endianness == getHostEndianness())
349 sys::swapByteOrder<uint32_t>(TotalSize);
350 sys::swapByteOrder<uint32_t>(NumValueKinds);
352 ValueProfRecord *VR = getFirstValueProfRecord(this);
353 for (uint32_t K = 0; K < NumValueKinds; K++) {
354 VR->swapBytes(Endianness, getHostEndianness());
355 VR = getValueProfRecordNext(VR);
359 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
360 using namespace support;
361 if (Endianness == getHostEndianness())
364 ValueProfRecord *VR = getFirstValueProfRecord(this);
365 for (uint32_t K = 0; K < NumValueKinds; K++) {
366 ValueProfRecord *NVR = getValueProfRecordNext(VR);
367 VR->swapBytes(getHostEndianness(), Endianness);
370 sys::swapByteOrder<uint32_t>(TotalSize);
371 sys::swapByteOrder<uint32_t>(NumValueKinds);