blob: f459d2d54314a7096cf0956496682c9141e9a4c1 [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)";
Vedant Kumar43cba732016-05-03 16:53:17 +000065 case instrprof_error::compress_failed:
66 return "Failed to compress data (zlib)";
67 case instrprof_error::uncompress_failed:
68 return "Failed to uncompress data (zlib)";
Justin Bognerf8d79192014-03-21 17:24:48 +000069 }
70 llvm_unreachable("A value of instrprof_error has no message.");
71 }
Justin Bognerf8d79192014-03-21 17:24:48 +000072};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000073} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +000074
Chris Bieneman1efe8012014-09-19 23:19:24 +000075static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
76
Rafael Espindola25188c92014-06-12 01:45:43 +000077const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +000078 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +000079}
Xinliang David Li441959d2015-11-09 00:01:22 +000080
81namespace llvm {
82
83std::string getPGOFuncName(StringRef RawFuncName,
84 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +000085 StringRef FileName,
86 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +000087 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +000088}
89
Rong Xub5341662016-03-30 18:37:52 +000090// Return the PGOFuncName. This function has some special handling when called
91// in LTO optimization. The following only applies when calling in LTO passes
92// (when \c InLTO is true): LTO's internalization privatizes many global linkage
93// symbols. This happens after value profile annotation, but those internal
94// linkage functions should not have a source prefix.
95// To differentiate compiler generated internal symbols from original ones,
96// PGOFuncName meta data are created and attached to the original internal
97// symbols in the value profile annotation step
98// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
99// data, its original linkage must be non-internal.
100std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
101 if (!InLTO)
102 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
103 Version);
104
Rong Xu8e8fe852016-04-01 16:43:30 +0000105 // In LTO mode (when InLTO is true), first check if there is a meta data.
106 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
Rong Xub5341662016-03-30 18:37:52 +0000107 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
108 return S.str();
109 }
110
111 // If there is no meta data, the function must be a global before the value
112 // profile annotation pass. Its current linkage may be internal if it is
113 // internalized in LTO mode.
Rong Xu8e8fe852016-04-01 16:43:30 +0000114 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
Xinliang David Li441959d2015-11-09 00:01:22 +0000115}
116
Xinliang David Li4ec40142015-12-15 19:44:45 +0000117StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
118 if (FileName.empty())
Vedant Kumar43a85652016-03-28 15:49:08 +0000119 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +0000120 // Drop the file name including ':'. See also getPGOFuncName.
121 if (PGOFuncName.startswith(FileName))
122 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
123 return PGOFuncName;
124}
125
Xinliang David Lid1bab962015-12-12 17:28:03 +0000126// \p FuncName is the string used as profile lookup key for the function. A
127// symbol is created to hold the name. Return the legalized symbol name.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000128std::string getPGOFuncNameVarName(StringRef FuncName,
129 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000130 std::string VarName = getInstrProfNameVarPrefix();
131 VarName += FuncName;
132
133 if (!GlobalValue::isLocalLinkage(Linkage))
134 return VarName;
135
136 // Now fix up illegal chars in local VarName that may upset the assembler.
137 const char *InvalidChars = "-:<>\"'";
138 size_t found = VarName.find_first_of(InvalidChars);
139 while (found != std::string::npos) {
140 VarName[found] = '_';
141 found = VarName.find_first_of(InvalidChars, found + 1);
142 }
143 return VarName;
144}
145
Xinliang David Li441959d2015-11-09 00:01:22 +0000146GlobalVariable *createPGOFuncNameVar(Module &M,
147 GlobalValue::LinkageTypes Linkage,
Xinliang David Li897d2922016-03-16 22:13:41 +0000148 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000149
150 // We generally want to match the function's linkage, but available_externally
151 // and extern_weak both have the wrong semantics, and anything that doesn't
152 // need to link across compilation units doesn't need to be visible at all.
153 if (Linkage == GlobalValue::ExternalWeakLinkage)
154 Linkage = GlobalValue::LinkOnceAnyLinkage;
155 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
156 Linkage = GlobalValue::LinkOnceODRLinkage;
157 else if (Linkage == GlobalValue::InternalLinkage ||
158 Linkage == GlobalValue::ExternalLinkage)
159 Linkage = GlobalValue::PrivateLinkage;
160
Xinliang David Li897d2922016-03-16 22:13:41 +0000161 auto *Value =
162 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000163 auto FuncNameVar =
164 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000165 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000166
167 // Hide the symbol so that we correctly get a copy for each executable.
168 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
169 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
170
171 return FuncNameVar;
172}
173
Xinliang David Li897d2922016-03-16 22:13:41 +0000174GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
175 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000176}
Xinliang David Liee415892015-11-10 00:24:45 +0000177
Rong Xub5341662016-03-30 18:37:52 +0000178void InstrProfSymtab::create(Module &M, bool InLTO) {
179 for (Function &F : M) {
180 // Function may not have a name: like using asm("") to overwrite the name.
181 // Ignore in this case.
182 if (!F.hasName())
183 continue;
184 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
185 addFuncName(PGOFuncName);
Rong Xud5a57b52016-03-31 17:39:33 +0000186 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
Rong Xub5341662016-03-30 18:37:52 +0000187 }
Xinliang David Li59411db2016-01-20 01:26:34 +0000188
189 finalizeSymtab();
190}
191
Vedant Kumar43cba732016-05-03 16:53:17 +0000192std::error_code
193collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
194 bool doCompression, std::string &Result) {
Vedant Kumar86705ba2016-03-28 21:06:42 +0000195 assert(NameStrs.size() && "No name data to emit");
196
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000197 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000198 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000199 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
200
201 assert(StringRef(UncompressedNameStrings)
202 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
203 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000204
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000205 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
206 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000207
208 auto WriteStringToResult = [&](size_t CompressedLen,
209 const std::string &InputStr) {
210 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000211 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000212 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
213 unsigned HeaderLen = P - &Header[0];
214 Result.append(HeaderStr, HeaderLen);
215 Result += InputStr;
Vedant Kumar43cba732016-05-03 16:53:17 +0000216 return make_error_code(instrprof_error::success);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000217 };
218
219 if (!doCompression)
220 return WriteStringToResult(0, UncompressedNameStrings);
221
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000222 SmallVector<char, 128> CompressedNameStrings;
223 zlib::Status Success =
224 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
225 zlib::BestSizeCompression);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000226
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000227 if (Success != zlib::StatusOK)
Vedant Kumar43cba732016-05-03 16:53:17 +0000228 return make_error_code(instrprof_error::compress_failed);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000229
230 return WriteStringToResult(
231 CompressedNameStrings.size(),
232 std::string(CompressedNameStrings.data(), CompressedNameStrings.size()));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000233}
234
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000235StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000236 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
237 StringRef NameStr =
238 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
239 return NameStr;
240}
241
Vedant Kumar43cba732016-05-03 16:53:17 +0000242std::error_code
243collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
244 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000245 std::vector<std::string> NameStrs;
246 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000247 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000248 }
Xinliang David Li73163752016-01-26 23:13:00 +0000249 return collectPGOFuncNameStrings(
250 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000251}
252
Vedant Kumar43cba732016-05-03 16:53:17 +0000253std::error_code readPGOFuncNameStrings(StringRef NameStrings,
254 InstrProfSymtab &Symtab) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000255 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
256 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
257 NameStrings.size());
258 while (P < EndP) {
259 uint32_t N;
260 uint64_t UncompressedSize = decodeULEB128(P, &N);
261 P += N;
262 uint64_t CompressedSize = decodeULEB128(P, &N);
263 P += N;
264 bool isCompressed = (CompressedSize != 0);
265 SmallString<128> UncompressedNameStrings;
266 StringRef NameStrings;
267 if (isCompressed) {
268 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
269 CompressedSize);
270 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
271 UncompressedSize) != zlib::StatusOK)
Vedant Kumar43cba732016-05-03 16:53:17 +0000272 return make_error_code(instrprof_error::uncompress_failed);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000273 P += CompressedSize;
274 NameStrings = StringRef(UncompressedNameStrings.data(),
275 UncompressedNameStrings.size());
276 } else {
277 NameStrings =
278 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
279 P += UncompressedSize;
280 }
281 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000282 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000283 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000284 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000285 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000286
287 while (P < EndP && *P == 0)
288 P++;
289 }
290 Symtab.finalizeSymtab();
Vedant Kumar43cba732016-05-03 16:53:17 +0000291 return make_error_code(instrprof_error::success);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000292}
293
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000294instrprof_error InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
295 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000296 this->sortByTargetValues();
297 Input.sortByTargetValues();
298 auto I = ValueData.begin();
299 auto IE = ValueData.end();
300 instrprof_error Result = instrprof_error::success;
301 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
302 ++J) {
303 while (I != IE && I->Value < J->Value)
304 ++I;
305 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000306 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000307 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000308 if (Overflowed)
309 Result = instrprof_error::counter_overflow;
310 ++I;
311 continue;
312 }
313 ValueData.insert(I, *J);
314 }
315 return Result;
316}
317
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000318instrprof_error InstrProfValueSiteRecord::scale(uint64_t Weight) {
319 instrprof_error Result = instrprof_error::success;
320 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
321 bool Overflowed;
322 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
323 if (Overflowed)
324 Result = instrprof_error::counter_overflow;
325 }
326 return Result;
327}
328
Xinliang David Li020f22d2015-12-18 23:06:37 +0000329// Merge Value Profile data from Src record to this record for ValueKind.
330// Scale merged value counts by \p Weight.
331instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
332 InstrProfRecord &Src,
333 uint64_t Weight) {
334 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
335 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
336 if (ThisNumValueSites != OtherNumValueSites)
337 return instrprof_error::value_site_count_mismatch;
338 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
339 getValueSitesForKind(ValueKind);
340 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
341 Src.getValueSitesForKind(ValueKind);
342 instrprof_error Result = instrprof_error::success;
343 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000344 MergeResult(Result, ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight));
Xinliang David Li020f22d2015-12-18 23:06:37 +0000345 return Result;
346}
347
348instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
349 uint64_t Weight) {
350 // If the number of counters doesn't match we either have bad data
351 // or a hash collision.
352 if (Counts.size() != Other.Counts.size())
353 return instrprof_error::count_mismatch;
354
355 instrprof_error Result = instrprof_error::success;
356
357 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
358 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000359 Counts[I] =
360 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000361 if (Overflowed)
362 Result = instrprof_error::counter_overflow;
363 }
364
365 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
366 MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
367
368 return Result;
369}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000370
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000371instrprof_error InstrProfRecord::scaleValueProfData(uint32_t ValueKind,
372 uint64_t Weight) {
373 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
374 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
375 getValueSitesForKind(ValueKind);
376 instrprof_error Result = instrprof_error::success;
377 for (uint32_t I = 0; I < ThisNumValueSites; I++)
378 MergeResult(Result, ThisSiteRecords[I].scale(Weight));
379 return Result;
380}
381
382instrprof_error InstrProfRecord::scale(uint64_t Weight) {
383 instrprof_error Result = instrprof_error::success;
384 for (auto &Count : this->Counts) {
385 bool Overflowed;
386 Count = SaturatingMultiply(Count, Weight, &Overflowed);
387 if (Overflowed && Result == instrprof_error::success) {
388 Result = instrprof_error::counter_overflow;
389 }
390 }
391 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
392 MergeResult(Result, scaleValueProfData(Kind, Weight));
393
394 return Result;
395}
396
Xinliang David Li020f22d2015-12-18 23:06:37 +0000397// Map indirect call target name hash to name string.
398uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000399 ValueMapType *ValueMap) {
400 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000401 return Value;
402 switch (ValueKind) {
403 case IPVK_IndirectCallTarget: {
404 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000405 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
406 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000407 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Li8dd4ca82016-04-11 17:13:08 +0000408 // Raw function pointer collected by value profiler may be from
409 // external functions that are not instrumented. They won't have
410 // mapping data to be used by the deserializer. Force the value to
411 // be 0 in this case.
Xinliang David Li28464482016-04-10 03:32:02 +0000412 if (Result != ValueMap->end() && Result->first == Value)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000413 Value = (uint64_t)Result->second;
Xinliang David Li28464482016-04-10 03:32:02 +0000414 else
415 Value = 0;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000416 break;
417 }
418 }
419 return Value;
420}
421
Xinliang David Li020f22d2015-12-18 23:06:37 +0000422void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
423 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000424 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000425 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000426 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000427 }
428 std::vector<InstrProfValueSiteRecord> &ValueSites =
429 getValueSitesForKind(ValueKind);
430 if (N == 0)
431 ValueSites.push_back(InstrProfValueSiteRecord());
432 else
433 ValueSites.emplace_back(VData, VData + N);
434}
435
Xinliang David Lib75544a2015-11-28 19:07:09 +0000436#define INSTR_PROF_COMMON_API_IMPL
437#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000438
Xinliang David Li020f22d2015-12-18 23:06:37 +0000439/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000440 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000441 * class. These C wrappers are used as adaptors so that C++ code can be
442 * invoked as callbacks.
443 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000444uint32_t getNumValueKindsInstrProf(const void *Record) {
445 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
446}
447
448uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
449 return reinterpret_cast<const InstrProfRecord *>(Record)
450 ->getNumValueSites(VKind);
451}
452
453uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
454 return reinterpret_cast<const InstrProfRecord *>(Record)
455 ->getNumValueData(VKind);
456}
457
458uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
459 uint32_t S) {
460 return reinterpret_cast<const InstrProfRecord *>(R)
461 ->getNumValueDataForSite(VK, S);
462}
463
464void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000465 uint32_t K, uint32_t S) {
466 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
Xinliang David Lie8092312015-11-25 19:13:00 +0000467}
468
Xinliang David Lif47cf552015-11-25 06:23:38 +0000469ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000470 ValueProfData *VD =
471 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
472 memset(VD, 0, TotalSizeInBytes);
473 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000474}
475
476static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000477 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000478 getNumValueKindsInstrProf,
479 getNumValueSitesInstrProf,
480 getNumValueDataInstrProf,
481 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000482 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000483 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000484 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000485
Xinliang David Lie8092312015-11-25 19:13:00 +0000486// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000487uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
488 InstrProfRecordClosure.Record = &Record;
489 return getValueProfDataSize(&InstrProfRecordClosure);
490}
491
Xinliang David Lie8092312015-11-25 19:13:00 +0000492// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000493std::unique_ptr<ValueProfData>
494ValueProfData::serializeFrom(const InstrProfRecord &Record) {
495 InstrProfRecordClosure.Record = &Record;
496
497 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000498 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000499 return VPD;
500}
501
Xinliang David Lie8092312015-11-25 19:13:00 +0000502void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
503 InstrProfRecord::ValueMapType *VMap) {
504 Record.reserveSites(Kind, NumValueSites);
505
506 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
507 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
508 uint8_t ValueDataCount = this->SiteCountArray[VSite];
509 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
510 ValueData += ValueDataCount;
511 }
512}
Xinliang David Lied966772015-11-25 23:31:18 +0000513
Xinliang David Lie8092312015-11-25 19:13:00 +0000514// For writing/serializing, Old is the host endianness, and New is
515// byte order intended on disk. For Reading/deserialization, Old
516// is the on-disk source endianness, and New is the host endianness.
517void ValueProfRecord::swapBytes(support::endianness Old,
518 support::endianness New) {
519 using namespace support;
520 if (Old == New)
521 return;
522
523 if (getHostEndianness() != Old) {
524 sys::swapByteOrder<uint32_t>(NumValueSites);
525 sys::swapByteOrder<uint32_t>(Kind);
526 }
527 uint32_t ND = getValueProfRecordNumValueData(this);
528 InstrProfValueData *VD = getValueProfRecordValueData(this);
529
530 // No need to swap byte array: SiteCountArrray.
531 for (uint32_t I = 0; I < ND; I++) {
532 sys::swapByteOrder<uint64_t>(VD[I].Value);
533 sys::swapByteOrder<uint64_t>(VD[I].Count);
534 }
535 if (getHostEndianness() == Old) {
536 sys::swapByteOrder<uint32_t>(NumValueSites);
537 sys::swapByteOrder<uint32_t>(Kind);
538 }
539}
540
541void ValueProfData::deserializeTo(InstrProfRecord &Record,
542 InstrProfRecord::ValueMapType *VMap) {
543 if (NumValueKinds == 0)
544 return;
545
546 ValueProfRecord *VR = getFirstValueProfRecord(this);
547 for (uint32_t K = 0; K < NumValueKinds; K++) {
548 VR->deserializeTo(Record, VMap);
549 VR = getValueProfRecordNext(VR);
550 }
551}
552
553template <class T>
554static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
555 using namespace support;
556 if (Orig == little)
557 return endian::readNext<T, little, unaligned>(D);
558 else
559 return endian::readNext<T, big, unaligned>(D);
560}
561
562static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
563 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
564 ValueProfData());
565}
566
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000567instrprof_error ValueProfData::checkIntegrity() {
568 if (NumValueKinds > IPVK_Last + 1)
569 return instrprof_error::malformed;
570 // Total size needs to be mulltiple of quadword size.
571 if (TotalSize % sizeof(uint64_t))
572 return instrprof_error::malformed;
573
574 ValueProfRecord *VR = getFirstValueProfRecord(this);
575 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
576 if (VR->Kind > IPVK_Last)
577 return instrprof_error::malformed;
578 VR = getValueProfRecordNext(VR);
579 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
580 return instrprof_error::malformed;
581 }
582 return instrprof_error::success;
583}
584
Xinliang David Liee415892015-11-10 00:24:45 +0000585ErrorOr<std::unique_ptr<ValueProfData>>
586ValueProfData::getValueProfData(const unsigned char *D,
587 const unsigned char *const BufferEnd,
588 support::endianness Endianness) {
589 using namespace support;
590 if (D + sizeof(ValueProfData) > BufferEnd)
591 return instrprof_error::truncated;
592
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000593 const unsigned char *Header = D;
594 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000595 if (D + TotalSize > BufferEnd)
596 return instrprof_error::too_large;
Xinliang David Liee415892015-11-10 00:24:45 +0000597
Xinliang David Lif47cf552015-11-25 06:23:38 +0000598 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000599 memcpy(VPD.get(), D, TotalSize);
600 // Byte swap.
601 VPD->swapBytesToHost(Endianness);
602
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000603 instrprof_error EC = VPD->checkIntegrity();
604 if (EC != instrprof_error::success)
605 return EC;
Xinliang David Liee415892015-11-10 00:24:45 +0000606
Xinliang David Liee415892015-11-10 00:24:45 +0000607 return std::move(VPD);
608}
609
610void ValueProfData::swapBytesToHost(support::endianness Endianness) {
611 using namespace support;
612 if (Endianness == getHostEndianness())
613 return;
614
615 sys::swapByteOrder<uint32_t>(TotalSize);
616 sys::swapByteOrder<uint32_t>(NumValueKinds);
617
Xinliang David Lif47cf552015-11-25 06:23:38 +0000618 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000619 for (uint32_t K = 0; K < NumValueKinds; K++) {
620 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000621 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000622 }
623}
624
625void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
626 using namespace support;
627 if (Endianness == getHostEndianness())
628 return;
629
Xinliang David Lif47cf552015-11-25 06:23:38 +0000630 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000631 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000632 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000633 VR->swapBytes(getHostEndianness(), Endianness);
634 VR = NVR;
635 }
636 sys::swapByteOrder<uint32_t>(TotalSize);
637 sys::swapByteOrder<uint32_t>(NumValueKinds);
638}
Xinliang David Lie8092312015-11-25 19:13:00 +0000639
Xinliang David Li402477d2016-02-04 19:11:43 +0000640void annotateValueSite(Module &M, Instruction &Inst,
641 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000642 InstrProfValueKind ValueKind, uint32_t SiteIdx,
643 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000644 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
Betul Buyukkurt4f1e8c92016-04-14 16:25:45 +0000645 if (!NV)
646 return;
Xinliang David Li402477d2016-02-04 19:11:43 +0000647
648 uint64_t Sum = 0;
649 std::unique_ptr<InstrProfValueData[]> VD =
650 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
651
Rong Xu311ada12016-03-30 16:56:31 +0000652 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
653 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000654}
655
656void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000657 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000658 uint64_t Sum, InstrProfValueKind ValueKind,
659 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000660 LLVMContext &Ctx = M.getContext();
661 MDBuilder MDHelper(Ctx);
662 SmallVector<Metadata *, 3> Vals;
663 // Tag
664 Vals.push_back(MDHelper.createString("VP"));
665 // Value Kind
666 Vals.push_back(MDHelper.createConstant(
667 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
668 // Total Count
669 Vals.push_back(
670 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
671
672 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000673 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000674 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000675 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000676 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000677 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000678 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000679 if (--MDCount == 0)
680 break;
681 }
682 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
683}
684
685bool getValueProfDataFromInst(const Instruction &Inst,
686 InstrProfValueKind ValueKind,
687 uint32_t MaxNumValueData,
688 InstrProfValueData ValueData[],
689 uint32_t &ActualNumValueData, uint64_t &TotalC) {
690 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
691 if (!MD)
692 return false;
693
694 unsigned NOps = MD->getNumOperands();
695
696 if (NOps < 5)
697 return false;
698
699 // Operand 0 is a string tag "VP":
700 MDString *Tag = cast<MDString>(MD->getOperand(0));
701 if (!Tag)
702 return false;
703
704 if (!Tag->getString().equals("VP"))
705 return false;
706
707 // Now check kind:
708 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
709 if (!KindInt)
710 return false;
711 if (KindInt->getZExtValue() != ValueKind)
712 return false;
713
714 // Get total count
715 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
716 if (!TotalCInt)
717 return false;
718 TotalC = TotalCInt->getZExtValue();
719
720 ActualNumValueData = 0;
721
722 for (unsigned I = 3; I < NOps; I += 2) {
723 if (ActualNumValueData >= MaxNumValueData)
724 break;
725 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
726 ConstantInt *Count =
727 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
728 if (!Value || !Count)
729 return false;
730 ValueData[ActualNumValueData].Value = Value->getZExtValue();
731 ValueData[ActualNumValueData].Count = Count->getZExtValue();
732 ActualNumValueData++;
733 }
734 return true;
735}
Rong Xu8e8fe852016-04-01 16:43:30 +0000736
Rong Xu92c2eae2016-04-01 20:15:04 +0000737MDNode *getPGOFuncNameMetadata(const Function &F) {
738 return F.getMetadata(getPGOFuncNameMetadataName());
739}
740
Rong Xuf8f051c2016-04-22 21:00:17 +0000741void createPGOFuncNameMetadata(Function &F, const std::string &PGOFuncName) {
742 // Only for internal linkage functions.
743 if (PGOFuncName == F.getName())
744 return;
745 // Don't create duplicated meta-data.
746 if (getPGOFuncNameMetadata(F))
Rong Xu8e8fe852016-04-01 16:43:30 +0000747 return;
Rong Xu8e8fe852016-04-01 16:43:30 +0000748 LLVMContext &C = F.getContext();
Rong Xuf8f051c2016-04-22 21:00:17 +0000749 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName.c_str()));
Rong Xu8e8fe852016-04-01 16:43:30 +0000750 F.setMetadata(getPGOFuncNameMetadataName(), N);
751}
752
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000753} // end namespace llvm