blob: 6962f82a5ef5ca4d58454061a7ce8044e194952a [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"
Xinliang David Li9eb472b2016-07-12 17:14:51 +000026#include "llvm/Support/Path.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000027
28using namespace llvm;
29
Xinliang David Li9eb472b2016-07-12 17:14:51 +000030static cl::opt<bool> StaticFuncFullModulePrefix(
31 "static-func-full-module-prefix", cl::init(false),
32 cl::desc("Use full module build paths in the profile counter names for "
33 "static functions."));
34
Justin Bognerf8d79192014-03-21 17:24:48 +000035namespace {
Vedant Kumar9152fd12016-05-19 03:54:45 +000036std::string getInstrProfErrString(instrprof_error Err) {
37 switch (Err) {
38 case instrprof_error::success:
39 return "Success";
40 case instrprof_error::eof:
41 return "End of File";
42 case instrprof_error::unrecognized_format:
43 return "Unrecognized instrumentation profile encoding format";
44 case instrprof_error::bad_magic:
45 return "Invalid instrumentation profile data (bad magic)";
46 case instrprof_error::bad_header:
47 return "Invalid instrumentation profile data (file header is corrupt)";
48 case instrprof_error::unsupported_version:
49 return "Unsupported instrumentation profile format version";
50 case instrprof_error::unsupported_hash_type:
51 return "Unsupported instrumentation profile hash type";
52 case instrprof_error::too_large:
53 return "Too much profile data";
54 case instrprof_error::truncated:
55 return "Truncated profile data";
56 case instrprof_error::malformed:
57 return "Malformed instrumentation profile data";
58 case instrprof_error::unknown_function:
59 return "No profile data available for function";
60 case instrprof_error::hash_mismatch:
61 return "Function control flow change detected (hash mismatch)";
62 case instrprof_error::count_mismatch:
63 return "Function basic block count change detected (counter mismatch)";
64 case instrprof_error::counter_overflow:
65 return "Counter overflow";
66 case instrprof_error::value_site_count_mismatch:
67 return "Function value site count change detected (counter mismatch)";
68 case instrprof_error::compress_failed:
69 return "Failed to compress data (zlib)";
70 case instrprof_error::uncompress_failed:
71 return "Failed to uncompress data (zlib)";
72 }
73 llvm_unreachable("A value of instrprof_error has no message.");
74}
75
Peter Collingbourne4718f8b2016-05-24 20:13:46 +000076// FIXME: This class is only here to support the transition to llvm::Error. It
77// will be removed once this transition is complete. Clients should prefer to
78// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +000079class InstrProfErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +000080 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
Justin Bognerf8d79192014-03-21 17:24:48 +000081 std::string message(int IE) const override {
Vedant Kumar9152fd12016-05-19 03:54:45 +000082 return getInstrProfErrString(static_cast<instrprof_error>(IE));
Justin Bognerf8d79192014-03-21 17:24:48 +000083 }
Justin Bognerf8d79192014-03-21 17:24:48 +000084};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000085} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +000086
Chris Bieneman1efe8012014-09-19 23:19:24 +000087static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
88
Rafael Espindola25188c92014-06-12 01:45:43 +000089const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +000090 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +000091}
Xinliang David Li441959d2015-11-09 00:01:22 +000092
93namespace llvm {
94
Vedant Kumar42369db2016-05-11 19:42:19 +000095void SoftInstrProfErrors::addError(instrprof_error IE) {
96 if (IE == instrprof_error::success)
97 return;
98
99 if (FirstError == instrprof_error::success)
100 FirstError = IE;
101
102 switch (IE) {
103 case instrprof_error::hash_mismatch:
104 ++NumHashMismatches;
105 break;
106 case instrprof_error::count_mismatch:
107 ++NumCountMismatches;
108 break;
109 case instrprof_error::counter_overflow:
110 ++NumCounterOverflows;
111 break;
112 case instrprof_error::value_site_count_mismatch:
113 ++NumValueSiteCountMismatches;
114 break;
115 default:
116 llvm_unreachable("Not a soft error");
117 }
118}
119
Vedant Kumar9152fd12016-05-19 03:54:45 +0000120std::string InstrProfError::message() const {
121 return getInstrProfErrString(Err);
122}
123
124char InstrProfError::ID = 0;
125
Xinliang David Li441959d2015-11-09 00:01:22 +0000126std::string getPGOFuncName(StringRef RawFuncName,
127 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +0000128 StringRef FileName,
129 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +0000130 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000131}
132
Rong Xub5341662016-03-30 18:37:52 +0000133// Return the PGOFuncName. This function has some special handling when called
134// in LTO optimization. The following only applies when calling in LTO passes
135// (when \c InLTO is true): LTO's internalization privatizes many global linkage
136// symbols. This happens after value profile annotation, but those internal
137// linkage functions should not have a source prefix.
138// To differentiate compiler generated internal symbols from original ones,
139// PGOFuncName meta data are created and attached to the original internal
140// symbols in the value profile annotation step
141// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
142// data, its original linkage must be non-internal.
143std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000144 if (!InLTO) {
145 StringRef FileName = (StaticFuncFullModulePrefix
146 ? F.getParent()->getName()
147 : sys::path::filename(F.getParent()->getName()));
148 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
149 }
Rong Xub5341662016-03-30 18:37:52 +0000150
Rong Xu8e8fe852016-04-01 16:43:30 +0000151 // In LTO mode (when InLTO is true), first check if there is a meta data.
152 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
Rong Xub5341662016-03-30 18:37:52 +0000153 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
154 return S.str();
155 }
156
157 // If there is no meta data, the function must be a global before the value
158 // profile annotation pass. Its current linkage may be internal if it is
159 // internalized in LTO mode.
Rong Xu8e8fe852016-04-01 16:43:30 +0000160 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
Xinliang David Li441959d2015-11-09 00:01:22 +0000161}
162
Xinliang David Li4ec40142015-12-15 19:44:45 +0000163StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
164 if (FileName.empty())
Vedant Kumar43a85652016-03-28 15:49:08 +0000165 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +0000166 // Drop the file name including ':'. See also getPGOFuncName.
167 if (PGOFuncName.startswith(FileName))
168 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
169 return PGOFuncName;
170}
171
Xinliang David Lid1bab962015-12-12 17:28:03 +0000172// \p FuncName is the string used as profile lookup key for the function. A
173// symbol is created to hold the name. Return the legalized symbol name.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000174std::string getPGOFuncNameVarName(StringRef FuncName,
175 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000176 std::string VarName = getInstrProfNameVarPrefix();
177 VarName += FuncName;
178
179 if (!GlobalValue::isLocalLinkage(Linkage))
180 return VarName;
181
182 // Now fix up illegal chars in local VarName that may upset the assembler.
Xinliang David Lieeaf0bc2016-06-10 06:32:26 +0000183 const char *InvalidChars = "-:<>/\"'";
Xinliang David Lid1bab962015-12-12 17:28:03 +0000184 size_t found = VarName.find_first_of(InvalidChars);
185 while (found != std::string::npos) {
186 VarName[found] = '_';
187 found = VarName.find_first_of(InvalidChars, found + 1);
188 }
189 return VarName;
190}
191
Xinliang David Li441959d2015-11-09 00:01:22 +0000192GlobalVariable *createPGOFuncNameVar(Module &M,
193 GlobalValue::LinkageTypes Linkage,
Xinliang David Li897d2922016-03-16 22:13:41 +0000194 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000195
196 // We generally want to match the function's linkage, but available_externally
197 // and extern_weak both have the wrong semantics, and anything that doesn't
198 // need to link across compilation units doesn't need to be visible at all.
199 if (Linkage == GlobalValue::ExternalWeakLinkage)
200 Linkage = GlobalValue::LinkOnceAnyLinkage;
201 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
202 Linkage = GlobalValue::LinkOnceODRLinkage;
203 else if (Linkage == GlobalValue::InternalLinkage ||
204 Linkage == GlobalValue::ExternalLinkage)
205 Linkage = GlobalValue::PrivateLinkage;
206
Xinliang David Li897d2922016-03-16 22:13:41 +0000207 auto *Value =
208 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000209 auto FuncNameVar =
210 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000211 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000212
213 // Hide the symbol so that we correctly get a copy for each executable.
214 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
215 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
216
217 return FuncNameVar;
218}
219
Xinliang David Li897d2922016-03-16 22:13:41 +0000220GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
221 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000222}
Xinliang David Liee415892015-11-10 00:24:45 +0000223
Rong Xub5341662016-03-30 18:37:52 +0000224void InstrProfSymtab::create(Module &M, bool InLTO) {
225 for (Function &F : M) {
226 // Function may not have a name: like using asm("") to overwrite the name.
227 // Ignore in this case.
228 if (!F.hasName())
229 continue;
230 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
231 addFuncName(PGOFuncName);
Rong Xud5a57b52016-03-31 17:39:33 +0000232 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
Rong Xub5341662016-03-30 18:37:52 +0000233 }
Xinliang David Li59411db2016-01-20 01:26:34 +0000234
235 finalizeSymtab();
236}
237
Vedant Kumar9152fd12016-05-19 03:54:45 +0000238Error collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
239 bool doCompression, std::string &Result) {
Vedant Kumar86705ba2016-03-28 21:06:42 +0000240 assert(NameStrs.size() && "No name data to emit");
241
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000242 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000243 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000244 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
245
246 assert(StringRef(UncompressedNameStrings)
247 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
248 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000249
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000250 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
251 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000252
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000253 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000254 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000255 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000256 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
257 unsigned HeaderLen = P - &Header[0];
258 Result.append(HeaderStr, HeaderLen);
259 Result += InputStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000260 return Error::success();
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000261 };
262
Vedant Kumar9152fd12016-05-19 03:54:45 +0000263 if (!doCompression) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000264 return WriteStringToResult(0, UncompressedNameStrings);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000265 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000266
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000267 SmallString<128> CompressedNameStrings;
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000268 zlib::Status Success =
269 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
270 zlib::BestSizeCompression);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000271
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000272 if (Success != zlib::StatusOK)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000273 return make_error<InstrProfError>(instrprof_error::compress_failed);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000274
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000275 return WriteStringToResult(CompressedNameStrings.size(),
276 CompressedNameStrings);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000277}
278
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000279StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000280 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
281 StringRef NameStr =
282 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
283 return NameStr;
284}
285
Vedant Kumar9152fd12016-05-19 03:54:45 +0000286Error collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
287 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000288 std::vector<std::string> NameStrs;
289 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000290 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000291 }
Xinliang David Li73163752016-01-26 23:13:00 +0000292 return collectPGOFuncNameStrings(
293 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000294}
295
Vedant Kumar9152fd12016-05-19 03:54:45 +0000296Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000297 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
298 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
299 NameStrings.size());
300 while (P < EndP) {
301 uint32_t N;
302 uint64_t UncompressedSize = decodeULEB128(P, &N);
303 P += N;
304 uint64_t CompressedSize = decodeULEB128(P, &N);
305 P += N;
306 bool isCompressed = (CompressedSize != 0);
307 SmallString<128> UncompressedNameStrings;
308 StringRef NameStrings;
309 if (isCompressed) {
310 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
311 CompressedSize);
312 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
313 UncompressedSize) != zlib::StatusOK)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000314 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000315 P += CompressedSize;
316 NameStrings = StringRef(UncompressedNameStrings.data(),
317 UncompressedNameStrings.size());
318 } else {
319 NameStrings =
320 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
321 P += UncompressedSize;
322 }
323 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000324 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000325 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000326 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000327 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000328
329 while (P < EndP && *P == 0)
330 P++;
331 }
332 Symtab.finalizeSymtab();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000333 return Error::success();
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000334}
335
Vedant Kumar42369db2016-05-11 19:42:19 +0000336void InstrProfValueSiteRecord::merge(SoftInstrProfErrors &SIPE,
337 InstrProfValueSiteRecord &Input,
338 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000339 this->sortByTargetValues();
340 Input.sortByTargetValues();
341 auto I = ValueData.begin();
342 auto IE = ValueData.end();
Xinliang David Li5c24da52015-12-20 05:15:45 +0000343 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
344 ++J) {
345 while (I != IE && I->Value < J->Value)
346 ++I;
347 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000348 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000349 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000350 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000351 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000352 ++I;
353 continue;
354 }
355 ValueData.insert(I, *J);
356 }
Xinliang David Li5c24da52015-12-20 05:15:45 +0000357}
358
Vedant Kumar42369db2016-05-11 19:42:19 +0000359void InstrProfValueSiteRecord::scale(SoftInstrProfErrors &SIPE,
360 uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000361 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
362 bool Overflowed;
363 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
364 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000365 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000366 }
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000367}
368
Xinliang David Li020f22d2015-12-18 23:06:37 +0000369// Merge Value Profile data from Src record to this record for ValueKind.
370// Scale merged value counts by \p Weight.
Vedant Kumar42369db2016-05-11 19:42:19 +0000371void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
372 InstrProfRecord &Src,
373 uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000374 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
375 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
Vedant Kumar42369db2016-05-11 19:42:19 +0000376 if (ThisNumValueSites != OtherNumValueSites) {
377 SIPE.addError(instrprof_error::value_site_count_mismatch);
378 return;
379 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000380 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
381 getValueSitesForKind(ValueKind);
382 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
383 Src.getValueSitesForKind(ValueKind);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000384 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000385 ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000386}
387
Vedant Kumar42369db2016-05-11 19:42:19 +0000388void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000389 // If the number of counters doesn't match we either have bad data
390 // or a hash collision.
Vedant Kumar42369db2016-05-11 19:42:19 +0000391 if (Counts.size() != Other.Counts.size()) {
392 SIPE.addError(instrprof_error::count_mismatch);
393 return;
394 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000395
396 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
397 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000398 Counts[I] =
399 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000400 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000401 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000402 }
403
404 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000405 mergeValueProfData(Kind, Other, Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000406}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000407
Vedant Kumar42369db2016-05-11 19:42:19 +0000408void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000409 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
410 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
411 getValueSitesForKind(ValueKind);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000412 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000413 ThisSiteRecords[I].scale(SIPE, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000414}
415
Vedant Kumar42369db2016-05-11 19:42:19 +0000416void InstrProfRecord::scale(uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000417 for (auto &Count : this->Counts) {
418 bool Overflowed;
419 Count = SaturatingMultiply(Count, Weight, &Overflowed);
Vedant Kumar42369db2016-05-11 19:42:19 +0000420 if (Overflowed)
421 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000422 }
423 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000424 scaleValueProfData(Kind, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000425}
426
Xinliang David Li020f22d2015-12-18 23:06:37 +0000427// Map indirect call target name hash to name string.
428uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000429 ValueMapType *ValueMap) {
430 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000431 return Value;
432 switch (ValueKind) {
433 case IPVK_IndirectCallTarget: {
434 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000435 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
436 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000437 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Li8dd4ca82016-04-11 17:13:08 +0000438 // Raw function pointer collected by value profiler may be from
439 // external functions that are not instrumented. They won't have
440 // mapping data to be used by the deserializer. Force the value to
441 // be 0 in this case.
Xinliang David Li28464482016-04-10 03:32:02 +0000442 if (Result != ValueMap->end() && Result->first == Value)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000443 Value = (uint64_t)Result->second;
Xinliang David Li28464482016-04-10 03:32:02 +0000444 else
445 Value = 0;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000446 break;
447 }
448 }
449 return Value;
450}
451
Xinliang David Li020f22d2015-12-18 23:06:37 +0000452void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
453 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000454 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000455 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000456 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000457 }
458 std::vector<InstrProfValueSiteRecord> &ValueSites =
459 getValueSitesForKind(ValueKind);
460 if (N == 0)
Vedant Kumar6b22ba62016-05-11 16:03:02 +0000461 ValueSites.emplace_back();
Xinliang David Li020f22d2015-12-18 23:06:37 +0000462 else
463 ValueSites.emplace_back(VData, VData + N);
464}
465
Xinliang David Lib75544a2015-11-28 19:07:09 +0000466#define INSTR_PROF_COMMON_API_IMPL
467#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000468
Xinliang David Li020f22d2015-12-18 23:06:37 +0000469/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000470 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000471 * class. These C wrappers are used as adaptors so that C++ code can be
472 * invoked as callbacks.
473 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000474uint32_t getNumValueKindsInstrProf(const void *Record) {
475 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
476}
477
478uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
479 return reinterpret_cast<const InstrProfRecord *>(Record)
480 ->getNumValueSites(VKind);
481}
482
483uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
484 return reinterpret_cast<const InstrProfRecord *>(Record)
485 ->getNumValueData(VKind);
486}
487
488uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
489 uint32_t S) {
490 return reinterpret_cast<const InstrProfRecord *>(R)
491 ->getNumValueDataForSite(VK, S);
492}
493
494void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000495 uint32_t K, uint32_t S) {
496 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
Xinliang David Lie8092312015-11-25 19:13:00 +0000497}
498
Xinliang David Lif47cf552015-11-25 06:23:38 +0000499ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000500 ValueProfData *VD =
501 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
502 memset(VD, 0, TotalSizeInBytes);
503 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000504}
505
506static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000507 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000508 getNumValueKindsInstrProf,
509 getNumValueSitesInstrProf,
510 getNumValueDataInstrProf,
511 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000512 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000513 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000514 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000515
Xinliang David Lie8092312015-11-25 19:13:00 +0000516// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000517uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
518 InstrProfRecordClosure.Record = &Record;
519 return getValueProfDataSize(&InstrProfRecordClosure);
520}
521
Xinliang David Lie8092312015-11-25 19:13:00 +0000522// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000523std::unique_ptr<ValueProfData>
524ValueProfData::serializeFrom(const InstrProfRecord &Record) {
525 InstrProfRecordClosure.Record = &Record;
526
527 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000528 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000529 return VPD;
530}
531
Xinliang David Lie8092312015-11-25 19:13:00 +0000532void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
533 InstrProfRecord::ValueMapType *VMap) {
534 Record.reserveSites(Kind, NumValueSites);
535
536 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
537 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
538 uint8_t ValueDataCount = this->SiteCountArray[VSite];
539 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
540 ValueData += ValueDataCount;
541 }
542}
Xinliang David Lied966772015-11-25 23:31:18 +0000543
Xinliang David Lie8092312015-11-25 19:13:00 +0000544// For writing/serializing, Old is the host endianness, and New is
545// byte order intended on disk. For Reading/deserialization, Old
546// is the on-disk source endianness, and New is the host endianness.
547void ValueProfRecord::swapBytes(support::endianness Old,
548 support::endianness New) {
549 using namespace support;
550 if (Old == New)
551 return;
552
553 if (getHostEndianness() != Old) {
554 sys::swapByteOrder<uint32_t>(NumValueSites);
555 sys::swapByteOrder<uint32_t>(Kind);
556 }
557 uint32_t ND = getValueProfRecordNumValueData(this);
558 InstrProfValueData *VD = getValueProfRecordValueData(this);
559
560 // No need to swap byte array: SiteCountArrray.
561 for (uint32_t I = 0; I < ND; I++) {
562 sys::swapByteOrder<uint64_t>(VD[I].Value);
563 sys::swapByteOrder<uint64_t>(VD[I].Count);
564 }
565 if (getHostEndianness() == Old) {
566 sys::swapByteOrder<uint32_t>(NumValueSites);
567 sys::swapByteOrder<uint32_t>(Kind);
568 }
569}
570
571void ValueProfData::deserializeTo(InstrProfRecord &Record,
572 InstrProfRecord::ValueMapType *VMap) {
573 if (NumValueKinds == 0)
574 return;
575
576 ValueProfRecord *VR = getFirstValueProfRecord(this);
577 for (uint32_t K = 0; K < NumValueKinds; K++) {
578 VR->deserializeTo(Record, VMap);
579 VR = getValueProfRecordNext(VR);
580 }
581}
582
583template <class T>
584static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
585 using namespace support;
586 if (Orig == little)
587 return endian::readNext<T, little, unaligned>(D);
588 else
589 return endian::readNext<T, big, unaligned>(D);
590}
591
592static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
593 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
594 ValueProfData());
595}
596
Vedant Kumar9152fd12016-05-19 03:54:45 +0000597Error ValueProfData::checkIntegrity() {
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000598 if (NumValueKinds > IPVK_Last + 1)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000599 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000600 // Total size needs to be mulltiple of quadword size.
601 if (TotalSize % sizeof(uint64_t))
Vedant Kumar9152fd12016-05-19 03:54:45 +0000602 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000603
604 ValueProfRecord *VR = getFirstValueProfRecord(this);
605 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
606 if (VR->Kind > IPVK_Last)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000607 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000608 VR = getValueProfRecordNext(VR);
609 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000610 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000611 }
Vedant Kumar9152fd12016-05-19 03:54:45 +0000612 return Error::success();
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000613}
614
Vedant Kumar9152fd12016-05-19 03:54:45 +0000615Expected<std::unique_ptr<ValueProfData>>
Xinliang David Liee415892015-11-10 00:24:45 +0000616ValueProfData::getValueProfData(const unsigned char *D,
617 const unsigned char *const BufferEnd,
618 support::endianness Endianness) {
619 using namespace support;
620 if (D + sizeof(ValueProfData) > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000621 return make_error<InstrProfError>(instrprof_error::truncated);
Xinliang David Liee415892015-11-10 00:24:45 +0000622
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000623 const unsigned char *Header = D;
624 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000625 if (D + TotalSize > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000626 return make_error<InstrProfError>(instrprof_error::too_large);
Xinliang David Liee415892015-11-10 00:24:45 +0000627
Xinliang David Lif47cf552015-11-25 06:23:38 +0000628 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000629 memcpy(VPD.get(), D, TotalSize);
630 // Byte swap.
631 VPD->swapBytesToHost(Endianness);
632
Vedant Kumar9152fd12016-05-19 03:54:45 +0000633 Error E = VPD->checkIntegrity();
634 if (E)
635 return std::move(E);
Xinliang David Liee415892015-11-10 00:24:45 +0000636
Xinliang David Liee415892015-11-10 00:24:45 +0000637 return std::move(VPD);
638}
639
640void ValueProfData::swapBytesToHost(support::endianness Endianness) {
641 using namespace support;
642 if (Endianness == getHostEndianness())
643 return;
644
645 sys::swapByteOrder<uint32_t>(TotalSize);
646 sys::swapByteOrder<uint32_t>(NumValueKinds);
647
Xinliang David Lif47cf552015-11-25 06:23:38 +0000648 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000649 for (uint32_t K = 0; K < NumValueKinds; K++) {
650 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000651 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000652 }
653}
654
655void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
656 using namespace support;
657 if (Endianness == getHostEndianness())
658 return;
659
Xinliang David Lif47cf552015-11-25 06:23:38 +0000660 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000661 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000662 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000663 VR->swapBytes(getHostEndianness(), Endianness);
664 VR = NVR;
665 }
666 sys::swapByteOrder<uint32_t>(TotalSize);
667 sys::swapByteOrder<uint32_t>(NumValueKinds);
668}
Xinliang David Lie8092312015-11-25 19:13:00 +0000669
Xinliang David Li402477d2016-02-04 19:11:43 +0000670void annotateValueSite(Module &M, Instruction &Inst,
671 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000672 InstrProfValueKind ValueKind, uint32_t SiteIdx,
673 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000674 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
Betul Buyukkurt4f1e8c92016-04-14 16:25:45 +0000675 if (!NV)
676 return;
Xinliang David Li402477d2016-02-04 19:11:43 +0000677
678 uint64_t Sum = 0;
679 std::unique_ptr<InstrProfValueData[]> VD =
680 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
681
Rong Xu311ada12016-03-30 16:56:31 +0000682 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
683 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000684}
685
686void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000687 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000688 uint64_t Sum, InstrProfValueKind ValueKind,
689 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000690 LLVMContext &Ctx = M.getContext();
691 MDBuilder MDHelper(Ctx);
692 SmallVector<Metadata *, 3> Vals;
693 // Tag
694 Vals.push_back(MDHelper.createString("VP"));
695 // Value Kind
696 Vals.push_back(MDHelper.createConstant(
697 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
698 // Total Count
699 Vals.push_back(
700 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
701
702 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000703 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000704 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000705 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000706 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000707 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000708 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000709 if (--MDCount == 0)
710 break;
711 }
712 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
713}
714
715bool getValueProfDataFromInst(const Instruction &Inst,
716 InstrProfValueKind ValueKind,
717 uint32_t MaxNumValueData,
718 InstrProfValueData ValueData[],
719 uint32_t &ActualNumValueData, uint64_t &TotalC) {
720 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
721 if (!MD)
722 return false;
723
724 unsigned NOps = MD->getNumOperands();
725
726 if (NOps < 5)
727 return false;
728
729 // Operand 0 is a string tag "VP":
730 MDString *Tag = cast<MDString>(MD->getOperand(0));
731 if (!Tag)
732 return false;
733
734 if (!Tag->getString().equals("VP"))
735 return false;
736
737 // Now check kind:
738 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
739 if (!KindInt)
740 return false;
741 if (KindInt->getZExtValue() != ValueKind)
742 return false;
743
744 // Get total count
745 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
746 if (!TotalCInt)
747 return false;
748 TotalC = TotalCInt->getZExtValue();
749
750 ActualNumValueData = 0;
751
752 for (unsigned I = 3; I < NOps; I += 2) {
753 if (ActualNumValueData >= MaxNumValueData)
754 break;
755 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
756 ConstantInt *Count =
757 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
758 if (!Value || !Count)
759 return false;
760 ValueData[ActualNumValueData].Value = Value->getZExtValue();
761 ValueData[ActualNumValueData].Count = Count->getZExtValue();
762 ActualNumValueData++;
763 }
764 return true;
765}
Rong Xu8e8fe852016-04-01 16:43:30 +0000766
Rong Xu92c2eae2016-04-01 20:15:04 +0000767MDNode *getPGOFuncNameMetadata(const Function &F) {
768 return F.getMetadata(getPGOFuncNameMetadataName());
769}
770
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000771void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
Rong Xuf8f051c2016-04-22 21:00:17 +0000772 // Only for internal linkage functions.
773 if (PGOFuncName == F.getName())
774 return;
775 // Don't create duplicated meta-data.
776 if (getPGOFuncNameMetadata(F))
Rong Xu8e8fe852016-04-01 16:43:30 +0000777 return;
Rong Xu8e8fe852016-04-01 16:43:30 +0000778 LLVMContext &C = F.getContext();
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000779 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
Rong Xu8e8fe852016-04-01 16:43:30 +0000780 F.setMetadata(getPGOFuncNameMetadataName(), N);
781}
782
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000783} // end namespace llvm