LLVM  4.0.0
InstrProf.cpp
Go to the documentation of this file.
1 //=-- 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 
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/MDBuilder.h"
22 #include "llvm/IR/Module.h"
25 #include "llvm/Support/LEB128.h"
27 #include "llvm/Support/Path.h"
28 
29 using namespace llvm;
30 
32  "static-func-full-module-prefix", cl::init(false),
33  cl::desc("Use full module build paths in the profile counter names for "
34  "static functions."));
35 
36 namespace {
37 std::string getInstrProfErrString(instrprof_error Err) {
38  switch (Err) {
40  return "Success";
42  return "End of File";
44  return "Unrecognized instrumentation profile encoding format";
46  return "Invalid instrumentation profile data (bad magic)";
48  return "Invalid instrumentation profile data (file header is corrupt)";
50  return "Unsupported instrumentation profile format version";
52  return "Unsupported instrumentation profile hash type";
54  return "Too much profile data";
56  return "Truncated profile data";
58  return "Malformed instrumentation profile data";
60  return "No profile data available for function";
62  return "Function control flow change detected (hash mismatch)";
64  return "Function basic block count change detected (counter mismatch)";
66  return "Counter overflow";
68  return "Function value site count change detected (counter mismatch)";
70  return "Failed to compress data (zlib)";
72  return "Failed to uncompress data (zlib)";
74  return "Empty raw profile file";
75  }
76  llvm_unreachable("A value of instrprof_error has no message.");
77 }
78 
79 // FIXME: This class is only here to support the transition to llvm::Error. It
80 // will be removed once this transition is complete. Clients should prefer to
81 // deal with the Error value directly, rather than converting to error_code.
82 class InstrProfErrorCategoryType : public std::error_category {
83  const char *name() const noexcept override { return "llvm.instrprof"; }
84  std::string message(int IE) const override {
85  return getInstrProfErrString(static_cast<instrprof_error>(IE));
86  }
87 };
88 } // end anonymous namespace
89 
91 
93  return *ErrorCategory;
94 }
95 
96 namespace llvm {
97 
99  if (IE == instrprof_error::success)
100  return;
101 
102  if (FirstError == instrprof_error::success)
103  FirstError = IE;
104 
105  switch (IE) {
107  ++NumHashMismatches;
108  break;
110  ++NumCountMismatches;
111  break;
113  ++NumCounterOverflows;
114  break;
116  ++NumValueSiteCountMismatches;
117  break;
118  default:
119  llvm_unreachable("Not a soft error");
120  }
121 }
122 
123 std::string InstrProfError::message() const {
124  return getInstrProfErrString(Err);
125 }
126 
127 char InstrProfError::ID = 0;
128 
129 std::string getPGOFuncName(StringRef RawFuncName,
131  StringRef FileName,
132  uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
133  return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
134 }
135 
136 // Return the PGOFuncName. This function has some special handling when called
137 // in LTO optimization. The following only applies when calling in LTO passes
138 // (when \c InLTO is true): LTO's internalization privatizes many global linkage
139 // symbols. This happens after value profile annotation, but those internal
140 // linkage functions should not have a source prefix.
141 // Additionally, for ThinLTO mode, exported internal functions are promoted
142 // and renamed. We need to ensure that the original internal PGO name is
143 // used when computing the GUID that is compared against the profiled GUIDs.
144 // To differentiate compiler generated internal symbols from original ones,
145 // PGOFuncName meta data are created and attached to the original internal
146 // symbols in the value profile annotation step
147 // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
148 // data, its original linkage must be non-internal.
149 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
150  if (!InLTO) {
152  ? F.getParent()->getName()
154  return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
155  }
156 
157  // In LTO mode (when InLTO is true), first check if there is a meta data.
158  if (MDNode *MD = getPGOFuncNameMetadata(F)) {
159  StringRef S = cast<MDString>(MD->getOperand(0))->getString();
160  return S.str();
161  }
162 
163  // If there is no meta data, the function must be a global before the value
164  // profile annotation pass. Its current linkage may be internal if it is
165  // internalized in LTO mode.
167 }
168 
170  if (FileName.empty())
171  return PGOFuncName;
172  // Drop the file name including ':'. See also getPGOFuncName.
173  if (PGOFuncName.startswith(FileName))
174  PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
175  return PGOFuncName;
176 }
177 
178 // \p FuncName is the string used as profile lookup key for the function. A
179 // symbol is created to hold the name. Return the legalized symbol name.
180 std::string getPGOFuncNameVarName(StringRef FuncName,
181  GlobalValue::LinkageTypes Linkage) {
182  std::string VarName = getInstrProfNameVarPrefix();
183  VarName += FuncName;
184 
185  if (!GlobalValue::isLocalLinkage(Linkage))
186  return VarName;
187 
188  // Now fix up illegal chars in local VarName that may upset the assembler.
189  const char *InvalidChars = "-:<>/\"'";
190  size_t found = VarName.find_first_of(InvalidChars);
191  while (found != std::string::npos) {
192  VarName[found] = '_';
193  found = VarName.find_first_of(InvalidChars, found + 1);
194  }
195  return VarName;
196 }
197 
200  StringRef PGOFuncName) {
201 
202  // We generally want to match the function's linkage, but available_externally
203  // and extern_weak both have the wrong semantics, and anything that doesn't
204  // need to link across compilation units doesn't need to be visible at all.
205  if (Linkage == GlobalValue::ExternalWeakLinkage)
207  else if (Linkage == GlobalValue::AvailableExternallyLinkage)
209  else if (Linkage == GlobalValue::InternalLinkage ||
210  Linkage == GlobalValue::ExternalLinkage)
211  Linkage = GlobalValue::PrivateLinkage;
212 
213  auto *Value =
214  ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
215  auto FuncNameVar =
216  new GlobalVariable(M, Value->getType(), true, Linkage, Value,
217  getPGOFuncNameVarName(PGOFuncName, Linkage));
218 
219  // Hide the symbol so that we correctly get a copy for each executable.
220  if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
222 
223  return FuncNameVar;
224 }
225 
227  return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
228 }
229 
230 void InstrProfSymtab::create(Module &M, bool InLTO) {
231  for (Function &F : M) {
232  // Function may not have a name: like using asm("") to overwrite the name.
233  // Ignore in this case.
234  if (!F.hasName())
235  continue;
236  const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
237  addFuncName(PGOFuncName);
238  MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
239  }
240 
241  finalizeSymtab();
242 }
243 
244 Error collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
245  bool doCompression, std::string &Result) {
246  assert(NameStrs.size() && "No name data to emit");
247 
248  uint8_t Header[16], *P = Header;
249  std::string UncompressedNameStrings =
250  join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
251 
252  assert(StringRef(UncompressedNameStrings)
253  .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
254  "PGO name is invalid (contains separator token)");
255 
256  unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
257  P += EncLen;
258 
259  auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
260  EncLen = encodeULEB128(CompressedLen, P);
261  P += EncLen;
262  char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
263  unsigned HeaderLen = P - &Header[0];
264  Result.append(HeaderStr, HeaderLen);
265  Result += InputStr;
266  return Error::success();
267  };
268 
269  if (!doCompression) {
270  return WriteStringToResult(0, UncompressedNameStrings);
271  }
272 
273  SmallString<128> CompressedNameStrings;
275  zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
277 
278  if (Success != zlib::StatusOK)
279  return make_error<InstrProfError>(instrprof_error::compress_failed);
280 
281  return WriteStringToResult(CompressedNameStrings.size(),
282  CompressedNameStrings);
283 }
284 
286  auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
287  StringRef NameStr =
288  Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
289  return NameStr;
290 }
291 
292 Error collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
293  std::string &Result, bool doCompression) {
294  std::vector<std::string> NameStrs;
295  for (auto *NameVar : NameVars) {
296  NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
297  }
299  NameStrs, zlib::isAvailable() && doCompression, Result);
300 }
301 
303  const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
304  const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
305  NameStrings.size());
306  while (P < EndP) {
307  uint32_t N;
308  uint64_t UncompressedSize = decodeULEB128(P, &N);
309  P += N;
310  uint64_t CompressedSize = decodeULEB128(P, &N);
311  P += N;
312  bool isCompressed = (CompressedSize != 0);
313  SmallString<128> UncompressedNameStrings;
314  StringRef NameStrings;
315  if (isCompressed) {
316  StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
317  CompressedSize);
318  if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
319  UncompressedSize) != zlib::StatusOK)
320  return make_error<InstrProfError>(instrprof_error::uncompress_failed);
321  P += CompressedSize;
322  NameStrings = StringRef(UncompressedNameStrings.data(),
323  UncompressedNameStrings.size());
324  } else {
325  NameStrings =
326  StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
327  P += UncompressedSize;
328  }
329  // Now parse the name strings.
331  NameStrings.split(Names, getInstrProfNameSeparator());
332  for (StringRef &Name : Names)
333  Symtab.addFuncName(Name);
334 
335  while (P < EndP && *P == 0)
336  P++;
337  }
338  Symtab.finalizeSymtab();
339  return Error::success();
340 }
341 
344  uint64_t Weight) {
345  this->sortByTargetValues();
346  Input.sortByTargetValues();
347  auto I = ValueData.begin();
348  auto IE = ValueData.end();
349  for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
350  ++J) {
351  while (I != IE && I->Value < J->Value)
352  ++I;
353  if (I != IE && I->Value == J->Value) {
354  bool Overflowed;
355  I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
356  if (Overflowed)
358  ++I;
359  continue;
360  }
361  ValueData.insert(I, *J);
362  }
363 }
364 
366  uint64_t Weight) {
367  for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
368  bool Overflowed;
369  I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
370  if (Overflowed)
372  }
373 }
374 
375 // Merge Value Profile data from Src record to this record for ValueKind.
376 // Scale merged value counts by \p Weight.
377 void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
378  InstrProfRecord &Src,
379  uint64_t Weight) {
380  uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
381  uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
382  if (ThisNumValueSites != OtherNumValueSites) {
384  return;
385  }
386  std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
387  getValueSitesForKind(ValueKind);
388  std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
389  Src.getValueSitesForKind(ValueKind);
390  for (uint32_t I = 0; I < ThisNumValueSites; I++)
391  ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
392 }
393 
394 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
395  // If the number of counters doesn't match we either have bad data
396  // or a hash collision.
397  if (Counts.size() != Other.Counts.size()) {
399  return;
400  }
401 
402  for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
403  bool Overflowed;
404  Counts[I] =
405  SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
406  if (Overflowed)
408  }
409 
410  for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
411  mergeValueProfData(Kind, Other, Weight);
412 }
413 
414 void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
415  uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
416  std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
417  getValueSitesForKind(ValueKind);
418  for (uint32_t I = 0; I < ThisNumValueSites; I++)
419  ThisSiteRecords[I].scale(SIPE, Weight);
420 }
421 
422 void InstrProfRecord::scale(uint64_t Weight) {
423  for (auto &Count : this->Counts) {
424  bool Overflowed;
425  Count = SaturatingMultiply(Count, Weight, &Overflowed);
426  if (Overflowed)
428  }
429  for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
430  scaleValueProfData(Kind, Weight);
431 }
432 
433 // Map indirect call target name hash to name string.
434 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
435  ValueMapType *ValueMap) {
436  if (!ValueMap)
437  return Value;
438  switch (ValueKind) {
439  case IPVK_IndirectCallTarget: {
440  auto Result =
441  std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
442  [](const std::pair<uint64_t, uint64_t> &LHS,
443  uint64_t RHS) { return LHS.first < RHS; });
444  // Raw function pointer collected by value profiler may be from
445  // external functions that are not instrumented. They won't have
446  // mapping data to be used by the deserializer. Force the value to
447  // be 0 in this case.
448  if (Result != ValueMap->end() && Result->first == Value)
449  Value = (uint64_t)Result->second;
450  else
451  Value = 0;
452  break;
453  }
454  }
455  return Value;
456 }
457 
459  InstrProfValueData *VData, uint32_t N,
460  ValueMapType *ValueMap) {
461  for (uint32_t I = 0; I < N; I++) {
462  VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
463  }
464  std::vector<InstrProfValueSiteRecord> &ValueSites =
465  getValueSitesForKind(ValueKind);
466  if (N == 0)
467  ValueSites.emplace_back();
468  else
469  ValueSites.emplace_back(VData, VData + N);
470 }
471 
472 #define INSTR_PROF_COMMON_API_IMPL
474 
475 /*!
476  * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
477  * class. These C wrappers are used as adaptors so that C++ code can be
478  * invoked as callbacks.
479  */
481  return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
482 }
483 
485  return reinterpret_cast<const InstrProfRecord *>(Record)
486  ->getNumValueSites(VKind);
487 }
488 
490  return reinterpret_cast<const InstrProfRecord *>(Record)
491  ->getNumValueData(VKind);
492 }
493 
495  uint32_t S) {
496  return reinterpret_cast<const InstrProfRecord *>(R)
497  ->getNumValueDataForSite(VK, S);
498 }
499 
500 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
501  uint32_t K, uint32_t S) {
502  reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
503 }
504 
505 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
506  ValueProfData *VD =
507  (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
508  memset(VD, 0, TotalSizeInBytes);
509  return VD;
510 }
511 
512 static ValueProfRecordClosure InstrProfRecordClosure = {
513  nullptr,
518  nullptr,
521 
522 // Wrapper implementation using the closure mechanism.
523 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
524  InstrProfRecordClosure.Record = &Record;
525  return getValueProfDataSize(&InstrProfRecordClosure);
526 }
527 
528 // Wrapper implementation using the closure mechanism.
529 std::unique_ptr<ValueProfData>
530 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
531  InstrProfRecordClosure.Record = &Record;
532 
533  std::unique_ptr<ValueProfData> VPD(
534  serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
535  return VPD;
536 }
537 
538 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
540  Record.reserveSites(Kind, NumValueSites);
541 
542  InstrProfValueData *ValueData = getValueProfRecordValueData(this);
543  for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
544  uint8_t ValueDataCount = this->SiteCountArray[VSite];
545  Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
546  ValueData += ValueDataCount;
547  }
548 }
549 
550 // For writing/serializing, Old is the host endianness, and New is
551 // byte order intended on disk. For Reading/deserialization, Old
552 // is the on-disk source endianness, and New is the host endianness.
553 void ValueProfRecord::swapBytes(support::endianness Old,
554  support::endianness New) {
555  using namespace support;
556  if (Old == New)
557  return;
558 
559  if (getHostEndianness() != Old) {
560  sys::swapByteOrder<uint32_t>(NumValueSites);
561  sys::swapByteOrder<uint32_t>(Kind);
562  }
563  uint32_t ND = getValueProfRecordNumValueData(this);
564  InstrProfValueData *VD = getValueProfRecordValueData(this);
565 
566  // No need to swap byte array: SiteCountArrray.
567  for (uint32_t I = 0; I < ND; I++) {
568  sys::swapByteOrder<uint64_t>(VD[I].Value);
569  sys::swapByteOrder<uint64_t>(VD[I].Count);
570  }
571  if (getHostEndianness() == Old) {
572  sys::swapByteOrder<uint32_t>(NumValueSites);
573  sys::swapByteOrder<uint32_t>(Kind);
574  }
575 }
576 
577 void ValueProfData::deserializeTo(InstrProfRecord &Record,
579  if (NumValueKinds == 0)
580  return;
581 
582  ValueProfRecord *VR = getFirstValueProfRecord(this);
583  for (uint32_t K = 0; K < NumValueKinds; K++) {
584  VR->deserializeTo(Record, VMap);
585  VR = getValueProfRecordNext(VR);
586  }
587 }
588 
589 template <class T>
590 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
591  using namespace support;
592  if (Orig == little)
593  return endian::readNext<T, little, unaligned>(D);
594  else
595  return endian::readNext<T, big, unaligned>(D);
596 }
597 
598 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
599  return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
600  ValueProfData());
601 }
602 
603 Error ValueProfData::checkIntegrity() {
604  if (NumValueKinds > IPVK_Last + 1)
605  return make_error<InstrProfError>(instrprof_error::malformed);
606  // Total size needs to be mulltiple of quadword size.
607  if (TotalSize % sizeof(uint64_t))
608  return make_error<InstrProfError>(instrprof_error::malformed);
609 
610  ValueProfRecord *VR = getFirstValueProfRecord(this);
611  for (uint32_t K = 0; K < this->NumValueKinds; K++) {
612  if (VR->Kind > IPVK_Last)
613  return make_error<InstrProfError>(instrprof_error::malformed);
614  VR = getValueProfRecordNext(VR);
615  if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
616  return make_error<InstrProfError>(instrprof_error::malformed);
617  }
618  return Error::success();
619 }
620 
622 ValueProfData::getValueProfData(const unsigned char *D,
623  const unsigned char *const BufferEnd,
624  support::endianness Endianness) {
625  using namespace support;
626  if (D + sizeof(ValueProfData) > BufferEnd)
627  return make_error<InstrProfError>(instrprof_error::truncated);
628 
629  const unsigned char *Header = D;
630  uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
631  if (D + TotalSize > BufferEnd)
632  return make_error<InstrProfError>(instrprof_error::too_large);
633 
634  std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
635  memcpy(VPD.get(), D, TotalSize);
636  // Byte swap.
637  VPD->swapBytesToHost(Endianness);
638 
639  Error E = VPD->checkIntegrity();
640  if (E)
641  return std::move(E);
642 
643  return std::move(VPD);
644 }
645 
646 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
647  using namespace support;
648  if (Endianness == getHostEndianness())
649  return;
650 
651  sys::swapByteOrder<uint32_t>(TotalSize);
652  sys::swapByteOrder<uint32_t>(NumValueKinds);
653 
654  ValueProfRecord *VR = getFirstValueProfRecord(this);
655  for (uint32_t K = 0; K < NumValueKinds; K++) {
656  VR->swapBytes(Endianness, getHostEndianness());
657  VR = getValueProfRecordNext(VR);
658  }
659 }
660 
661 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
662  using namespace support;
663  if (Endianness == getHostEndianness())
664  return;
665 
666  ValueProfRecord *VR = getFirstValueProfRecord(this);
667  for (uint32_t K = 0; K < NumValueKinds; K++) {
668  ValueProfRecord *NVR = getValueProfRecordNext(VR);
669  VR->swapBytes(getHostEndianness(), Endianness);
670  VR = NVR;
671  }
672  sys::swapByteOrder<uint32_t>(TotalSize);
673  sys::swapByteOrder<uint32_t>(NumValueKinds);
674 }
675 
677  const InstrProfRecord &InstrProfR,
678  InstrProfValueKind ValueKind, uint32_t SiteIdx,
679  uint32_t MaxMDCount) {
680  uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
681  if (!NV)
682  return;
683 
684  uint64_t Sum = 0;
685  std::unique_ptr<InstrProfValueData[]> VD =
686  InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
687 
688  ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
689  annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
690 }
691 
694  uint64_t Sum, InstrProfValueKind ValueKind,
695  uint32_t MaxMDCount) {
696  LLVMContext &Ctx = M.getContext();
697  MDBuilder MDHelper(Ctx);
699  // Tag
700  Vals.push_back(MDHelper.createString("VP"));
701  // Value Kind
702  Vals.push_back(MDHelper.createConstant(
703  ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
704  // Total Count
705  Vals.push_back(
706  MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
707 
708  // Value Profile Data
709  uint32_t MDCount = MaxMDCount;
710  for (auto &VD : VDs) {
711  Vals.push_back(MDHelper.createConstant(
712  ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
713  Vals.push_back(MDHelper.createConstant(
714  ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
715  if (--MDCount == 0)
716  break;
717  }
718  Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
719 }
720 
722  InstrProfValueKind ValueKind,
723  uint32_t MaxNumValueData,
724  InstrProfValueData ValueData[],
725  uint32_t &ActualNumValueData, uint64_t &TotalC) {
727  if (!MD)
728  return false;
729 
730  unsigned NOps = MD->getNumOperands();
731 
732  if (NOps < 5)
733  return false;
734 
735  // Operand 0 is a string tag "VP":
736  MDString *Tag = cast<MDString>(MD->getOperand(0));
737  if (!Tag)
738  return false;
739 
740  if (!Tag->getString().equals("VP"))
741  return false;
742 
743  // Now check kind:
744  ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
745  if (!KindInt)
746  return false;
747  if (KindInt->getZExtValue() != ValueKind)
748  return false;
749 
750  // Get total count
751  ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
752  if (!TotalCInt)
753  return false;
754  TotalC = TotalCInt->getZExtValue();
755 
756  ActualNumValueData = 0;
757 
758  for (unsigned I = 3; I < NOps; I += 2) {
759  if (ActualNumValueData >= MaxNumValueData)
760  break;
761  ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
762  ConstantInt *Count =
763  mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
764  if (!Value || !Count)
765  return false;
766  ValueData[ActualNumValueData].Value = Value->getZExtValue();
767  ValueData[ActualNumValueData].Count = Count->getZExtValue();
768  ActualNumValueData++;
769  }
770  return true;
771 }
772 
775 }
776 
778  // Only for internal linkage functions.
779  if (PGOFuncName == F.getName())
780  return;
781  // Don't create duplicated meta-data.
782  if (getPGOFuncNameMetadata(F))
783  return;
784  LLVMContext &C = F.getContext();
785  MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
787 }
788 
789 bool needsComdatForCounter(const Function &F, const Module &M) {
790  if (F.hasComdat())
791  return true;
792 
793  Triple TT(M.getTargetTriple());
794  if (!TT.isOSBinFormatELF())
795  return false;
796 
797  // See createPGOFuncNameVar for more details. To avoid link errors, profile
798  // counters for function with available_externally linkage needs to be changed
799  // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
800  // created. Without using comdat, duplicate entries won't be removed by the
801  // linker leading to increased data segement size and raw profile size. Even
802  // worse, since the referenced counter from profile per-function data object
803  // will be resolved to the common strong definition, the profile counts for
804  // available_externally functions will end up being duplicated in raw profile
805  // data. This can result in distorted profile as the counts of those dups
806  // will be accumulated by the profile merger.
808  if (Linkage != GlobalValue::ExternalWeakLinkage &&
810  return false;
811 
812  return true;
813 }
814 
815 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
816 bool isIRPGOFlagSet(const Module *M) {
817  auto IRInstrVar =
818  M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
819  if (!IRInstrVar || IRInstrVar->isDeclaration() ||
820  IRInstrVar->hasLocalLinkage())
821  return false;
822 
823  // Check if the flag is set.
824  if (!IRInstrVar->hasInitializer())
825  return false;
826 
827  const Constant *InitVal = IRInstrVar->getInitializer();
828  if (!InitVal)
829  return false;
830 
831  return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
832  VARIANT_MASK_IR_PROF) != 0;
833 }
834 
835 // Check if we can safely rename this Comdat function.
836 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
837  if (F.getName().empty())
838  return false;
839  if (!needsComdatForCounter(F, *(F.getParent())))
840  return false;
841  // Unsafe to rename the address-taken function (which can be used in
842  // function comparison).
843  if (CheckAddressTaken && F.hasAddressTaken())
844  return false;
845  // Only safe to do if this function may be discarded if it is not used
846  // in the compilation unit.
848  return false;
849 
850  // For AvailableExternallyLinkage functions.
851  if (!F.hasComdat()) {
853  return true;
854  }
855  return true;
856 }
857 } // end namespace llvm
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:225
void scale(uint64_t Weight)
Scale up profile counts (including value profile data) by Weight.
Definition: InstrProf.cpp:422
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:634
void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst, uint32_t K, uint32_t S)
Definition: InstrProf.cpp:500
LinkageTypes getLinkage() const
Definition: GlobalValue.h:429
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
Definition: InstrProf.h:416
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2471
bool hasComdat() const
Definition: GlobalObject.h:91
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:226
DiagnosticInfoOptimizationBase::Argument NV
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition: InstrProf.h:90
uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind)
Definition: InstrProf.cpp:489
SoftInstrProfErrors SIPE
Definition: InstrProf.h:588
ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition: MDBuilder.cpp:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:473
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:414
Available for inspection, not emission.
Definition: GlobalValue.h:50
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1040
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:836
MDNode * getPGOFuncNameMetadata(const Function &F)
Return the PGOFuncName meta data associated with a function.
Definition: InstrProf.cpp:773
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
Externally visible function.
Definition: GlobalValue.h:49
static std::unique_ptr< ValueProfData > allocValueProfData(uint32_t TotalSize)
Definition: InstrProf.cpp:598
static T swapToHostOrder(const unsigned char *&D, support::endianness Orig)
Definition: InstrProf.cpp:590
Metadata node.
Definition: Metadata.h:830
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:170
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:218
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
Definition: MathExtras.h:767
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Definition: InstrProf.h:736
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:300
uint32_t getNumValueKindsInstrProf(const void *Record)
ValueProfRecordClosure Interface implementation for InstrProfRecord class.
Definition: InstrProf.cpp:480
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:191
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:205
const std::error_category & instrprof_category()
Definition: InstrProf.cpp:92
static GCRegistry::Add< StatepointGC > D("statepoint-example","an example strategy for statepoint")
InstrProfValueKind
Definition: InstrProf.h:242
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
Definition: StringRef.h:166
Status compress(StringRef InputBuffer, SmallVectorImpl< char > &CompressedBuffer, CompressionLevel Level=DefaultCompression)
Definition: Compression.cpp:49
void merge(InstrProfRecord &Other, uint64_t Weight=1)
Merge the counts in Other into this one.
Definition: InstrProf.cpp:394
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
Definition: StringExtras.h:232
Error collectPGOFuncNameStrings(const std::vector< std::string > &NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (function PGO names) NameStrs, the method generates a combined string Resul...
Definition: InstrProf.cpp:244
Tagged union holding either a T or a Error.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:154
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name...
Definition: InstrProf.cpp:169
#define F(x, y, z)
Definition: MD5.cpp:51
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:264
void addFuncName(StringRef FuncName)
Update the symtab by adding FuncName to the table.
Definition: InstrProf.h:468
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition: InstrProf.h:169
void addError(instrprof_error IE)
Track a soft error (IE) and increment its associated counter.
Definition: InstrProf.cpp:98
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:791
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:135
bool isDiscardableIfUnused() const
Definition: GlobalValue.h:431
uint64_t decodeULEB128(const uint8_t *p, unsigned *n=nullptr)
Utility function to decode a ULEB128 value.
Definition: LEB128.h:80
void merge(SoftInstrProfErrors &SIPE, InstrProfValueSiteRecord &Input, uint64_t Weight=1)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight...
Definition: InstrProf.cpp:342
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
Definition: InstrProf.cpp:816
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
static ManagedStatic< InstrProfErrorCategoryType > ErrorCategory
Definition: InstrProf.cpp:90
std::string message() const override
Return the error message as a string.
Definition: InstrProf.cpp:123
Status uncompress(StringRef InputBuffer, char *UncompressedBuffer, size_t &UncompressedSize)
Definition: Compression.cpp:65
ExternalWeak linkage description.
Definition: GlobalValue.h:58
bool needsComdatForCounter(const Function &F, const Module &M)
Check if we can use Comdat for profile variables.
Definition: InstrProf.cpp:789
bool isAvailable()
Definition: Compression.cpp:48
#define P(N)
StringRef filename(StringRef path)
Get filename.
Definition: Path.cpp:584
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:52
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
bool getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, InstrProfValueData ValueData[], uint32_t &ActualNumValueData, uint64_t &TotalC)
Extract the value profile data from Inst which is annotated with value profile meta data...
Definition: InstrProf.cpp:721
void scale(SoftInstrProfErrors &SIPE, uint64_t Weight)
Scale up value profile data counts.
Definition: InstrProf.cpp:365
std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
Definition: InstrProf.cpp:180
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:48
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static ValueProfRecordClosure InstrProfRecordClosure
Definition: InstrProf.cpp:512
ValueProfData * allocValueProfDataInstrProf(size_t TotalSizeInBytes)
Definition: InstrProf.cpp:505
static ManagedStatic< _object_error_category > error_category
#define LLVM_ATTRIBUTE_UNUSED
Definition: Compiler.h:150
static cl::opt< bool > StaticFuncFullModulePrefix("static-func-full-module-prefix", cl::init(false), cl::desc("Use full module build paths in the profile counter names for ""static functions."))
std::list< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition: InstrProf.h:555
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:225
void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
Definition: InstrProf.cpp:676
Value(Type *Ty, unsigned scid)
Definition: Value.cpp:48
uint32_t getNumValueDataForSite(uint32_t ValueKind, uint32_t Site) const
Return the number of value data collected for ValueKind at profiling site: Site.
Definition: InstrProf.h:700
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
Definition: InstrProf.cpp:777
Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab)
NameStrings is a string composed of one of more sub-strings encoded in the format described above...
Definition: InstrProf.cpp:302
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1183
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
void addValueData(uint32_t ValueKind, uint32_t Site, InstrProfValueData *VData, uint32_t N, ValueMapType *ValueMap)
Add ValueData for ValueKind at value Site.
Definition: InstrProf.cpp:458
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition: MathExtras.h:813
StringRef getString() const
Definition: Metadata.cpp:424
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1034
static ErrorSuccess success()
Create a success value.
uint64_t * Vals
See the file comment.
Definition: ValueMap.h:87
This is the shared class of boolean and integer constants.
Definition: Constants.h:88
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:51
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:175
GlobalVariable * getNamedGlobal(StringRef Name)
Return the global variable in the module with the specified name, of arbitrary type.
Definition: Module.h:357
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
Definition: Globals.cpp:140
StringRef getPGOFuncNameMetadataName()
Definition: InstrProf.h:271
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:558
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
static char ID
Definition: InstrProf.h:339
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:716
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition: InstrProf.h:563
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:130
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1391
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1381
#define Success
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1132
std::vector< uint64_t > Counts
Definition: InstrProf.h:587
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition: Function.cpp:1171
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:142
Profiling information for a single function.
Definition: InstrProf.h:581
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:169
std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Return the modified name for function F suitable to be used the key for profile lookup.
Definition: InstrProf.cpp:149
instrprof_error
Definition: InstrProf.h:287
MDString * createString(StringRef Str)
Return the given string as metadata.
Definition: MDBuilder.cpp:20
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
Definition: InstrProf.cpp:226
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition: InstrProf.h:696
const unsigned Kind
uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind)
Definition: InstrProf.cpp:484
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
aarch64 promote const
std::unique_ptr< InstrProfValueData[]> getValueForSite(uint32_t ValueKind, uint32_t Site, uint64_t *TotalC=0) const
Return the array of profiled values at Site.
Definition: InstrProf.h:706
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:537
LLVM Value Representation.
Definition: Value.h:71
static const char * name
Lightweight error class with error context and mandatory checking.
support::endianness getHostEndianness()
Definition: InstrProf.h:742
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:125
void encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned Padding=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:38
std::vector< std::pair< uint64_t, uint64_t > > ValueMapType
Definition: InstrProf.h:590
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
A single uniqued string.
Definition: Metadata.h:586
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:63
uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK, uint32_t S)
Definition: InstrProf.cpp:494
const uint64_t Version
Definition: InstrProf.h:799
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
Definition: InstrProf.cpp:285
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:222