blob: 723408b1c2ad4f89fa25026aa4d408d72a2f5beb [file] [log] [blame]
Justin Bognerf8d79192014-03-21 17:24:48 +00001//=-- InstrProf.cpp - Instrumented profiling format support -----------------=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for clang's instrumentation based PGO and
11// coverage.
12//
13//===----------------------------------------------------------------------===//
14
Xinliang David Li441959d2015-11-09 00:01:22 +000015#include "llvm/IR/Constants.h"
16#include "llvm/IR/Function.h"
17#include "llvm/IR/Module.h"
18#include "llvm/IR/GlobalVariable.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000019#include "llvm/ProfileData/InstrProf.h"
20#include "llvm/Support/ErrorHandling.h"
Chris Bieneman1efe8012014-09-19 23:19:24 +000021#include "llvm/Support/ManagedStatic.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000022
23using namespace llvm;
24
25namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +000026class InstrProfErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +000027 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
Justin Bognerf8d79192014-03-21 17:24:48 +000028 std::string message(int IE) const override {
Rafael Espindola92512e82014-06-03 05:12:33 +000029 instrprof_error E = static_cast<instrprof_error>(IE);
Justin Bognerf8d79192014-03-21 17:24:48 +000030 switch (E) {
31 case instrprof_error::success:
32 return "Success";
33 case instrprof_error::eof:
34 return "End of File";
Nathan Slingerland4f823662015-11-13 03:47:58 +000035 case instrprof_error::unrecognized_format:
36 return "Unrecognized instrumentation profile encoding format";
Justin Bognerf8d79192014-03-21 17:24:48 +000037 case instrprof_error::bad_magic:
Nathan Slingerland4f823662015-11-13 03:47:58 +000038 return "Invalid instrumentation profile data (bad magic)";
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +000039 case instrprof_error::bad_header:
Nathan Slingerland4f823662015-11-13 03:47:58 +000040 return "Invalid instrumentation profile data (file header is corrupt)";
Justin Bognerf8d79192014-03-21 17:24:48 +000041 case instrprof_error::unsupported_version:
Nathan Slingerland4f823662015-11-13 03:47:58 +000042 return "Unsupported instrumentation profile format version";
Justin Bognerb7aa2632014-04-18 21:48:40 +000043 case instrprof_error::unsupported_hash_type:
Nathan Slingerland4f823662015-11-13 03:47:58 +000044 return "Unsupported instrumentation profile hash type";
Justin Bognerf8d79192014-03-21 17:24:48 +000045 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:
Nathan Slingerland4f823662015-11-13 03:47:58 +000050 return "Malformed instrumentation profile data";
Justin Bognerf8d79192014-03-21 17:24:48 +000051 case instrprof_error::unknown_function:
52 return "No profile data available for function";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000053 case instrprof_error::hash_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000054 return "Function control flow change detected (hash mismatch)";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000055 case instrprof_error::count_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000056 return "Function basic block count change detected (counter mismatch)";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000057 case instrprof_error::counter_overflow:
58 return "Counter overflow";
Justin Bogner9e9a0572015-09-29 22:13:58 +000059 case instrprof_error::value_site_count_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000060 return "Function value site count change detected (counter mismatch)";
Justin Bognerf8d79192014-03-21 17:24:48 +000061 }
62 llvm_unreachable("A value of instrprof_error has no message.");
63 }
Justin Bognerf8d79192014-03-21 17:24:48 +000064};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000065}
Justin Bognerf8d79192014-03-21 17:24:48 +000066
Chris Bieneman1efe8012014-09-19 23:19:24 +000067static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
68
Rafael Espindola25188c92014-06-12 01:45:43 +000069const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +000070 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +000071}
Xinliang David Li441959d2015-11-09 00:01:22 +000072
73namespace llvm {
74
75std::string getPGOFuncName(StringRef RawFuncName,
76 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +000077 StringRef FileName,
78 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Xinliang David Li441959d2015-11-09 00:01:22 +000079
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);
85
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.
92 if (FileName.empty())
Xinliang David Lia86545b2015-12-11 20:23:22 +000093 FuncName = FuncName.insert(0, "<unknown>:");
Xinliang David Li441959d2015-11-09 00:01:22 +000094 else
Xinliang David Lia86545b2015-12-11 20:23:22 +000095 FuncName = FuncName.insert(0, FileName.str() + ":");
Xinliang David Li441959d2015-11-09 00:01:22 +000096 }
97 return FuncName;
98}
99
Xinliang David Li307902e2015-12-05 05:16:36 +0000100std::string getPGOFuncName(const Function &F, uint64_t Version) {
101 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
102 Version);
Xinliang David Li441959d2015-11-09 00:01:22 +0000103}
104
Xinliang David Li4ec40142015-12-15 19:44:45 +0000105StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
106 if (FileName.empty())
107 return PGOFuncName;
108 // Drop the file name including ':'. See also getPGOFuncName.
109 if (PGOFuncName.startswith(FileName))
110 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
111 return PGOFuncName;
112}
113
Xinliang David Lid1bab962015-12-12 17:28:03 +0000114// \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.
116static std::string getPGOFuncNameVarName(StringRef FuncName,
117 GlobalValue::LinkageTypes Linkage) {
118 std::string VarName = getInstrProfNameVarPrefix();
119 VarName += FuncName;
120
121 if (!GlobalValue::isLocalLinkage(Linkage))
122 return VarName;
123
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);
130 }
131 return VarName;
132}
133
Xinliang David Li441959d2015-11-09 00:01:22 +0000134GlobalVariable *createPGOFuncNameVar(Module &M,
135 GlobalValue::LinkageTypes Linkage,
136 StringRef FuncName) {
137
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;
148
149 auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
150 auto FuncNameVar =
151 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Lid1bab962015-12-12 17:28:03 +0000152 getPGOFuncNameVarName(FuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000153
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);
157
158 return FuncNameVar;
159}
160
161GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
162 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
163}
Xinliang David Liee415892015-11-10 00:24:45 +0000164
Xinliang David Lib75544a2015-11-28 19:07:09 +0000165#define INSTR_PROF_COMMON_API_IMPL
166#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000167
Xinliang David Liee415892015-11-10 00:24:45 +0000168
Xinliang David Lib75544a2015-11-28 19:07:09 +0000169/*!
170 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000171 * class. These C wrappers are used as adaptors so that C++ code can be
172 * invoked as callbacks.
173 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000174uint32_t getNumValueKindsInstrProf(const void *Record) {
175 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
176}
177
178uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
179 return reinterpret_cast<const InstrProfRecord *>(Record)
180 ->getNumValueSites(VKind);
181}
182
183uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
184 return reinterpret_cast<const InstrProfRecord *>(Record)
185 ->getNumValueData(VKind);
186}
187
188uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
189 uint32_t S) {
190 return reinterpret_cast<const InstrProfRecord *>(R)
191 ->getNumValueDataForSite(VK, S);
192}
193
194void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
195 uint32_t K, uint32_t S,
196 uint64_t (*Mapper)(uint32_t, uint64_t)) {
197 return reinterpret_cast<const InstrProfRecord *>(R)
198 ->getValueForSite(Dst, K, S, Mapper);
199}
200
Xinliang David Lie8092312015-11-25 19:13:00 +0000201uint64_t stringToHash(uint32_t ValueKind, uint64_t Value) {
202 switch (ValueKind) {
203 case IPVK_IndirectCallTarget:
204 return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType,
205 (const char *)Value);
206 break;
207 default:
208 llvm_unreachable("value kind not handled !");
209 }
210 return Value;
211}
212
Xinliang David Lif47cf552015-11-25 06:23:38 +0000213ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
214 return (ValueProfData *)(new (::operator new(TotalSizeInBytes))
215 ValueProfData());
216}
217
218static ValueProfRecordClosure InstrProfRecordClosure = {
219 0,
220 getNumValueKindsInstrProf,
221 getNumValueSitesInstrProf,
222 getNumValueDataInstrProf,
223 getNumValueDataForSiteInstrProf,
224 stringToHash,
225 getValueForSiteInstrProf,
Xinliang David Lie8092312015-11-25 19:13:00 +0000226 allocValueProfDataInstrProf
227};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000228
Xinliang David Lie8092312015-11-25 19:13:00 +0000229// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000230uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
231 InstrProfRecordClosure.Record = &Record;
232 return getValueProfDataSize(&InstrProfRecordClosure);
233}
234
Xinliang David Lie8092312015-11-25 19:13:00 +0000235// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000236std::unique_ptr<ValueProfData>
237ValueProfData::serializeFrom(const InstrProfRecord &Record) {
238 InstrProfRecordClosure.Record = &Record;
239
240 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000241 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000242 return VPD;
243}
244
Xinliang David Lie8092312015-11-25 19:13:00 +0000245void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
246 InstrProfRecord::ValueMapType *VMap) {
247 Record.reserveSites(Kind, NumValueSites);
248
249 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
250 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
251 uint8_t ValueDataCount = this->SiteCountArray[VSite];
252 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
253 ValueData += ValueDataCount;
254 }
255}
Xinliang David Lied966772015-11-25 23:31:18 +0000256
Xinliang David Lie8092312015-11-25 19:13:00 +0000257// For writing/serializing, Old is the host endianness, and New is
258// byte order intended on disk. For Reading/deserialization, Old
259// is the on-disk source endianness, and New is the host endianness.
260void ValueProfRecord::swapBytes(support::endianness Old,
261 support::endianness New) {
262 using namespace support;
263 if (Old == New)
264 return;
265
266 if (getHostEndianness() != Old) {
267 sys::swapByteOrder<uint32_t>(NumValueSites);
268 sys::swapByteOrder<uint32_t>(Kind);
269 }
270 uint32_t ND = getValueProfRecordNumValueData(this);
271 InstrProfValueData *VD = getValueProfRecordValueData(this);
272
273 // No need to swap byte array: SiteCountArrray.
274 for (uint32_t I = 0; I < ND; I++) {
275 sys::swapByteOrder<uint64_t>(VD[I].Value);
276 sys::swapByteOrder<uint64_t>(VD[I].Count);
277 }
278 if (getHostEndianness() == Old) {
279 sys::swapByteOrder<uint32_t>(NumValueSites);
280 sys::swapByteOrder<uint32_t>(Kind);
281 }
282}
283
284void ValueProfData::deserializeTo(InstrProfRecord &Record,
285 InstrProfRecord::ValueMapType *VMap) {
286 if (NumValueKinds == 0)
287 return;
288
289 ValueProfRecord *VR = getFirstValueProfRecord(this);
290 for (uint32_t K = 0; K < NumValueKinds; K++) {
291 VR->deserializeTo(Record, VMap);
292 VR = getValueProfRecordNext(VR);
293 }
294}
295
296template <class T>
297static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
298 using namespace support;
299 if (Orig == little)
300 return endian::readNext<T, little, unaligned>(D);
301 else
302 return endian::readNext<T, big, unaligned>(D);
303}
304
305static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
306 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
307 ValueProfData());
308}
309
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000310instrprof_error ValueProfData::checkIntegrity() {
311 if (NumValueKinds > IPVK_Last + 1)
312 return instrprof_error::malformed;
313 // Total size needs to be mulltiple of quadword size.
314 if (TotalSize % sizeof(uint64_t))
315 return instrprof_error::malformed;
316
317 ValueProfRecord *VR = getFirstValueProfRecord(this);
318 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
319 if (VR->Kind > IPVK_Last)
320 return instrprof_error::malformed;
321 VR = getValueProfRecordNext(VR);
322 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
323 return instrprof_error::malformed;
324 }
325 return instrprof_error::success;
326}
327
Xinliang David Liee415892015-11-10 00:24:45 +0000328ErrorOr<std::unique_ptr<ValueProfData>>
329ValueProfData::getValueProfData(const unsigned char *D,
330 const unsigned char *const BufferEnd,
331 support::endianness Endianness) {
332 using namespace support;
333 if (D + sizeof(ValueProfData) > BufferEnd)
334 return instrprof_error::truncated;
335
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000336 const unsigned char *Header = D;
337 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000338 if (D + TotalSize > BufferEnd)
339 return instrprof_error::too_large;
Xinliang David Liee415892015-11-10 00:24:45 +0000340
Xinliang David Lif47cf552015-11-25 06:23:38 +0000341 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000342 memcpy(VPD.get(), D, TotalSize);
343 // Byte swap.
344 VPD->swapBytesToHost(Endianness);
345
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000346 instrprof_error EC = VPD->checkIntegrity();
347 if (EC != instrprof_error::success)
348 return EC;
Xinliang David Liee415892015-11-10 00:24:45 +0000349
Xinliang David Liee415892015-11-10 00:24:45 +0000350 return std::move(VPD);
351}
352
353void ValueProfData::swapBytesToHost(support::endianness Endianness) {
354 using namespace support;
355 if (Endianness == getHostEndianness())
356 return;
357
358 sys::swapByteOrder<uint32_t>(TotalSize);
359 sys::swapByteOrder<uint32_t>(NumValueKinds);
360
Xinliang David Lif47cf552015-11-25 06:23:38 +0000361 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000362 for (uint32_t K = 0; K < NumValueKinds; K++) {
363 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000364 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000365 }
366}
367
368void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
369 using namespace support;
370 if (Endianness == getHostEndianness())
371 return;
372
Xinliang David Lif47cf552015-11-25 06:23:38 +0000373 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000374 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000375 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000376 VR->swapBytes(getHostEndianness(), Endianness);
377 VR = NVR;
378 }
379 sys::swapByteOrder<uint32_t>(TotalSize);
380 sys::swapByteOrder<uint32_t>(NumValueKinds);
381}
Xinliang David Lie8092312015-11-25 19:13:00 +0000382
Xinliang David Liee415892015-11-10 00:24:45 +0000383}