blob: 19b3f036b2888c1e5a33ec3f4419ecad97d36c8c [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 {
Vedant Kumar9152fd12016-05-19 03:54:45 +000030std::string getInstrProfErrString(instrprof_error Err) {
31 switch (Err) {
32 case instrprof_error::success:
33 return "Success";
34 case instrprof_error::eof:
35 return "End of File";
36 case instrprof_error::unrecognized_format:
37 return "Unrecognized instrumentation profile encoding format";
38 case instrprof_error::bad_magic:
39 return "Invalid instrumentation profile data (bad magic)";
40 case instrprof_error::bad_header:
41 return "Invalid instrumentation profile data (file header is corrupt)";
42 case instrprof_error::unsupported_version:
43 return "Unsupported instrumentation profile format version";
44 case instrprof_error::unsupported_hash_type:
45 return "Unsupported instrumentation profile hash type";
46 case instrprof_error::too_large:
47 return "Too much profile data";
48 case instrprof_error::truncated:
49 return "Truncated profile data";
50 case instrprof_error::malformed:
51 return "Malformed instrumentation profile data";
52 case instrprof_error::unknown_function:
53 return "No profile data available for function";
54 case instrprof_error::hash_mismatch:
55 return "Function control flow change detected (hash mismatch)";
56 case instrprof_error::count_mismatch:
57 return "Function basic block count change detected (counter mismatch)";
58 case instrprof_error::counter_overflow:
59 return "Counter overflow";
60 case instrprof_error::value_site_count_mismatch:
61 return "Function value site count change detected (counter mismatch)";
62 case instrprof_error::compress_failed:
63 return "Failed to compress data (zlib)";
64 case instrprof_error::uncompress_failed:
65 return "Failed to uncompress data (zlib)";
66 }
67 llvm_unreachable("A value of instrprof_error has no message.");
68}
69
Peter Collingbourne4718f8b2016-05-24 20:13:46 +000070// FIXME: This class is only here to support the transition to llvm::Error. It
71// will be removed once this transition is complete. Clients should prefer to
72// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +000073class InstrProfErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +000074 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
Justin Bognerf8d79192014-03-21 17:24:48 +000075 std::string message(int IE) const override {
Vedant Kumar9152fd12016-05-19 03:54:45 +000076 return getInstrProfErrString(static_cast<instrprof_error>(IE));
Justin Bognerf8d79192014-03-21 17:24:48 +000077 }
Justin Bognerf8d79192014-03-21 17:24:48 +000078};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000079} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +000080
Chris Bieneman1efe8012014-09-19 23:19:24 +000081static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
82
Rafael Espindola25188c92014-06-12 01:45:43 +000083const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +000084 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +000085}
Xinliang David Li441959d2015-11-09 00:01:22 +000086
87namespace llvm {
88
Vedant Kumar42369db2016-05-11 19:42:19 +000089void SoftInstrProfErrors::addError(instrprof_error IE) {
90 if (IE == instrprof_error::success)
91 return;
92
93 if (FirstError == instrprof_error::success)
94 FirstError = IE;
95
96 switch (IE) {
97 case instrprof_error::hash_mismatch:
98 ++NumHashMismatches;
99 break;
100 case instrprof_error::count_mismatch:
101 ++NumCountMismatches;
102 break;
103 case instrprof_error::counter_overflow:
104 ++NumCounterOverflows;
105 break;
106 case instrprof_error::value_site_count_mismatch:
107 ++NumValueSiteCountMismatches;
108 break;
109 default:
110 llvm_unreachable("Not a soft error");
111 }
112}
113
Vedant Kumar9152fd12016-05-19 03:54:45 +0000114std::string InstrProfError::message() const {
115 return getInstrProfErrString(Err);
116}
117
118char InstrProfError::ID = 0;
119
Xinliang David Li441959d2015-11-09 00:01:22 +0000120std::string getPGOFuncName(StringRef RawFuncName,
121 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +0000122 StringRef FileName,
123 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +0000124 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000125}
126
Rong Xub5341662016-03-30 18:37:52 +0000127// Return the PGOFuncName. This function has some special handling when called
128// in LTO optimization. The following only applies when calling in LTO passes
129// (when \c InLTO is true): LTO's internalization privatizes many global linkage
130// symbols. This happens after value profile annotation, but those internal
131// linkage functions should not have a source prefix.
132// To differentiate compiler generated internal symbols from original ones,
133// PGOFuncName meta data are created and attached to the original internal
134// symbols in the value profile annotation step
135// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
136// data, its original linkage must be non-internal.
137std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
138 if (!InLTO)
139 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
140 Version);
141
Rong Xu8e8fe852016-04-01 16:43:30 +0000142 // In LTO mode (when InLTO is true), first check if there is a meta data.
143 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
Rong Xub5341662016-03-30 18:37:52 +0000144 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
145 return S.str();
146 }
147
148 // If there is no meta data, the function must be a global before the value
149 // profile annotation pass. Its current linkage may be internal if it is
150 // internalized in LTO mode.
Rong Xu8e8fe852016-04-01 16:43:30 +0000151 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
Xinliang David Li441959d2015-11-09 00:01:22 +0000152}
153
Xinliang David Li4ec40142015-12-15 19:44:45 +0000154StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
155 if (FileName.empty())
Vedant Kumar43a85652016-03-28 15:49:08 +0000156 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +0000157 // Drop the file name including ':'. See also getPGOFuncName.
158 if (PGOFuncName.startswith(FileName))
159 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
160 return PGOFuncName;
161}
162
Xinliang David Lid1bab962015-12-12 17:28:03 +0000163// \p FuncName is the string used as profile lookup key for the function. A
164// symbol is created to hold the name. Return the legalized symbol name.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000165std::string getPGOFuncNameVarName(StringRef FuncName,
166 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000167 std::string VarName = getInstrProfNameVarPrefix();
168 VarName += FuncName;
169
170 if (!GlobalValue::isLocalLinkage(Linkage))
171 return VarName;
172
173 // Now fix up illegal chars in local VarName that may upset the assembler.
174 const char *InvalidChars = "-:<>\"'";
175 size_t found = VarName.find_first_of(InvalidChars);
176 while (found != std::string::npos) {
177 VarName[found] = '_';
178 found = VarName.find_first_of(InvalidChars, found + 1);
179 }
180 return VarName;
181}
182
Xinliang David Li441959d2015-11-09 00:01:22 +0000183GlobalVariable *createPGOFuncNameVar(Module &M,
184 GlobalValue::LinkageTypes Linkage,
Xinliang David Li897d2922016-03-16 22:13:41 +0000185 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000186
187 // We generally want to match the function's linkage, but available_externally
188 // and extern_weak both have the wrong semantics, and anything that doesn't
189 // need to link across compilation units doesn't need to be visible at all.
190 if (Linkage == GlobalValue::ExternalWeakLinkage)
191 Linkage = GlobalValue::LinkOnceAnyLinkage;
192 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
193 Linkage = GlobalValue::LinkOnceODRLinkage;
194 else if (Linkage == GlobalValue::InternalLinkage ||
195 Linkage == GlobalValue::ExternalLinkage)
196 Linkage = GlobalValue::PrivateLinkage;
197
Xinliang David Li897d2922016-03-16 22:13:41 +0000198 auto *Value =
199 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000200 auto FuncNameVar =
201 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000202 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000203
204 // Hide the symbol so that we correctly get a copy for each executable.
205 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
206 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
207
208 return FuncNameVar;
209}
210
Xinliang David Li897d2922016-03-16 22:13:41 +0000211GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
212 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000213}
Xinliang David Liee415892015-11-10 00:24:45 +0000214
Rong Xub5341662016-03-30 18:37:52 +0000215void InstrProfSymtab::create(Module &M, bool InLTO) {
216 for (Function &F : M) {
217 // Function may not have a name: like using asm("") to overwrite the name.
218 // Ignore in this case.
219 if (!F.hasName())
220 continue;
221 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
222 addFuncName(PGOFuncName);
Rong Xud5a57b52016-03-31 17:39:33 +0000223 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
Rong Xub5341662016-03-30 18:37:52 +0000224 }
Xinliang David Li59411db2016-01-20 01:26:34 +0000225
226 finalizeSymtab();
227}
228
Vedant Kumar9152fd12016-05-19 03:54:45 +0000229Error collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
230 bool doCompression, std::string &Result) {
Vedant Kumar86705ba2016-03-28 21:06:42 +0000231 assert(NameStrs.size() && "No name data to emit");
232
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000233 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000234 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000235 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
236
237 assert(StringRef(UncompressedNameStrings)
238 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
239 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000240
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000241 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
242 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000243
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000244 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000245 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000246 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000247 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
248 unsigned HeaderLen = P - &Header[0];
249 Result.append(HeaderStr, HeaderLen);
250 Result += InputStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000251 return Error::success();
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000252 };
253
Vedant Kumar9152fd12016-05-19 03:54:45 +0000254 if (!doCompression) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000255 return WriteStringToResult(0, UncompressedNameStrings);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000256 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000257
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000258 SmallString<128> CompressedNameStrings;
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000259 zlib::Status Success =
260 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
261 zlib::BestSizeCompression);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000262
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000263 if (Success != zlib::StatusOK)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000264 return make_error<InstrProfError>(instrprof_error::compress_failed);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000265
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000266 return WriteStringToResult(CompressedNameStrings.size(),
267 CompressedNameStrings);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000268}
269
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000270StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000271 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
272 StringRef NameStr =
273 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
274 return NameStr;
275}
276
Vedant Kumar9152fd12016-05-19 03:54:45 +0000277Error collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
278 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000279 std::vector<std::string> NameStrs;
280 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000281 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000282 }
Xinliang David Li73163752016-01-26 23:13:00 +0000283 return collectPGOFuncNameStrings(
284 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000285}
286
Vedant Kumar9152fd12016-05-19 03:54:45 +0000287Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000288 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
289 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
290 NameStrings.size());
291 while (P < EndP) {
292 uint32_t N;
293 uint64_t UncompressedSize = decodeULEB128(P, &N);
294 P += N;
295 uint64_t CompressedSize = decodeULEB128(P, &N);
296 P += N;
297 bool isCompressed = (CompressedSize != 0);
298 SmallString<128> UncompressedNameStrings;
299 StringRef NameStrings;
300 if (isCompressed) {
301 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
302 CompressedSize);
303 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
304 UncompressedSize) != zlib::StatusOK)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000305 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000306 P += CompressedSize;
307 NameStrings = StringRef(UncompressedNameStrings.data(),
308 UncompressedNameStrings.size());
309 } else {
310 NameStrings =
311 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
312 P += UncompressedSize;
313 }
314 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000315 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000316 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000317 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000318 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000319
320 while (P < EndP && *P == 0)
321 P++;
322 }
323 Symtab.finalizeSymtab();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000324 return Error::success();
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000325}
326
Vedant Kumar42369db2016-05-11 19:42:19 +0000327void InstrProfValueSiteRecord::merge(SoftInstrProfErrors &SIPE,
328 InstrProfValueSiteRecord &Input,
329 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000330 this->sortByTargetValues();
331 Input.sortByTargetValues();
332 auto I = ValueData.begin();
333 auto IE = ValueData.end();
Xinliang David Li5c24da52015-12-20 05:15:45 +0000334 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
335 ++J) {
336 while (I != IE && I->Value < J->Value)
337 ++I;
338 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000339 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000340 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000341 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000342 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000343 ++I;
344 continue;
345 }
346 ValueData.insert(I, *J);
347 }
Xinliang David Li5c24da52015-12-20 05:15:45 +0000348}
349
Vedant Kumar42369db2016-05-11 19:42:19 +0000350void InstrProfValueSiteRecord::scale(SoftInstrProfErrors &SIPE,
351 uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000352 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
353 bool Overflowed;
354 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
355 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000356 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000357 }
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000358}
359
Xinliang David Li020f22d2015-12-18 23:06:37 +0000360// Merge Value Profile data from Src record to this record for ValueKind.
361// Scale merged value counts by \p Weight.
Vedant Kumar42369db2016-05-11 19:42:19 +0000362void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
363 InstrProfRecord &Src,
364 uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000365 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
366 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
Vedant Kumar42369db2016-05-11 19:42:19 +0000367 if (ThisNumValueSites != OtherNumValueSites) {
368 SIPE.addError(instrprof_error::value_site_count_mismatch);
369 return;
370 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000371 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
372 getValueSitesForKind(ValueKind);
373 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
374 Src.getValueSitesForKind(ValueKind);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000375 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000376 ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000377}
378
Vedant Kumar42369db2016-05-11 19:42:19 +0000379void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000380 // If the number of counters doesn't match we either have bad data
381 // or a hash collision.
Vedant Kumar42369db2016-05-11 19:42:19 +0000382 if (Counts.size() != Other.Counts.size()) {
383 SIPE.addError(instrprof_error::count_mismatch);
384 return;
385 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000386
387 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
388 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000389 Counts[I] =
390 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000391 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000392 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000393 }
394
395 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000396 mergeValueProfData(Kind, Other, Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000397}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000398
Vedant Kumar42369db2016-05-11 19:42:19 +0000399void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000400 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
401 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
402 getValueSitesForKind(ValueKind);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000403 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000404 ThisSiteRecords[I].scale(SIPE, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000405}
406
Vedant Kumar42369db2016-05-11 19:42:19 +0000407void InstrProfRecord::scale(uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000408 for (auto &Count : this->Counts) {
409 bool Overflowed;
410 Count = SaturatingMultiply(Count, Weight, &Overflowed);
Vedant Kumar42369db2016-05-11 19:42:19 +0000411 if (Overflowed)
412 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000413 }
414 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000415 scaleValueProfData(Kind, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000416}
417
Xinliang David Li020f22d2015-12-18 23:06:37 +0000418// Map indirect call target name hash to name string.
419uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000420 ValueMapType *ValueMap) {
421 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000422 return Value;
423 switch (ValueKind) {
424 case IPVK_IndirectCallTarget: {
425 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000426 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
427 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000428 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Li8dd4ca82016-04-11 17:13:08 +0000429 // Raw function pointer collected by value profiler may be from
430 // external functions that are not instrumented. They won't have
431 // mapping data to be used by the deserializer. Force the value to
432 // be 0 in this case.
Xinliang David Li28464482016-04-10 03:32:02 +0000433 if (Result != ValueMap->end() && Result->first == Value)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000434 Value = (uint64_t)Result->second;
Xinliang David Li28464482016-04-10 03:32:02 +0000435 else
436 Value = 0;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000437 break;
438 }
439 }
440 return Value;
441}
442
Xinliang David Li020f22d2015-12-18 23:06:37 +0000443void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
444 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000445 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000446 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000447 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000448 }
449 std::vector<InstrProfValueSiteRecord> &ValueSites =
450 getValueSitesForKind(ValueKind);
451 if (N == 0)
Vedant Kumar6b22ba62016-05-11 16:03:02 +0000452 ValueSites.emplace_back();
Xinliang David Li020f22d2015-12-18 23:06:37 +0000453 else
454 ValueSites.emplace_back(VData, VData + N);
455}
456
Xinliang David Lib75544a2015-11-28 19:07:09 +0000457#define INSTR_PROF_COMMON_API_IMPL
458#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000459
Xinliang David Li020f22d2015-12-18 23:06:37 +0000460/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000461 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000462 * class. These C wrappers are used as adaptors so that C++ code can be
463 * invoked as callbacks.
464 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000465uint32_t getNumValueKindsInstrProf(const void *Record) {
466 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
467}
468
469uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
470 return reinterpret_cast<const InstrProfRecord *>(Record)
471 ->getNumValueSites(VKind);
472}
473
474uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
475 return reinterpret_cast<const InstrProfRecord *>(Record)
476 ->getNumValueData(VKind);
477}
478
479uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
480 uint32_t S) {
481 return reinterpret_cast<const InstrProfRecord *>(R)
482 ->getNumValueDataForSite(VK, S);
483}
484
485void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000486 uint32_t K, uint32_t S) {
487 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
Xinliang David Lie8092312015-11-25 19:13:00 +0000488}
489
Xinliang David Lif47cf552015-11-25 06:23:38 +0000490ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000491 ValueProfData *VD =
492 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
493 memset(VD, 0, TotalSizeInBytes);
494 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000495}
496
497static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000498 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000499 getNumValueKindsInstrProf,
500 getNumValueSitesInstrProf,
501 getNumValueDataInstrProf,
502 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000503 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000504 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000505 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000506
Xinliang David Lie8092312015-11-25 19:13:00 +0000507// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000508uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
509 InstrProfRecordClosure.Record = &Record;
510 return getValueProfDataSize(&InstrProfRecordClosure);
511}
512
Xinliang David Lie8092312015-11-25 19:13:00 +0000513// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000514std::unique_ptr<ValueProfData>
515ValueProfData::serializeFrom(const InstrProfRecord &Record) {
516 InstrProfRecordClosure.Record = &Record;
517
518 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000519 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000520 return VPD;
521}
522
Xinliang David Lie8092312015-11-25 19:13:00 +0000523void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
524 InstrProfRecord::ValueMapType *VMap) {
525 Record.reserveSites(Kind, NumValueSites);
526
527 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
528 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
529 uint8_t ValueDataCount = this->SiteCountArray[VSite];
530 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
531 ValueData += ValueDataCount;
532 }
533}
Xinliang David Lied966772015-11-25 23:31:18 +0000534
Xinliang David Lie8092312015-11-25 19:13:00 +0000535// For writing/serializing, Old is the host endianness, and New is
536// byte order intended on disk. For Reading/deserialization, Old
537// is the on-disk source endianness, and New is the host endianness.
538void ValueProfRecord::swapBytes(support::endianness Old,
539 support::endianness New) {
540 using namespace support;
541 if (Old == New)
542 return;
543
544 if (getHostEndianness() != Old) {
545 sys::swapByteOrder<uint32_t>(NumValueSites);
546 sys::swapByteOrder<uint32_t>(Kind);
547 }
548 uint32_t ND = getValueProfRecordNumValueData(this);
549 InstrProfValueData *VD = getValueProfRecordValueData(this);
550
551 // No need to swap byte array: SiteCountArrray.
552 for (uint32_t I = 0; I < ND; I++) {
553 sys::swapByteOrder<uint64_t>(VD[I].Value);
554 sys::swapByteOrder<uint64_t>(VD[I].Count);
555 }
556 if (getHostEndianness() == Old) {
557 sys::swapByteOrder<uint32_t>(NumValueSites);
558 sys::swapByteOrder<uint32_t>(Kind);
559 }
560}
561
562void ValueProfData::deserializeTo(InstrProfRecord &Record,
563 InstrProfRecord::ValueMapType *VMap) {
564 if (NumValueKinds == 0)
565 return;
566
567 ValueProfRecord *VR = getFirstValueProfRecord(this);
568 for (uint32_t K = 0; K < NumValueKinds; K++) {
569 VR->deserializeTo(Record, VMap);
570 VR = getValueProfRecordNext(VR);
571 }
572}
573
574template <class T>
575static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
576 using namespace support;
577 if (Orig == little)
578 return endian::readNext<T, little, unaligned>(D);
579 else
580 return endian::readNext<T, big, unaligned>(D);
581}
582
583static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
584 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
585 ValueProfData());
586}
587
Vedant Kumar9152fd12016-05-19 03:54:45 +0000588Error ValueProfData::checkIntegrity() {
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000589 if (NumValueKinds > IPVK_Last + 1)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000590 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000591 // Total size needs to be mulltiple of quadword size.
592 if (TotalSize % sizeof(uint64_t))
Vedant Kumar9152fd12016-05-19 03:54:45 +0000593 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000594
595 ValueProfRecord *VR = getFirstValueProfRecord(this);
596 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
597 if (VR->Kind > IPVK_Last)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000598 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000599 VR = getValueProfRecordNext(VR);
600 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000601 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000602 }
Vedant Kumar9152fd12016-05-19 03:54:45 +0000603 return Error::success();
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000604}
605
Vedant Kumar9152fd12016-05-19 03:54:45 +0000606Expected<std::unique_ptr<ValueProfData>>
Xinliang David Liee415892015-11-10 00:24:45 +0000607ValueProfData::getValueProfData(const unsigned char *D,
608 const unsigned char *const BufferEnd,
609 support::endianness Endianness) {
610 using namespace support;
611 if (D + sizeof(ValueProfData) > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000612 return make_error<InstrProfError>(instrprof_error::truncated);
Xinliang David Liee415892015-11-10 00:24:45 +0000613
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000614 const unsigned char *Header = D;
615 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000616 if (D + TotalSize > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000617 return make_error<InstrProfError>(instrprof_error::too_large);
Xinliang David Liee415892015-11-10 00:24:45 +0000618
Xinliang David Lif47cf552015-11-25 06:23:38 +0000619 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000620 memcpy(VPD.get(), D, TotalSize);
621 // Byte swap.
622 VPD->swapBytesToHost(Endianness);
623
Vedant Kumar9152fd12016-05-19 03:54:45 +0000624 Error E = VPD->checkIntegrity();
625 if (E)
626 return std::move(E);
Xinliang David Liee415892015-11-10 00:24:45 +0000627
Xinliang David Liee415892015-11-10 00:24:45 +0000628 return std::move(VPD);
629}
630
631void ValueProfData::swapBytesToHost(support::endianness Endianness) {
632 using namespace support;
633 if (Endianness == getHostEndianness())
634 return;
635
636 sys::swapByteOrder<uint32_t>(TotalSize);
637 sys::swapByteOrder<uint32_t>(NumValueKinds);
638
Xinliang David Lif47cf552015-11-25 06:23:38 +0000639 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000640 for (uint32_t K = 0; K < NumValueKinds; K++) {
641 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000642 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000643 }
644}
645
646void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
647 using namespace support;
648 if (Endianness == getHostEndianness())
649 return;
650
Xinliang David Lif47cf552015-11-25 06:23:38 +0000651 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000652 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000653 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000654 VR->swapBytes(getHostEndianness(), Endianness);
655 VR = NVR;
656 }
657 sys::swapByteOrder<uint32_t>(TotalSize);
658 sys::swapByteOrder<uint32_t>(NumValueKinds);
659}
Xinliang David Lie8092312015-11-25 19:13:00 +0000660
Xinliang David Li402477d2016-02-04 19:11:43 +0000661void annotateValueSite(Module &M, Instruction &Inst,
662 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000663 InstrProfValueKind ValueKind, uint32_t SiteIdx,
664 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000665 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
Betul Buyukkurt4f1e8c92016-04-14 16:25:45 +0000666 if (!NV)
667 return;
Xinliang David Li402477d2016-02-04 19:11:43 +0000668
669 uint64_t Sum = 0;
670 std::unique_ptr<InstrProfValueData[]> VD =
671 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
672
Rong Xu311ada12016-03-30 16:56:31 +0000673 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
674 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000675}
676
677void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000678 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000679 uint64_t Sum, InstrProfValueKind ValueKind,
680 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000681 LLVMContext &Ctx = M.getContext();
682 MDBuilder MDHelper(Ctx);
683 SmallVector<Metadata *, 3> Vals;
684 // Tag
685 Vals.push_back(MDHelper.createString("VP"));
686 // Value Kind
687 Vals.push_back(MDHelper.createConstant(
688 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
689 // Total Count
690 Vals.push_back(
691 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
692
693 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000694 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000695 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000696 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000697 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000698 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000699 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000700 if (--MDCount == 0)
701 break;
702 }
703 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
704}
705
706bool getValueProfDataFromInst(const Instruction &Inst,
707 InstrProfValueKind ValueKind,
708 uint32_t MaxNumValueData,
709 InstrProfValueData ValueData[],
710 uint32_t &ActualNumValueData, uint64_t &TotalC) {
711 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
712 if (!MD)
713 return false;
714
715 unsigned NOps = MD->getNumOperands();
716
717 if (NOps < 5)
718 return false;
719
720 // Operand 0 is a string tag "VP":
721 MDString *Tag = cast<MDString>(MD->getOperand(0));
722 if (!Tag)
723 return false;
724
725 if (!Tag->getString().equals("VP"))
726 return false;
727
728 // Now check kind:
729 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
730 if (!KindInt)
731 return false;
732 if (KindInt->getZExtValue() != ValueKind)
733 return false;
734
735 // Get total count
736 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
737 if (!TotalCInt)
738 return false;
739 TotalC = TotalCInt->getZExtValue();
740
741 ActualNumValueData = 0;
742
743 for (unsigned I = 3; I < NOps; I += 2) {
744 if (ActualNumValueData >= MaxNumValueData)
745 break;
746 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
747 ConstantInt *Count =
748 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
749 if (!Value || !Count)
750 return false;
751 ValueData[ActualNumValueData].Value = Value->getZExtValue();
752 ValueData[ActualNumValueData].Count = Count->getZExtValue();
753 ActualNumValueData++;
754 }
755 return true;
756}
Rong Xu8e8fe852016-04-01 16:43:30 +0000757
Rong Xu92c2eae2016-04-01 20:15:04 +0000758MDNode *getPGOFuncNameMetadata(const Function &F) {
759 return F.getMetadata(getPGOFuncNameMetadataName());
760}
761
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000762void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
Rong Xuf8f051c2016-04-22 21:00:17 +0000763 // Only for internal linkage functions.
764 if (PGOFuncName == F.getName())
765 return;
766 // Don't create duplicated meta-data.
767 if (getPGOFuncNameMetadata(F))
Rong Xu8e8fe852016-04-01 16:43:30 +0000768 return;
Rong Xu8e8fe852016-04-01 16:43:30 +0000769 LLVMContext &C = F.getContext();
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000770 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
Rong Xu8e8fe852016-04-01 16:43:30 +0000771 F.setMetadata(getPGOFuncNameMetadataName(), N);
772}
773
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000774} // end namespace llvm