blob: 1cfc21e493adda9ee0167d23b8bcf51fd4452691 [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 Lie413f1a2015-12-31 07:57:16 +000015#include "llvm/ProfileData/InstrProf.h"
Xinliang David Li0c677872016-01-04 21:31:09 +000016#include "llvm/ADT/StringExtras.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000017#include "llvm/IR/Constants.h"
18#include "llvm/IR/Function.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000019#include "llvm/IR/GlobalVariable.h"
Xinliang David Li402477d2016-02-04 19:11:43 +000020#include "llvm/IR/MDBuilder.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000021#include "llvm/IR/Module.h"
22#include "llvm/Support/Compression.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000023#include "llvm/Support/ErrorHandling.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000024#include "llvm/Support/LEB128.h"
Chris Bieneman1efe8012014-09-19 23:19:24 +000025#include "llvm/Support/ManagedStatic.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000026
27using namespace llvm;
28
29namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +000030class InstrProfErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +000031 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
Justin Bognerf8d79192014-03-21 17:24:48 +000032 std::string message(int IE) const override {
Rafael Espindola92512e82014-06-03 05:12:33 +000033 instrprof_error E = static_cast<instrprof_error>(IE);
Justin Bognerf8d79192014-03-21 17:24:48 +000034 switch (E) {
35 case instrprof_error::success:
36 return "Success";
37 case instrprof_error::eof:
38 return "End of File";
Nathan Slingerland4f823662015-11-13 03:47:58 +000039 case instrprof_error::unrecognized_format:
40 return "Unrecognized instrumentation profile encoding format";
Justin Bognerf8d79192014-03-21 17:24:48 +000041 case instrprof_error::bad_magic:
Nathan Slingerland4f823662015-11-13 03:47:58 +000042 return "Invalid instrumentation profile data (bad magic)";
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +000043 case instrprof_error::bad_header:
Nathan Slingerland4f823662015-11-13 03:47:58 +000044 return "Invalid instrumentation profile data (file header is corrupt)";
Justin Bognerf8d79192014-03-21 17:24:48 +000045 case instrprof_error::unsupported_version:
Nathan Slingerland4f823662015-11-13 03:47:58 +000046 return "Unsupported instrumentation profile format version";
Justin Bognerb7aa2632014-04-18 21:48:40 +000047 case instrprof_error::unsupported_hash_type:
Nathan Slingerland4f823662015-11-13 03:47:58 +000048 return "Unsupported instrumentation profile hash type";
Justin Bognerf8d79192014-03-21 17:24:48 +000049 case instrprof_error::too_large:
50 return "Too much profile data";
51 case instrprof_error::truncated:
52 return "Truncated profile data";
53 case instrprof_error::malformed:
Nathan Slingerland4f823662015-11-13 03:47:58 +000054 return "Malformed instrumentation profile data";
Justin Bognerf8d79192014-03-21 17:24:48 +000055 case instrprof_error::unknown_function:
56 return "No profile data available for function";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000057 case instrprof_error::hash_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000058 return "Function control flow change detected (hash mismatch)";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000059 case instrprof_error::count_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000060 return "Function basic block count change detected (counter mismatch)";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000061 case instrprof_error::counter_overflow:
62 return "Counter overflow";
Justin Bogner9e9a0572015-09-29 22:13:58 +000063 case instrprof_error::value_site_count_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000064 return "Function value site count change detected (counter mismatch)";
Justin Bognerf8d79192014-03-21 17:24:48 +000065 }
66 llvm_unreachable("A value of instrprof_error has no message.");
67 }
Justin Bognerf8d79192014-03-21 17:24:48 +000068};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000069} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +000070
Chris Bieneman1efe8012014-09-19 23:19:24 +000071static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
72
Rafael Espindola25188c92014-06-12 01:45:43 +000073const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +000074 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +000075}
Xinliang David Li441959d2015-11-09 00:01:22 +000076
77namespace llvm {
78
79std::string getPGOFuncName(StringRef RawFuncName,
80 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +000081 StringRef FileName,
82 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Xinliang David Li441959d2015-11-09 00:01:22 +000083
84 // Function names may be prefixed with a binary '1' to indicate
85 // that the backend should not modify the symbols due to any platform
86 // naming convention. Do not include that '1' in the PGO profile name.
87 if (RawFuncName[0] == '\1')
88 RawFuncName = RawFuncName.substr(1);
89
90 std::string FuncName = RawFuncName;
91 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
92 // For local symbols, prepend the main file name to distinguish them.
93 // Do not include the full path in the file name since there's no guarantee
94 // that it will stay the same, e.g., if the files are checked out from
95 // version control in different locations.
96 if (FileName.empty())
Xinliang David Lia86545b2015-12-11 20:23:22 +000097 FuncName = FuncName.insert(0, "<unknown>:");
Xinliang David Li441959d2015-11-09 00:01:22 +000098 else
Xinliang David Lia86545b2015-12-11 20:23:22 +000099 FuncName = FuncName.insert(0, FileName.str() + ":");
Xinliang David Li441959d2015-11-09 00:01:22 +0000100 }
101 return FuncName;
102}
103
Xinliang David Li307902e2015-12-05 05:16:36 +0000104std::string getPGOFuncName(const Function &F, uint64_t Version) {
105 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
106 Version);
Xinliang David Li441959d2015-11-09 00:01:22 +0000107}
108
Xinliang David Li4ec40142015-12-15 19:44:45 +0000109StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
110 if (FileName.empty())
111 return PGOFuncName;
112 // Drop the file name including ':'. See also getPGOFuncName.
113 if (PGOFuncName.startswith(FileName))
114 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
115 return PGOFuncName;
116}
117
Xinliang David Lid1bab962015-12-12 17:28:03 +0000118// \p FuncName is the string used as profile lookup key for the function. A
119// symbol is created to hold the name. Return the legalized symbol name.
120static std::string getPGOFuncNameVarName(StringRef FuncName,
121 GlobalValue::LinkageTypes Linkage) {
122 std::string VarName = getInstrProfNameVarPrefix();
123 VarName += FuncName;
124
125 if (!GlobalValue::isLocalLinkage(Linkage))
126 return VarName;
127
128 // Now fix up illegal chars in local VarName that may upset the assembler.
129 const char *InvalidChars = "-:<>\"'";
130 size_t found = VarName.find_first_of(InvalidChars);
131 while (found != std::string::npos) {
132 VarName[found] = '_';
133 found = VarName.find_first_of(InvalidChars, found + 1);
134 }
135 return VarName;
136}
137
Xinliang David Li441959d2015-11-09 00:01:22 +0000138GlobalVariable *createPGOFuncNameVar(Module &M,
139 GlobalValue::LinkageTypes Linkage,
140 StringRef FuncName) {
141
142 // We generally want to match the function's linkage, but available_externally
143 // and extern_weak both have the wrong semantics, and anything that doesn't
144 // need to link across compilation units doesn't need to be visible at all.
145 if (Linkage == GlobalValue::ExternalWeakLinkage)
146 Linkage = GlobalValue::LinkOnceAnyLinkage;
147 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
148 Linkage = GlobalValue::LinkOnceODRLinkage;
149 else if (Linkage == GlobalValue::InternalLinkage ||
150 Linkage == GlobalValue::ExternalLinkage)
151 Linkage = GlobalValue::PrivateLinkage;
152
153 auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
154 auto FuncNameVar =
155 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Lid1bab962015-12-12 17:28:03 +0000156 getPGOFuncNameVarName(FuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000157
158 // Hide the symbol so that we correctly get a copy for each executable.
159 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
160 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
161
162 return FuncNameVar;
163}
164
165GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
166 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
167}
Xinliang David Liee415892015-11-10 00:24:45 +0000168
Xinliang David Li59411db2016-01-20 01:26:34 +0000169void InstrProfSymtab::create(const Module &M) {
170 for (const Function &F : M)
171 addFuncName(getPGOFuncName(F));
172
173 finalizeSymtab();
174}
175
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000176int collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
177 bool doCompression, std::string &Result) {
178 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000179 std::string UncompressedNameStrings =
180 join(NameStrs.begin(), NameStrs.end(), StringRef(" "));
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000181
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000182 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
183 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000184
185 auto WriteStringToResult = [&](size_t CompressedLen,
186 const std::string &InputStr) {
187 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000188 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000189 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
190 unsigned HeaderLen = P - &Header[0];
191 Result.append(HeaderStr, HeaderLen);
192 Result += InputStr;
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000193 return 0;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000194 };
195
196 if (!doCompression)
197 return WriteStringToResult(0, UncompressedNameStrings);
198
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000199 SmallVector<char, 128> CompressedNameStrings;
200 zlib::Status Success =
201 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
202 zlib::BestSizeCompression);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000203
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000204 if (Success != zlib::StatusOK)
205 return 1;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000206
207 return WriteStringToResult(
208 CompressedNameStrings.size(),
209 std::string(CompressedNameStrings.data(), CompressedNameStrings.size()));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000210}
211
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000212StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000213 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
214 StringRef NameStr =
215 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
216 return NameStr;
217}
218
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000219int collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
Xinliang David Li73163752016-01-26 23:13:00 +0000220 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000221 std::vector<std::string> NameStrs;
222 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000223 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000224 }
Xinliang David Li73163752016-01-26 23:13:00 +0000225 return collectPGOFuncNameStrings(
226 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000227}
228
229int readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
230 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
231 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
232 NameStrings.size());
233 while (P < EndP) {
234 uint32_t N;
235 uint64_t UncompressedSize = decodeULEB128(P, &N);
236 P += N;
237 uint64_t CompressedSize = decodeULEB128(P, &N);
238 P += N;
239 bool isCompressed = (CompressedSize != 0);
240 SmallString<128> UncompressedNameStrings;
241 StringRef NameStrings;
242 if (isCompressed) {
243 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
244 CompressedSize);
245 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
246 UncompressedSize) != zlib::StatusOK)
247 return 1;
248 P += CompressedSize;
249 NameStrings = StringRef(UncompressedNameStrings.data(),
250 UncompressedNameStrings.size());
251 } else {
252 NameStrings =
253 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
254 P += UncompressedSize;
255 }
256 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000257 SmallVector<StringRef, 0> Names;
258 NameStrings.split(Names, ' ');
259 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000260 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000261
262 while (P < EndP && *P == 0)
263 P++;
264 }
265 Symtab.finalizeSymtab();
266 return 0;
267}
268
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000269instrprof_error InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
270 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000271 this->sortByTargetValues();
272 Input.sortByTargetValues();
273 auto I = ValueData.begin();
274 auto IE = ValueData.end();
275 instrprof_error Result = instrprof_error::success;
276 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
277 ++J) {
278 while (I != IE && I->Value < J->Value)
279 ++I;
280 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000281 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000282 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000283 if (Overflowed)
284 Result = instrprof_error::counter_overflow;
285 ++I;
286 continue;
287 }
288 ValueData.insert(I, *J);
289 }
290 return Result;
291}
292
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000293instrprof_error InstrProfValueSiteRecord::scale(uint64_t Weight) {
294 instrprof_error Result = instrprof_error::success;
295 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
296 bool Overflowed;
297 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
298 if (Overflowed)
299 Result = instrprof_error::counter_overflow;
300 }
301 return Result;
302}
303
Xinliang David Li020f22d2015-12-18 23:06:37 +0000304// Merge Value Profile data from Src record to this record for ValueKind.
305// Scale merged value counts by \p Weight.
306instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
307 InstrProfRecord &Src,
308 uint64_t Weight) {
309 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
310 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
311 if (ThisNumValueSites != OtherNumValueSites)
312 return instrprof_error::value_site_count_mismatch;
313 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
314 getValueSitesForKind(ValueKind);
315 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
316 Src.getValueSitesForKind(ValueKind);
317 instrprof_error Result = instrprof_error::success;
318 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000319 MergeResult(Result, ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight));
Xinliang David Li020f22d2015-12-18 23:06:37 +0000320 return Result;
321}
322
323instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
324 uint64_t Weight) {
325 // If the number of counters doesn't match we either have bad data
326 // or a hash collision.
327 if (Counts.size() != Other.Counts.size())
328 return instrprof_error::count_mismatch;
329
330 instrprof_error Result = instrprof_error::success;
331
332 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
333 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000334 Counts[I] =
335 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000336 if (Overflowed)
337 Result = instrprof_error::counter_overflow;
338 }
339
340 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
341 MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
342
343 return Result;
344}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000345
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000346instrprof_error InstrProfRecord::scaleValueProfData(uint32_t ValueKind,
347 uint64_t Weight) {
348 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
349 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
350 getValueSitesForKind(ValueKind);
351 instrprof_error Result = instrprof_error::success;
352 for (uint32_t I = 0; I < ThisNumValueSites; I++)
353 MergeResult(Result, ThisSiteRecords[I].scale(Weight));
354 return Result;
355}
356
357instrprof_error InstrProfRecord::scale(uint64_t Weight) {
358 instrprof_error Result = instrprof_error::success;
359 for (auto &Count : this->Counts) {
360 bool Overflowed;
361 Count = SaturatingMultiply(Count, Weight, &Overflowed);
362 if (Overflowed && Result == instrprof_error::success) {
363 Result = instrprof_error::counter_overflow;
364 }
365 }
366 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
367 MergeResult(Result, scaleValueProfData(Kind, Weight));
368
369 return Result;
370}
371
Xinliang David Li020f22d2015-12-18 23:06:37 +0000372// Map indirect call target name hash to name string.
373uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000374 ValueMapType *ValueMap) {
375 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000376 return Value;
377 switch (ValueKind) {
378 case IPVK_IndirectCallTarget: {
379 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000380 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
381 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000382 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Lia716cc52015-12-20 06:22:13 +0000383 if (Result != ValueMap->end())
Xinliang David Li020f22d2015-12-18 23:06:37 +0000384 Value = (uint64_t)Result->second;
385 break;
386 }
387 }
388 return Value;
389}
390
Xinliang David Li020f22d2015-12-18 23:06:37 +0000391void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
392 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000393 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000394 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000395 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000396 }
397 std::vector<InstrProfValueSiteRecord> &ValueSites =
398 getValueSitesForKind(ValueKind);
399 if (N == 0)
400 ValueSites.push_back(InstrProfValueSiteRecord());
401 else
402 ValueSites.emplace_back(VData, VData + N);
403}
404
Xinliang David Lib75544a2015-11-28 19:07:09 +0000405#define INSTR_PROF_COMMON_API_IMPL
406#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000407
Xinliang David Li020f22d2015-12-18 23:06:37 +0000408/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000409 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000410 * class. These C wrappers are used as adaptors so that C++ code can be
411 * invoked as callbacks.
412 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000413uint32_t getNumValueKindsInstrProf(const void *Record) {
414 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
415}
416
417uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
418 return reinterpret_cast<const InstrProfRecord *>(Record)
419 ->getNumValueSites(VKind);
420}
421
422uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
423 return reinterpret_cast<const InstrProfRecord *>(Record)
424 ->getNumValueData(VKind);
425}
426
427uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
428 uint32_t S) {
429 return reinterpret_cast<const InstrProfRecord *>(R)
430 ->getNumValueDataForSite(VK, S);
431}
432
433void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000434 uint32_t K, uint32_t S) {
435 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
436 return;
Xinliang David Lie8092312015-11-25 19:13:00 +0000437}
438
Xinliang David Lif47cf552015-11-25 06:23:38 +0000439ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000440 ValueProfData *VD =
441 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
442 memset(VD, 0, TotalSizeInBytes);
443 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000444}
445
446static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000447 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000448 getNumValueKindsInstrProf,
449 getNumValueSitesInstrProf,
450 getNumValueDataInstrProf,
451 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000452 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000453 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000454 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000455
Xinliang David Lie8092312015-11-25 19:13:00 +0000456// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000457uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
458 InstrProfRecordClosure.Record = &Record;
459 return getValueProfDataSize(&InstrProfRecordClosure);
460}
461
Xinliang David Lie8092312015-11-25 19:13:00 +0000462// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000463std::unique_ptr<ValueProfData>
464ValueProfData::serializeFrom(const InstrProfRecord &Record) {
465 InstrProfRecordClosure.Record = &Record;
466
467 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000468 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000469 return VPD;
470}
471
Xinliang David Lie8092312015-11-25 19:13:00 +0000472void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
473 InstrProfRecord::ValueMapType *VMap) {
474 Record.reserveSites(Kind, NumValueSites);
475
476 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
477 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
478 uint8_t ValueDataCount = this->SiteCountArray[VSite];
479 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
480 ValueData += ValueDataCount;
481 }
482}
Xinliang David Lied966772015-11-25 23:31:18 +0000483
Xinliang David Lie8092312015-11-25 19:13:00 +0000484// For writing/serializing, Old is the host endianness, and New is
485// byte order intended on disk. For Reading/deserialization, Old
486// is the on-disk source endianness, and New is the host endianness.
487void ValueProfRecord::swapBytes(support::endianness Old,
488 support::endianness New) {
489 using namespace support;
490 if (Old == New)
491 return;
492
493 if (getHostEndianness() != Old) {
494 sys::swapByteOrder<uint32_t>(NumValueSites);
495 sys::swapByteOrder<uint32_t>(Kind);
496 }
497 uint32_t ND = getValueProfRecordNumValueData(this);
498 InstrProfValueData *VD = getValueProfRecordValueData(this);
499
500 // No need to swap byte array: SiteCountArrray.
501 for (uint32_t I = 0; I < ND; I++) {
502 sys::swapByteOrder<uint64_t>(VD[I].Value);
503 sys::swapByteOrder<uint64_t>(VD[I].Count);
504 }
505 if (getHostEndianness() == Old) {
506 sys::swapByteOrder<uint32_t>(NumValueSites);
507 sys::swapByteOrder<uint32_t>(Kind);
508 }
509}
510
511void ValueProfData::deserializeTo(InstrProfRecord &Record,
512 InstrProfRecord::ValueMapType *VMap) {
513 if (NumValueKinds == 0)
514 return;
515
516 ValueProfRecord *VR = getFirstValueProfRecord(this);
517 for (uint32_t K = 0; K < NumValueKinds; K++) {
518 VR->deserializeTo(Record, VMap);
519 VR = getValueProfRecordNext(VR);
520 }
521}
522
523template <class T>
524static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
525 using namespace support;
526 if (Orig == little)
527 return endian::readNext<T, little, unaligned>(D);
528 else
529 return endian::readNext<T, big, unaligned>(D);
530}
531
532static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
533 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
534 ValueProfData());
535}
536
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000537instrprof_error ValueProfData::checkIntegrity() {
538 if (NumValueKinds > IPVK_Last + 1)
539 return instrprof_error::malformed;
540 // Total size needs to be mulltiple of quadword size.
541 if (TotalSize % sizeof(uint64_t))
542 return instrprof_error::malformed;
543
544 ValueProfRecord *VR = getFirstValueProfRecord(this);
545 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
546 if (VR->Kind > IPVK_Last)
547 return instrprof_error::malformed;
548 VR = getValueProfRecordNext(VR);
549 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
550 return instrprof_error::malformed;
551 }
552 return instrprof_error::success;
553}
554
Xinliang David Liee415892015-11-10 00:24:45 +0000555ErrorOr<std::unique_ptr<ValueProfData>>
556ValueProfData::getValueProfData(const unsigned char *D,
557 const unsigned char *const BufferEnd,
558 support::endianness Endianness) {
559 using namespace support;
560 if (D + sizeof(ValueProfData) > BufferEnd)
561 return instrprof_error::truncated;
562
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000563 const unsigned char *Header = D;
564 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000565 if (D + TotalSize > BufferEnd)
566 return instrprof_error::too_large;
Xinliang David Liee415892015-11-10 00:24:45 +0000567
Xinliang David Lif47cf552015-11-25 06:23:38 +0000568 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000569 memcpy(VPD.get(), D, TotalSize);
570 // Byte swap.
571 VPD->swapBytesToHost(Endianness);
572
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000573 instrprof_error EC = VPD->checkIntegrity();
574 if (EC != instrprof_error::success)
575 return EC;
Xinliang David Liee415892015-11-10 00:24:45 +0000576
Xinliang David Liee415892015-11-10 00:24:45 +0000577 return std::move(VPD);
578}
579
580void ValueProfData::swapBytesToHost(support::endianness Endianness) {
581 using namespace support;
582 if (Endianness == getHostEndianness())
583 return;
584
585 sys::swapByteOrder<uint32_t>(TotalSize);
586 sys::swapByteOrder<uint32_t>(NumValueKinds);
587
Xinliang David Lif47cf552015-11-25 06:23:38 +0000588 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000589 for (uint32_t K = 0; K < NumValueKinds; K++) {
590 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000591 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000592 }
593}
594
595void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
596 using namespace support;
597 if (Endianness == getHostEndianness())
598 return;
599
Xinliang David Lif47cf552015-11-25 06:23:38 +0000600 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000601 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000602 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000603 VR->swapBytes(getHostEndianness(), Endianness);
604 VR = NVR;
605 }
606 sys::swapByteOrder<uint32_t>(TotalSize);
607 sys::swapByteOrder<uint32_t>(NumValueKinds);
608}
Xinliang David Lie8092312015-11-25 19:13:00 +0000609
Xinliang David Li402477d2016-02-04 19:11:43 +0000610void annotateValueSite(Module &M, Instruction &Inst,
611 const InstrProfRecord &InstrProfR,
612 InstrProfValueKind ValueKind, uint32_t SiteIdx) {
613 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
614
615 uint64_t Sum = 0;
616 std::unique_ptr<InstrProfValueData[]> VD =
617 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
618
619 LLVMContext &Ctx = M.getContext();
620 MDBuilder MDHelper(Ctx);
621 SmallVector<Metadata *, 3> Vals;
622 // Tag
623 Vals.push_back(MDHelper.createString("VP"));
624 // Value Kind
625 Vals.push_back(MDHelper.createConstant(
626 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
627 // Total Count
628 Vals.push_back(
629 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
630
631 // Value Profile Data
632 uint32_t MDCount = 3;
633 for (uint32_t I = 0; I < NV; ++I) {
634 Vals.push_back(MDHelper.createConstant(
635 ConstantInt::get(Type::getInt64Ty(Ctx), VD[I].Value)));
636 Vals.push_back(MDHelper.createConstant(
637 ConstantInt::get(Type::getInt64Ty(Ctx), VD[I].Count)));
638 if (--MDCount == 0)
639 break;
640 }
641 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
642}
643
644bool getValueProfDataFromInst(const Instruction &Inst,
645 InstrProfValueKind ValueKind,
646 uint32_t MaxNumValueData,
647 InstrProfValueData ValueData[],
648 uint32_t &ActualNumValueData, uint64_t &TotalC) {
649 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
650 if (!MD)
651 return false;
652
653 unsigned NOps = MD->getNumOperands();
654
655 if (NOps < 5)
656 return false;
657
658 // Operand 0 is a string tag "VP":
659 MDString *Tag = cast<MDString>(MD->getOperand(0));
660 if (!Tag)
661 return false;
662
663 if (!Tag->getString().equals("VP"))
664 return false;
665
666 // Now check kind:
667 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
668 if (!KindInt)
669 return false;
670 if (KindInt->getZExtValue() != ValueKind)
671 return false;
672
673 // Get total count
674 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
675 if (!TotalCInt)
676 return false;
677 TotalC = TotalCInt->getZExtValue();
678
679 ActualNumValueData = 0;
680
681 for (unsigned I = 3; I < NOps; I += 2) {
682 if (ActualNumValueData >= MaxNumValueData)
683 break;
684 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
685 ConstantInt *Count =
686 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
687 if (!Value || !Count)
688 return false;
689 ValueData[ActualNumValueData].Value = Value->getZExtValue();
690 ValueData[ActualNumValueData].Count = Count->getZExtValue();
691 ActualNumValueData++;
692 }
693 return true;
694}
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000695} // end namespace llvm