OSDN Git Service

[PGO] Add another interface for annotateValueSite
[android-x86/external-llvm.git] / lib / ProfileData / InstrProf.cpp
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
15 #include "llvm/ProfileData/InstrProf.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/GlobalVariable.h"
20 #include "llvm/IR/MDBuilder.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/Compression.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/ManagedStatic.h"
26
27 using namespace llvm;
28
29 namespace {
30 class InstrProfErrorCategoryType : public std::error_category {
31   const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
32   std::string message(int IE) const override {
33     instrprof_error E = static_cast<instrprof_error>(IE);
34     switch (E) {
35     case instrprof_error::success:
36       return "Success";
37     case instrprof_error::eof:
38       return "End of File";
39     case instrprof_error::unrecognized_format:
40       return "Unrecognized instrumentation profile encoding format";
41     case instrprof_error::bad_magic:
42       return "Invalid instrumentation profile data (bad magic)";
43     case instrprof_error::bad_header:
44       return "Invalid instrumentation profile data (file header is corrupt)";
45     case instrprof_error::unsupported_version:
46       return "Unsupported instrumentation profile format version";
47     case instrprof_error::unsupported_hash_type:
48       return "Unsupported instrumentation profile hash type";
49     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:
54       return "Malformed instrumentation profile data";
55     case instrprof_error::unknown_function:
56       return "No profile data available for function";
57     case instrprof_error::hash_mismatch:
58       return "Function control flow change detected (hash mismatch)";
59     case instrprof_error::count_mismatch:
60       return "Function basic block count change detected (counter mismatch)";
61     case instrprof_error::counter_overflow:
62       return "Counter overflow";
63     case instrprof_error::value_site_count_mismatch:
64       return "Function value site count change detected (counter mismatch)";
65     }
66     llvm_unreachable("A value of instrprof_error has no message.");
67   }
68 };
69 } // end anonymous namespace
70
71 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
72
73 const std::error_category &llvm::instrprof_category() {
74   return *ErrorCategory;
75 }
76
77 namespace llvm {
78
79 std::string getPGOFuncName(StringRef RawFuncName,
80                            GlobalValue::LinkageTypes Linkage,
81                            StringRef FileName,
82                            uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
83   return Function::getGlobalIdentifier(RawFuncName, Linkage, FileName);
84 }
85
86 std::string getPGOFuncName(const Function &F, uint64_t Version) {
87   return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
88                         Version);
89 }
90
91 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
92   if (FileName.empty())
93     return PGOFuncName;
94   // Drop the file name including ':'. See also getPGOFuncName.
95   if (PGOFuncName.startswith(FileName))
96     PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
97   return PGOFuncName;
98 }
99
100 // \p FuncName is the string used as profile lookup key for the function. A
101 // symbol is created to hold the name. Return the legalized symbol name.
102 static std::string getPGOFuncNameVarName(StringRef FuncName,
103                                          GlobalValue::LinkageTypes Linkage) {
104   std::string VarName = getInstrProfNameVarPrefix();
105   VarName += FuncName;
106
107   if (!GlobalValue::isLocalLinkage(Linkage))
108     return VarName;
109
110   // Now fix up illegal chars in local VarName that may upset the assembler.
111   const char *InvalidChars = "-:<>\"'";
112   size_t found = VarName.find_first_of(InvalidChars);
113   while (found != std::string::npos) {
114     VarName[found] = '_';
115     found = VarName.find_first_of(InvalidChars, found + 1);
116   }
117   return VarName;
118 }
119
120 GlobalVariable *createPGOFuncNameVar(Module &M,
121                                      GlobalValue::LinkageTypes Linkage,
122                                      StringRef FuncName) {
123
124   // We generally want to match the function's linkage, but available_externally
125   // and extern_weak both have the wrong semantics, and anything that doesn't
126   // need to link across compilation units doesn't need to be visible at all.
127   if (Linkage == GlobalValue::ExternalWeakLinkage)
128     Linkage = GlobalValue::LinkOnceAnyLinkage;
129   else if (Linkage == GlobalValue::AvailableExternallyLinkage)
130     Linkage = GlobalValue::LinkOnceODRLinkage;
131   else if (Linkage == GlobalValue::InternalLinkage ||
132            Linkage == GlobalValue::ExternalLinkage)
133     Linkage = GlobalValue::PrivateLinkage;
134
135   auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
136   auto FuncNameVar =
137       new GlobalVariable(M, Value->getType(), true, Linkage, Value,
138                          getPGOFuncNameVarName(FuncName, Linkage));
139
140   // Hide the symbol so that we correctly get a copy for each executable.
141   if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
142     FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
143
144   return FuncNameVar;
145 }
146
147 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
148   return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
149 }
150
151 void InstrProfSymtab::create(const Module &M) {
152   for (const Function &F : M)
153     addFuncName(getPGOFuncName(F));
154
155   finalizeSymtab();
156 }
157
158 int collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
159                               bool doCompression, std::string &Result) {
160   uint8_t Header[16], *P = Header;
161   std::string UncompressedNameStrings =
162       join(NameStrs.begin(), NameStrs.end(), StringRef(" "));
163
164   unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
165   P += EncLen;
166
167   auto WriteStringToResult = [&](size_t CompressedLen,
168                                  const std::string &InputStr) {
169     EncLen = encodeULEB128(CompressedLen, P);
170     P += EncLen;
171     char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
172     unsigned HeaderLen = P - &Header[0];
173     Result.append(HeaderStr, HeaderLen);
174     Result += InputStr;
175     return 0;
176   };
177
178   if (!doCompression)
179     return WriteStringToResult(0, UncompressedNameStrings);
180
181   SmallVector<char, 128> CompressedNameStrings;
182   zlib::Status Success =
183       zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
184                      zlib::BestSizeCompression);
185
186   if (Success != zlib::StatusOK)
187     return 1;
188
189   return WriteStringToResult(
190       CompressedNameStrings.size(),
191       std::string(CompressedNameStrings.data(), CompressedNameStrings.size()));
192 }
193
194 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
195   auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
196   StringRef NameStr =
197       Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
198   return NameStr;
199 }
200
201 int collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
202                               std::string &Result, bool doCompression) {
203   std::vector<std::string> NameStrs;
204   for (auto *NameVar : NameVars) {
205     NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
206   }
207   return collectPGOFuncNameStrings(
208       NameStrs, zlib::isAvailable() && doCompression, Result);
209 }
210
211 int readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
212   const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
213   const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
214                                                           NameStrings.size());
215   while (P < EndP) {
216     uint32_t N;
217     uint64_t UncompressedSize = decodeULEB128(P, &N);
218     P += N;
219     uint64_t CompressedSize = decodeULEB128(P, &N);
220     P += N;
221     bool isCompressed = (CompressedSize != 0);
222     SmallString<128> UncompressedNameStrings;
223     StringRef NameStrings;
224     if (isCompressed) {
225       StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
226                                       CompressedSize);
227       if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
228                            UncompressedSize) != zlib::StatusOK)
229         return 1;
230       P += CompressedSize;
231       NameStrings = StringRef(UncompressedNameStrings.data(),
232                               UncompressedNameStrings.size());
233     } else {
234       NameStrings =
235           StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
236       P += UncompressedSize;
237     }
238     // Now parse the name strings.
239     SmallVector<StringRef, 0> Names;
240     NameStrings.split(Names, ' ');
241     for (StringRef &Name : Names)
242       Symtab.addFuncName(Name);
243
244     while (P < EndP && *P == 0)
245       P++;
246   }
247   Symtab.finalizeSymtab();
248   return 0;
249 }
250
251 instrprof_error InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
252                                                 uint64_t Weight) {
253   this->sortByTargetValues();
254   Input.sortByTargetValues();
255   auto I = ValueData.begin();
256   auto IE = ValueData.end();
257   instrprof_error Result = instrprof_error::success;
258   for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
259        ++J) {
260     while (I != IE && I->Value < J->Value)
261       ++I;
262     if (I != IE && I->Value == J->Value) {
263       bool Overflowed;
264       I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
265       if (Overflowed)
266         Result = instrprof_error::counter_overflow;
267       ++I;
268       continue;
269     }
270     ValueData.insert(I, *J);
271   }
272   return Result;
273 }
274
275 instrprof_error InstrProfValueSiteRecord::scale(uint64_t Weight) {
276   instrprof_error Result = instrprof_error::success;
277   for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
278     bool Overflowed;
279     I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
280     if (Overflowed)
281       Result = instrprof_error::counter_overflow;
282   }
283   return Result;
284 }
285
286 // Merge Value Profile data from Src record to this record for ValueKind.
287 // Scale merged value counts by \p Weight.
288 instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
289                                                     InstrProfRecord &Src,
290                                                     uint64_t Weight) {
291   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
292   uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
293   if (ThisNumValueSites != OtherNumValueSites)
294     return instrprof_error::value_site_count_mismatch;
295   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
296       getValueSitesForKind(ValueKind);
297   std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
298       Src.getValueSitesForKind(ValueKind);
299   instrprof_error Result = instrprof_error::success;
300   for (uint32_t I = 0; I < ThisNumValueSites; I++)
301     MergeResult(Result, ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight));
302   return Result;
303 }
304
305 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
306                                        uint64_t Weight) {
307   // If the number of counters doesn't match we either have bad data
308   // or a hash collision.
309   if (Counts.size() != Other.Counts.size())
310     return instrprof_error::count_mismatch;
311
312   instrprof_error Result = instrprof_error::success;
313
314   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
315     bool Overflowed;
316     Counts[I] =
317         SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
318     if (Overflowed)
319       Result = instrprof_error::counter_overflow;
320   }
321
322   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
323     MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
324
325   return Result;
326 }
327
328 instrprof_error InstrProfRecord::scaleValueProfData(uint32_t ValueKind,
329                                                     uint64_t Weight) {
330   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
331   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
332       getValueSitesForKind(ValueKind);
333   instrprof_error Result = instrprof_error::success;
334   for (uint32_t I = 0; I < ThisNumValueSites; I++)
335     MergeResult(Result, ThisSiteRecords[I].scale(Weight));
336   return Result;
337 }
338
339 instrprof_error InstrProfRecord::scale(uint64_t Weight) {
340   instrprof_error Result = instrprof_error::success;
341   for (auto &Count : this->Counts) {
342     bool Overflowed;
343     Count = SaturatingMultiply(Count, Weight, &Overflowed);
344     if (Overflowed && Result == instrprof_error::success) {
345       Result = instrprof_error::counter_overflow;
346     }
347   }
348   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
349     MergeResult(Result, scaleValueProfData(Kind, Weight));
350
351   return Result;
352 }
353
354 // Map indirect call target name hash to name string.
355 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
356                                      ValueMapType *ValueMap) {
357   if (!ValueMap)
358     return Value;
359   switch (ValueKind) {
360   case IPVK_IndirectCallTarget: {
361     auto Result =
362         std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
363                          [](const std::pair<uint64_t, uint64_t> &LHS,
364                             uint64_t RHS) { return LHS.first < RHS; });
365     if (Result != ValueMap->end())
366       Value = (uint64_t)Result->second;
367     break;
368   }
369   }
370   return Value;
371 }
372
373 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
374                                    InstrProfValueData *VData, uint32_t N,
375                                    ValueMapType *ValueMap) {
376   for (uint32_t I = 0; I < N; I++) {
377     VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
378   }
379   std::vector<InstrProfValueSiteRecord> &ValueSites =
380       getValueSitesForKind(ValueKind);
381   if (N == 0)
382     ValueSites.push_back(InstrProfValueSiteRecord());
383   else
384     ValueSites.emplace_back(VData, VData + N);
385 }
386
387 #define INSTR_PROF_COMMON_API_IMPL
388 #include "llvm/ProfileData/InstrProfData.inc"
389
390 /*!
391  * \brief ValueProfRecordClosure Interface implementation for  InstrProfRecord
392  *  class. These C wrappers are used as adaptors so that C++ code can be
393  *  invoked as callbacks.
394  */
395 uint32_t getNumValueKindsInstrProf(const void *Record) {
396   return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
397 }
398
399 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
400   return reinterpret_cast<const InstrProfRecord *>(Record)
401       ->getNumValueSites(VKind);
402 }
403
404 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
405   return reinterpret_cast<const InstrProfRecord *>(Record)
406       ->getNumValueData(VKind);
407 }
408
409 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
410                                          uint32_t S) {
411   return reinterpret_cast<const InstrProfRecord *>(R)
412       ->getNumValueDataForSite(VK, S);
413 }
414
415 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
416                               uint32_t K, uint32_t S) {
417   reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
418   return;
419 }
420
421 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
422   ValueProfData *VD =
423       (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
424   memset(VD, 0, TotalSizeInBytes);
425   return VD;
426 }
427
428 static ValueProfRecordClosure InstrProfRecordClosure = {
429     nullptr,
430     getNumValueKindsInstrProf,
431     getNumValueSitesInstrProf,
432     getNumValueDataInstrProf,
433     getNumValueDataForSiteInstrProf,
434     nullptr,
435     getValueForSiteInstrProf,
436     allocValueProfDataInstrProf};
437
438 // Wrapper implementation using the closure mechanism.
439 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
440   InstrProfRecordClosure.Record = &Record;
441   return getValueProfDataSize(&InstrProfRecordClosure);
442 }
443
444 // Wrapper implementation using the closure mechanism.
445 std::unique_ptr<ValueProfData>
446 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
447   InstrProfRecordClosure.Record = &Record;
448
449   std::unique_ptr<ValueProfData> VPD(
450       serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
451   return VPD;
452 }
453
454 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
455                                     InstrProfRecord::ValueMapType *VMap) {
456   Record.reserveSites(Kind, NumValueSites);
457
458   InstrProfValueData *ValueData = getValueProfRecordValueData(this);
459   for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
460     uint8_t ValueDataCount = this->SiteCountArray[VSite];
461     Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
462     ValueData += ValueDataCount;
463   }
464 }
465
466 // For writing/serializing,  Old is the host endianness, and  New is
467 // byte order intended on disk. For Reading/deserialization, Old
468 // is the on-disk source endianness, and New is the host endianness.
469 void ValueProfRecord::swapBytes(support::endianness Old,
470                                 support::endianness New) {
471   using namespace support;
472   if (Old == New)
473     return;
474
475   if (getHostEndianness() != Old) {
476     sys::swapByteOrder<uint32_t>(NumValueSites);
477     sys::swapByteOrder<uint32_t>(Kind);
478   }
479   uint32_t ND = getValueProfRecordNumValueData(this);
480   InstrProfValueData *VD = getValueProfRecordValueData(this);
481
482   // No need to swap byte array: SiteCountArrray.
483   for (uint32_t I = 0; I < ND; I++) {
484     sys::swapByteOrder<uint64_t>(VD[I].Value);
485     sys::swapByteOrder<uint64_t>(VD[I].Count);
486   }
487   if (getHostEndianness() == Old) {
488     sys::swapByteOrder<uint32_t>(NumValueSites);
489     sys::swapByteOrder<uint32_t>(Kind);
490   }
491 }
492
493 void ValueProfData::deserializeTo(InstrProfRecord &Record,
494                                   InstrProfRecord::ValueMapType *VMap) {
495   if (NumValueKinds == 0)
496     return;
497
498   ValueProfRecord *VR = getFirstValueProfRecord(this);
499   for (uint32_t K = 0; K < NumValueKinds; K++) {
500     VR->deserializeTo(Record, VMap);
501     VR = getValueProfRecordNext(VR);
502   }
503 }
504
505 template <class T>
506 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
507   using namespace support;
508   if (Orig == little)
509     return endian::readNext<T, little, unaligned>(D);
510   else
511     return endian::readNext<T, big, unaligned>(D);
512 }
513
514 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
515   return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
516                                             ValueProfData());
517 }
518
519 instrprof_error ValueProfData::checkIntegrity() {
520   if (NumValueKinds > IPVK_Last + 1)
521     return instrprof_error::malformed;
522   // Total size needs to be mulltiple of quadword size.
523   if (TotalSize % sizeof(uint64_t))
524     return instrprof_error::malformed;
525
526   ValueProfRecord *VR = getFirstValueProfRecord(this);
527   for (uint32_t K = 0; K < this->NumValueKinds; K++) {
528     if (VR->Kind > IPVK_Last)
529       return instrprof_error::malformed;
530     VR = getValueProfRecordNext(VR);
531     if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
532       return instrprof_error::malformed;
533   }
534   return instrprof_error::success;
535 }
536
537 ErrorOr<std::unique_ptr<ValueProfData>>
538 ValueProfData::getValueProfData(const unsigned char *D,
539                                 const unsigned char *const BufferEnd,
540                                 support::endianness Endianness) {
541   using namespace support;
542   if (D + sizeof(ValueProfData) > BufferEnd)
543     return instrprof_error::truncated;
544
545   const unsigned char *Header = D;
546   uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
547   if (D + TotalSize > BufferEnd)
548     return instrprof_error::too_large;
549
550   std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
551   memcpy(VPD.get(), D, TotalSize);
552   // Byte swap.
553   VPD->swapBytesToHost(Endianness);
554
555   instrprof_error EC = VPD->checkIntegrity();
556   if (EC != instrprof_error::success)
557     return EC;
558
559   return std::move(VPD);
560 }
561
562 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
563   using namespace support;
564   if (Endianness == getHostEndianness())
565     return;
566
567   sys::swapByteOrder<uint32_t>(TotalSize);
568   sys::swapByteOrder<uint32_t>(NumValueKinds);
569
570   ValueProfRecord *VR = getFirstValueProfRecord(this);
571   for (uint32_t K = 0; K < NumValueKinds; K++) {
572     VR->swapBytes(Endianness, getHostEndianness());
573     VR = getValueProfRecordNext(VR);
574   }
575 }
576
577 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
578   using namespace support;
579   if (Endianness == getHostEndianness())
580     return;
581
582   ValueProfRecord *VR = getFirstValueProfRecord(this);
583   for (uint32_t K = 0; K < NumValueKinds; K++) {
584     ValueProfRecord *NVR = getValueProfRecordNext(VR);
585     VR->swapBytes(getHostEndianness(), Endianness);
586     VR = NVR;
587   }
588   sys::swapByteOrder<uint32_t>(TotalSize);
589   sys::swapByteOrder<uint32_t>(NumValueKinds);
590 }
591
592 void annotateValueSite(Module &M, Instruction &Inst,
593                        const InstrProfRecord &InstrProfR,
594                        InstrProfValueKind ValueKind, uint32_t SiteIdx,
595                        uint32_t MaxMDCount) {
596   uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
597
598   uint64_t Sum = 0;
599   std::unique_ptr<InstrProfValueData[]> VD =
600       InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
601
602   annotateValueSite(M, Inst, VD.get(), NV, Sum, ValueKind, MaxMDCount);
603 }
604
605 void annotateValueSite(Module &M, Instruction &Inst,
606                        const InstrProfValueData VD[], uint32_t NV,
607                        uint64_t Sum, InstrProfValueKind ValueKind,
608                        uint32_t MaxMDCount) {
609   LLVMContext &Ctx = M.getContext();
610   MDBuilder MDHelper(Ctx);
611   SmallVector<Metadata *, 3> Vals;
612   // Tag
613   Vals.push_back(MDHelper.createString("VP"));
614   // Value Kind
615   Vals.push_back(MDHelper.createConstant(
616       ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
617   // Total Count
618   Vals.push_back(
619       MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
620
621   // Value Profile Data
622   uint32_t MDCount = MaxMDCount;
623   for (uint32_t I = 0; I < NV; ++I) {
624     Vals.push_back(MDHelper.createConstant(
625         ConstantInt::get(Type::getInt64Ty(Ctx), VD[I].Value)));
626     Vals.push_back(MDHelper.createConstant(
627         ConstantInt::get(Type::getInt64Ty(Ctx), VD[I].Count)));
628     if (--MDCount == 0)
629       break;
630   }
631   Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
632 }
633
634 bool getValueProfDataFromInst(const Instruction &Inst,
635                               InstrProfValueKind ValueKind,
636                               uint32_t MaxNumValueData,
637                               InstrProfValueData ValueData[],
638                               uint32_t &ActualNumValueData, uint64_t &TotalC) {
639   MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
640   if (!MD)
641     return false;
642
643   unsigned NOps = MD->getNumOperands();
644
645   if (NOps < 5)
646     return false;
647
648   // Operand 0 is a string tag "VP":
649   MDString *Tag = cast<MDString>(MD->getOperand(0));
650   if (!Tag)
651     return false;
652
653   if (!Tag->getString().equals("VP"))
654     return false;
655
656   // Now check kind:
657   ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
658   if (!KindInt)
659     return false;
660   if (KindInt->getZExtValue() != ValueKind)
661     return false;
662
663   // Get total count
664   ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
665   if (!TotalCInt)
666     return false;
667   TotalC = TotalCInt->getZExtValue();
668
669   ActualNumValueData = 0;
670
671   for (unsigned I = 3; I < NOps; I += 2) {
672     if (ActualNumValueData >= MaxNumValueData)
673       break;
674     ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
675     ConstantInt *Count =
676         mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
677     if (!Value || !Count)
678       return false;
679     ValueData[ActualNumValueData].Value = Value->getZExtValue();
680     ValueData[ActualNumValueData].Count = Count->getZExtValue();
681     ActualNumValueData++;
682   }
683   return true;
684 }
685 } // end namespace llvm