blob: 7e84a2702bd4ea22ef2567859a2a4dfd4ab895d9 [file] [log] [blame]
Justin Bognerf8d79192014-03-21 17:24:48 +00001//=-- InstrProf.cpp - Instrumented profiling format support -----------------=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for clang's instrumentation based PGO and
11// coverage.
12//
13//===----------------------------------------------------------------------===//
14
Xinliang David Lie413f1a2015-12-31 07:57:16 +000015#include "llvm/ProfileData/InstrProf.h"
Xinliang David Li0c677872016-01-04 21:31:09 +000016#include "llvm/ADT/StringExtras.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000017#include "llvm/IR/Constants.h"
18#include "llvm/IR/Function.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000019#include "llvm/IR/GlobalVariable.h"
Xinliang David Li402477d2016-02-04 19:11:43 +000020#include "llvm/IR/MDBuilder.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000021#include "llvm/IR/Module.h"
22#include "llvm/Support/Compression.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000023#include "llvm/Support/ErrorHandling.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000024#include "llvm/Support/LEB128.h"
Chris Bieneman1efe8012014-09-19 23:19:24 +000025#include "llvm/Support/ManagedStatic.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000026
27using namespace llvm;
28
29namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +000030class InstrProfErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +000031 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
Justin Bognerf8d79192014-03-21 17:24:48 +000032 std::string message(int IE) const override {
Rafael Espindola92512e82014-06-03 05:12:33 +000033 instrprof_error E = static_cast<instrprof_error>(IE);
Justin Bognerf8d79192014-03-21 17:24:48 +000034 switch (E) {
35 case instrprof_error::success:
36 return "Success";
37 case instrprof_error::eof:
38 return "End of File";
Nathan Slingerland4f823662015-11-13 03:47:58 +000039 case instrprof_error::unrecognized_format:
40 return "Unrecognized instrumentation profile encoding format";
Justin Bognerf8d79192014-03-21 17:24:48 +000041 case instrprof_error::bad_magic:
Nathan Slingerland4f823662015-11-13 03:47:58 +000042 return "Invalid instrumentation profile data (bad magic)";
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +000043 case instrprof_error::bad_header:
Nathan Slingerland4f823662015-11-13 03:47:58 +000044 return "Invalid instrumentation profile data (file header is corrupt)";
Justin Bognerf8d79192014-03-21 17:24:48 +000045 case instrprof_error::unsupported_version:
Nathan Slingerland4f823662015-11-13 03:47:58 +000046 return "Unsupported instrumentation profile format version";
Justin Bognerb7aa2632014-04-18 21:48:40 +000047 case instrprof_error::unsupported_hash_type:
Nathan Slingerland4f823662015-11-13 03:47:58 +000048 return "Unsupported instrumentation profile hash type";
Justin Bognerf8d79192014-03-21 17:24:48 +000049 case instrprof_error::too_large:
50 return "Too much profile data";
51 case instrprof_error::truncated:
52 return "Truncated profile data";
53 case instrprof_error::malformed:
Nathan Slingerland4f823662015-11-13 03:47:58 +000054 return "Malformed instrumentation profile data";
Justin Bognerf8d79192014-03-21 17:24:48 +000055 case instrprof_error::unknown_function:
56 return "No profile data available for function";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000057 case instrprof_error::hash_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000058 return "Function control flow change detected (hash mismatch)";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000059 case instrprof_error::count_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000060 return "Function basic block count change detected (counter mismatch)";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000061 case instrprof_error::counter_overflow:
62 return "Counter overflow";
Justin Bogner9e9a0572015-09-29 22:13:58 +000063 case instrprof_error::value_site_count_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000064 return "Function value site count change detected (counter mismatch)";
Justin Bognerf8d79192014-03-21 17:24:48 +000065 }
66 llvm_unreachable("A value of instrprof_error has no message.");
67 }
Justin Bognerf8d79192014-03-21 17:24:48 +000068};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000069} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +000070
Chris Bieneman1efe8012014-09-19 23:19:24 +000071static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
72
Rafael Espindola25188c92014-06-12 01:45:43 +000073const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +000074 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +000075}
Xinliang David Li441959d2015-11-09 00:01:22 +000076
77namespace llvm {
78
79std::string getPGOFuncName(StringRef RawFuncName,
80 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +000081 StringRef FileName,
82 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +000083 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +000084}
85
Rong Xub5341662016-03-30 18:37:52 +000086// Return the PGOFuncName. This function has some special handling when called
87// in LTO optimization. The following only applies when calling in LTO passes
88// (when \c InLTO is true): LTO's internalization privatizes many global linkage
89// symbols. This happens after value profile annotation, but those internal
90// linkage functions should not have a source prefix.
91// To differentiate compiler generated internal symbols from original ones,
92// PGOFuncName meta data are created and attached to the original internal
93// symbols in the value profile annotation step
94// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
95// data, its original linkage must be non-internal.
96std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
97 if (!InLTO)
98 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
99 Version);
100
Rong Xu8e8fe852016-04-01 16:43:30 +0000101 // In LTO mode (when InLTO is true), first check if there is a meta data.
102 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
Rong Xub5341662016-03-30 18:37:52 +0000103 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
104 return S.str();
105 }
106
107 // If there is no meta data, the function must be a global before the value
108 // profile annotation pass. Its current linkage may be internal if it is
109 // internalized in LTO mode.
Rong Xu8e8fe852016-04-01 16:43:30 +0000110 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
Xinliang David Li441959d2015-11-09 00:01:22 +0000111}
112
Xinliang David Li4ec40142015-12-15 19:44:45 +0000113StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
114 if (FileName.empty())
Vedant Kumar43a85652016-03-28 15:49:08 +0000115 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +0000116 // Drop the file name including ':'. See also getPGOFuncName.
117 if (PGOFuncName.startswith(FileName))
118 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
119 return PGOFuncName;
120}
121
Xinliang David Lid1bab962015-12-12 17:28:03 +0000122// \p FuncName is the string used as profile lookup key for the function. A
123// symbol is created to hold the name. Return the legalized symbol name.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000124std::string getPGOFuncNameVarName(StringRef FuncName,
125 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000126 std::string VarName = getInstrProfNameVarPrefix();
127 VarName += FuncName;
128
129 if (!GlobalValue::isLocalLinkage(Linkage))
130 return VarName;
131
132 // Now fix up illegal chars in local VarName that may upset the assembler.
133 const char *InvalidChars = "-:<>\"'";
134 size_t found = VarName.find_first_of(InvalidChars);
135 while (found != std::string::npos) {
136 VarName[found] = '_';
137 found = VarName.find_first_of(InvalidChars, found + 1);
138 }
139 return VarName;
140}
141
Xinliang David Li441959d2015-11-09 00:01:22 +0000142GlobalVariable *createPGOFuncNameVar(Module &M,
143 GlobalValue::LinkageTypes Linkage,
Xinliang David Li897d2922016-03-16 22:13:41 +0000144 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000145
146 // We generally want to match the function's linkage, but available_externally
147 // and extern_weak both have the wrong semantics, and anything that doesn't
148 // need to link across compilation units doesn't need to be visible at all.
149 if (Linkage == GlobalValue::ExternalWeakLinkage)
150 Linkage = GlobalValue::LinkOnceAnyLinkage;
151 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
152 Linkage = GlobalValue::LinkOnceODRLinkage;
153 else if (Linkage == GlobalValue::InternalLinkage ||
154 Linkage == GlobalValue::ExternalLinkage)
155 Linkage = GlobalValue::PrivateLinkage;
156
Xinliang David Li897d2922016-03-16 22:13:41 +0000157 auto *Value =
158 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000159 auto FuncNameVar =
160 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000161 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000162
163 // Hide the symbol so that we correctly get a copy for each executable.
164 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
165 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
166
167 return FuncNameVar;
168}
169
Xinliang David Li897d2922016-03-16 22:13:41 +0000170GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
171 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000172}
Xinliang David Liee415892015-11-10 00:24:45 +0000173
Rong Xub5341662016-03-30 18:37:52 +0000174void InstrProfSymtab::create(Module &M, bool InLTO) {
175 for (Function &F : M) {
176 // Function may not have a name: like using asm("") to overwrite the name.
177 // Ignore in this case.
178 if (!F.hasName())
179 continue;
180 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
181 addFuncName(PGOFuncName);
Rong Xud5a57b52016-03-31 17:39:33 +0000182 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
Rong Xub5341662016-03-30 18:37:52 +0000183 }
Xinliang David Li59411db2016-01-20 01:26:34 +0000184
185 finalizeSymtab();
186}
187
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000188int collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
189 bool doCompression, std::string &Result) {
Vedant Kumar86705ba2016-03-28 21:06:42 +0000190 assert(NameStrs.size() && "No name data to emit");
191
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000192 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000193 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000194 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
195
196 assert(StringRef(UncompressedNameStrings)
197 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
198 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000199
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000200 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
201 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000202
203 auto WriteStringToResult = [&](size_t CompressedLen,
204 const std::string &InputStr) {
205 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000206 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000207 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
208 unsigned HeaderLen = P - &Header[0];
209 Result.append(HeaderStr, HeaderLen);
210 Result += InputStr;
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000211 return 0;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000212 };
213
214 if (!doCompression)
215 return WriteStringToResult(0, UncompressedNameStrings);
216
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000217 SmallVector<char, 128> CompressedNameStrings;
218 zlib::Status Success =
219 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
220 zlib::BestSizeCompression);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000221
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000222 if (Success != zlib::StatusOK)
223 return 1;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000224
225 return WriteStringToResult(
226 CompressedNameStrings.size(),
227 std::string(CompressedNameStrings.data(), CompressedNameStrings.size()));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000228}
229
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000230StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000231 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
232 StringRef NameStr =
233 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
234 return NameStr;
235}
236
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000237int collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
Xinliang David Li73163752016-01-26 23:13:00 +0000238 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000239 std::vector<std::string> NameStrs;
240 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000241 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000242 }
Xinliang David Li73163752016-01-26 23:13:00 +0000243 return collectPGOFuncNameStrings(
244 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000245}
246
247int readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
248 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
249 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
250 NameStrings.size());
251 while (P < EndP) {
252 uint32_t N;
253 uint64_t UncompressedSize = decodeULEB128(P, &N);
254 P += N;
255 uint64_t CompressedSize = decodeULEB128(P, &N);
256 P += N;
257 bool isCompressed = (CompressedSize != 0);
258 SmallString<128> UncompressedNameStrings;
259 StringRef NameStrings;
260 if (isCompressed) {
261 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
262 CompressedSize);
263 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
264 UncompressedSize) != zlib::StatusOK)
265 return 1;
266 P += CompressedSize;
267 NameStrings = StringRef(UncompressedNameStrings.data(),
268 UncompressedNameStrings.size());
269 } else {
270 NameStrings =
271 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
272 P += UncompressedSize;
273 }
274 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000275 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000276 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000277 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000278 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000279
280 while (P < EndP && *P == 0)
281 P++;
282 }
283 Symtab.finalizeSymtab();
284 return 0;
285}
286
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000287instrprof_error InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
288 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000289 this->sortByTargetValues();
290 Input.sortByTargetValues();
291 auto I = ValueData.begin();
292 auto IE = ValueData.end();
293 instrprof_error Result = instrprof_error::success;
294 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
295 ++J) {
296 while (I != IE && I->Value < J->Value)
297 ++I;
298 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000299 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000300 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000301 if (Overflowed)
302 Result = instrprof_error::counter_overflow;
303 ++I;
304 continue;
305 }
306 ValueData.insert(I, *J);
307 }
308 return Result;
309}
310
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000311instrprof_error InstrProfValueSiteRecord::scale(uint64_t Weight) {
312 instrprof_error Result = instrprof_error::success;
313 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
314 bool Overflowed;
315 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
316 if (Overflowed)
317 Result = instrprof_error::counter_overflow;
318 }
319 return Result;
320}
321
Xinliang David Li020f22d2015-12-18 23:06:37 +0000322// Merge Value Profile data from Src record to this record for ValueKind.
323// Scale merged value counts by \p Weight.
324instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
325 InstrProfRecord &Src,
326 uint64_t Weight) {
327 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
328 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
329 if (ThisNumValueSites != OtherNumValueSites)
330 return instrprof_error::value_site_count_mismatch;
331 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
332 getValueSitesForKind(ValueKind);
333 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
334 Src.getValueSitesForKind(ValueKind);
335 instrprof_error Result = instrprof_error::success;
336 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000337 MergeResult(Result, ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight));
Xinliang David Li020f22d2015-12-18 23:06:37 +0000338 return Result;
339}
340
341instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
342 uint64_t Weight) {
343 // If the number of counters doesn't match we either have bad data
344 // or a hash collision.
345 if (Counts.size() != Other.Counts.size())
346 return instrprof_error::count_mismatch;
347
348 instrprof_error Result = instrprof_error::success;
349
350 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
351 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000352 Counts[I] =
353 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000354 if (Overflowed)
355 Result = instrprof_error::counter_overflow;
356 }
357
358 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
359 MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
360
361 return Result;
362}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000363
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000364instrprof_error InstrProfRecord::scaleValueProfData(uint32_t ValueKind,
365 uint64_t Weight) {
366 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
367 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
368 getValueSitesForKind(ValueKind);
369 instrprof_error Result = instrprof_error::success;
370 for (uint32_t I = 0; I < ThisNumValueSites; I++)
371 MergeResult(Result, ThisSiteRecords[I].scale(Weight));
372 return Result;
373}
374
375instrprof_error InstrProfRecord::scale(uint64_t Weight) {
376 instrprof_error Result = instrprof_error::success;
377 for (auto &Count : this->Counts) {
378 bool Overflowed;
379 Count = SaturatingMultiply(Count, Weight, &Overflowed);
380 if (Overflowed && Result == instrprof_error::success) {
381 Result = instrprof_error::counter_overflow;
382 }
383 }
384 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
385 MergeResult(Result, scaleValueProfData(Kind, Weight));
386
387 return Result;
388}
389
Xinliang David Li020f22d2015-12-18 23:06:37 +0000390// Map indirect call target name hash to name string.
391uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000392 ValueMapType *ValueMap) {
393 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000394 return Value;
395 switch (ValueKind) {
396 case IPVK_IndirectCallTarget: {
397 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000398 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
399 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000400 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Li8dd4ca82016-04-11 17:13:08 +0000401 // Raw function pointer collected by value profiler may be from
402 // external functions that are not instrumented. They won't have
403 // mapping data to be used by the deserializer. Force the value to
404 // be 0 in this case.
Xinliang David Li28464482016-04-10 03:32:02 +0000405 if (Result != ValueMap->end() && Result->first == Value)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000406 Value = (uint64_t)Result->second;
Xinliang David Li28464482016-04-10 03:32:02 +0000407 else
408 Value = 0;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000409 break;
410 }
411 }
412 return Value;
413}
414
Xinliang David Li020f22d2015-12-18 23:06:37 +0000415void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
416 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000417 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000418 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000419 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000420 }
421 std::vector<InstrProfValueSiteRecord> &ValueSites =
422 getValueSitesForKind(ValueKind);
423 if (N == 0)
424 ValueSites.push_back(InstrProfValueSiteRecord());
425 else
426 ValueSites.emplace_back(VData, VData + N);
427}
428
Xinliang David Lib75544a2015-11-28 19:07:09 +0000429#define INSTR_PROF_COMMON_API_IMPL
430#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000431
Xinliang David Li020f22d2015-12-18 23:06:37 +0000432/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000433 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000434 * class. These C wrappers are used as adaptors so that C++ code can be
435 * invoked as callbacks.
436 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000437uint32_t getNumValueKindsInstrProf(const void *Record) {
438 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
439}
440
441uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
442 return reinterpret_cast<const InstrProfRecord *>(Record)
443 ->getNumValueSites(VKind);
444}
445
446uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
447 return reinterpret_cast<const InstrProfRecord *>(Record)
448 ->getNumValueData(VKind);
449}
450
451uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
452 uint32_t S) {
453 return reinterpret_cast<const InstrProfRecord *>(R)
454 ->getNumValueDataForSite(VK, S);
455}
456
457void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000458 uint32_t K, uint32_t S) {
459 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
Xinliang David Lie8092312015-11-25 19:13:00 +0000460}
461
Xinliang David Lif47cf552015-11-25 06:23:38 +0000462ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000463 ValueProfData *VD =
464 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
465 memset(VD, 0, TotalSizeInBytes);
466 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000467}
468
469static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000470 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000471 getNumValueKindsInstrProf,
472 getNumValueSitesInstrProf,
473 getNumValueDataInstrProf,
474 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000475 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000476 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000477 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000478
Xinliang David Lie8092312015-11-25 19:13:00 +0000479// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000480uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
481 InstrProfRecordClosure.Record = &Record;
482 return getValueProfDataSize(&InstrProfRecordClosure);
483}
484
Xinliang David Lie8092312015-11-25 19:13:00 +0000485// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000486std::unique_ptr<ValueProfData>
487ValueProfData::serializeFrom(const InstrProfRecord &Record) {
488 InstrProfRecordClosure.Record = &Record;
489
490 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000491 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000492 return VPD;
493}
494
Xinliang David Lie8092312015-11-25 19:13:00 +0000495void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
496 InstrProfRecord::ValueMapType *VMap) {
497 Record.reserveSites(Kind, NumValueSites);
498
499 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
500 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
501 uint8_t ValueDataCount = this->SiteCountArray[VSite];
502 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
503 ValueData += ValueDataCount;
504 }
505}
Xinliang David Lied966772015-11-25 23:31:18 +0000506
Xinliang David Lie8092312015-11-25 19:13:00 +0000507// For writing/serializing, Old is the host endianness, and New is
508// byte order intended on disk. For Reading/deserialization, Old
509// is the on-disk source endianness, and New is the host endianness.
510void ValueProfRecord::swapBytes(support::endianness Old,
511 support::endianness New) {
512 using namespace support;
513 if (Old == New)
514 return;
515
516 if (getHostEndianness() != Old) {
517 sys::swapByteOrder<uint32_t>(NumValueSites);
518 sys::swapByteOrder<uint32_t>(Kind);
519 }
520 uint32_t ND = getValueProfRecordNumValueData(this);
521 InstrProfValueData *VD = getValueProfRecordValueData(this);
522
523 // No need to swap byte array: SiteCountArrray.
524 for (uint32_t I = 0; I < ND; I++) {
525 sys::swapByteOrder<uint64_t>(VD[I].Value);
526 sys::swapByteOrder<uint64_t>(VD[I].Count);
527 }
528 if (getHostEndianness() == Old) {
529 sys::swapByteOrder<uint32_t>(NumValueSites);
530 sys::swapByteOrder<uint32_t>(Kind);
531 }
532}
533
534void ValueProfData::deserializeTo(InstrProfRecord &Record,
535 InstrProfRecord::ValueMapType *VMap) {
536 if (NumValueKinds == 0)
537 return;
538
539 ValueProfRecord *VR = getFirstValueProfRecord(this);
540 for (uint32_t K = 0; K < NumValueKinds; K++) {
541 VR->deserializeTo(Record, VMap);
542 VR = getValueProfRecordNext(VR);
543 }
544}
545
546template <class T>
547static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
548 using namespace support;
549 if (Orig == little)
550 return endian::readNext<T, little, unaligned>(D);
551 else
552 return endian::readNext<T, big, unaligned>(D);
553}
554
555static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
556 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
557 ValueProfData());
558}
559
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000560instrprof_error ValueProfData::checkIntegrity() {
561 if (NumValueKinds > IPVK_Last + 1)
562 return instrprof_error::malformed;
563 // Total size needs to be mulltiple of quadword size.
564 if (TotalSize % sizeof(uint64_t))
565 return instrprof_error::malformed;
566
567 ValueProfRecord *VR = getFirstValueProfRecord(this);
568 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
569 if (VR->Kind > IPVK_Last)
570 return instrprof_error::malformed;
571 VR = getValueProfRecordNext(VR);
572 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
573 return instrprof_error::malformed;
574 }
575 return instrprof_error::success;
576}
577
Xinliang David Liee415892015-11-10 00:24:45 +0000578ErrorOr<std::unique_ptr<ValueProfData>>
579ValueProfData::getValueProfData(const unsigned char *D,
580 const unsigned char *const BufferEnd,
581 support::endianness Endianness) {
582 using namespace support;
583 if (D + sizeof(ValueProfData) > BufferEnd)
584 return instrprof_error::truncated;
585
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000586 const unsigned char *Header = D;
587 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000588 if (D + TotalSize > BufferEnd)
589 return instrprof_error::too_large;
Xinliang David Liee415892015-11-10 00:24:45 +0000590
Xinliang David Lif47cf552015-11-25 06:23:38 +0000591 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000592 memcpy(VPD.get(), D, TotalSize);
593 // Byte swap.
594 VPD->swapBytesToHost(Endianness);
595
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000596 instrprof_error EC = VPD->checkIntegrity();
597 if (EC != instrprof_error::success)
598 return EC;
Xinliang David Liee415892015-11-10 00:24:45 +0000599
Xinliang David Liee415892015-11-10 00:24:45 +0000600 return std::move(VPD);
601}
602
603void ValueProfData::swapBytesToHost(support::endianness Endianness) {
604 using namespace support;
605 if (Endianness == getHostEndianness())
606 return;
607
608 sys::swapByteOrder<uint32_t>(TotalSize);
609 sys::swapByteOrder<uint32_t>(NumValueKinds);
610
Xinliang David Lif47cf552015-11-25 06:23:38 +0000611 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000612 for (uint32_t K = 0; K < NumValueKinds; K++) {
613 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000614 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000615 }
616}
617
618void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
619 using namespace support;
620 if (Endianness == getHostEndianness())
621 return;
622
Xinliang David Lif47cf552015-11-25 06:23:38 +0000623 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000624 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000625 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000626 VR->swapBytes(getHostEndianness(), Endianness);
627 VR = NVR;
628 }
629 sys::swapByteOrder<uint32_t>(TotalSize);
630 sys::swapByteOrder<uint32_t>(NumValueKinds);
631}
Xinliang David Lie8092312015-11-25 19:13:00 +0000632
Xinliang David Li402477d2016-02-04 19:11:43 +0000633void annotateValueSite(Module &M, Instruction &Inst,
634 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000635 InstrProfValueKind ValueKind, uint32_t SiteIdx,
636 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000637 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
Betul Buyukkurt4f1e8c92016-04-14 16:25:45 +0000638 if (!NV)
639 return;
Xinliang David Li402477d2016-02-04 19:11:43 +0000640
641 uint64_t Sum = 0;
642 std::unique_ptr<InstrProfValueData[]> VD =
643 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
644
Rong Xu311ada12016-03-30 16:56:31 +0000645 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
646 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000647}
648
649void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000650 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000651 uint64_t Sum, InstrProfValueKind ValueKind,
652 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000653 LLVMContext &Ctx = M.getContext();
654 MDBuilder MDHelper(Ctx);
655 SmallVector<Metadata *, 3> Vals;
656 // Tag
657 Vals.push_back(MDHelper.createString("VP"));
658 // Value Kind
659 Vals.push_back(MDHelper.createConstant(
660 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
661 // Total Count
662 Vals.push_back(
663 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
664
665 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000666 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000667 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000668 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000669 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000670 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000671 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000672 if (--MDCount == 0)
673 break;
674 }
675 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
676}
677
678bool getValueProfDataFromInst(const Instruction &Inst,
679 InstrProfValueKind ValueKind,
680 uint32_t MaxNumValueData,
681 InstrProfValueData ValueData[],
682 uint32_t &ActualNumValueData, uint64_t &TotalC) {
683 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
684 if (!MD)
685 return false;
686
687 unsigned NOps = MD->getNumOperands();
688
689 if (NOps < 5)
690 return false;
691
692 // Operand 0 is a string tag "VP":
693 MDString *Tag = cast<MDString>(MD->getOperand(0));
694 if (!Tag)
695 return false;
696
697 if (!Tag->getString().equals("VP"))
698 return false;
699
700 // Now check kind:
701 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
702 if (!KindInt)
703 return false;
704 if (KindInt->getZExtValue() != ValueKind)
705 return false;
706
707 // Get total count
708 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
709 if (!TotalCInt)
710 return false;
711 TotalC = TotalCInt->getZExtValue();
712
713 ActualNumValueData = 0;
714
715 for (unsigned I = 3; I < NOps; I += 2) {
716 if (ActualNumValueData >= MaxNumValueData)
717 break;
718 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
719 ConstantInt *Count =
720 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
721 if (!Value || !Count)
722 return false;
723 ValueData[ActualNumValueData].Value = Value->getZExtValue();
724 ValueData[ActualNumValueData].Count = Count->getZExtValue();
725 ActualNumValueData++;
726 }
727 return true;
728}
Rong Xu8e8fe852016-04-01 16:43:30 +0000729
Rong Xu92c2eae2016-04-01 20:15:04 +0000730MDNode *getPGOFuncNameMetadata(const Function &F) {
731 return F.getMetadata(getPGOFuncNameMetadataName());
732}
733
Rong Xuf8f051c2016-04-22 21:00:17 +0000734void createPGOFuncNameMetadata(Function &F, const std::string &PGOFuncName) {
735 // Only for internal linkage functions.
736 if (PGOFuncName == F.getName())
737 return;
738 // Don't create duplicated meta-data.
739 if (getPGOFuncNameMetadata(F))
Rong Xu8e8fe852016-04-01 16:43:30 +0000740 return;
Rong Xu8e8fe852016-04-01 16:43:30 +0000741 LLVMContext &C = F.getContext();
Rong Xuf8f051c2016-04-22 21:00:17 +0000742 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName.c_str()));
Rong Xu8e8fe852016-04-01 16:43:30 +0000743 F.setMetadata(getPGOFuncNameMetadataName(), N);
744}
745
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000746} // end namespace llvm