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