1 //===- InstrProf.cpp - Instrumented profiling format support --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for clang's instrumentation based PGO and
10 // coverage.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ProfileData/InstrProf.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instruction.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/ProfileData/InstrProfReader.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Compression.h"
38 #include "llvm/Support/Endian.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/ManagedStatic.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/SwapByteOrder.h"
46 #include <algorithm>
47 #include <cassert>
48 #include <cstddef>
49 #include <cstdint>
50 #include <cstring>
51 #include <memory>
52 #include <string>
53 #include <system_error>
54 #include <type_traits>
55 #include <utility>
56 #include <vector>
57 
58 using namespace llvm;
59 
60 static cl::opt<bool> StaticFuncFullModulePrefix(
61     "static-func-full-module-prefix", cl::init(true), cl::Hidden,
62     cl::desc("Use full module build paths in the profile counter names for "
63              "static functions."));
64 
65 // This option is tailored to users that have different top-level directory in
66 // profile-gen and profile-use compilation. Users need to specific the number
67 // of levels to strip. A value larger than the number of directories in the
68 // source file will strip all the directory names and only leave the basename.
69 //
70 // Note current ThinLTO module importing for the indirect-calls assumes
71 // the source directory name not being stripped. A non-zero option value here
72 // can potentially prevent some inter-module indirect-call-promotions.
73 static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
74     "static-func-strip-dirname-prefix", cl::init(0), cl::Hidden,
75     cl::desc("Strip specified level of directory name from source path in "
76              "the profile counter name for static functions."));
77 
78 static std::string getInstrProfErrString(instrprof_error Err,
79                                          const std::string &ErrMsg = "") {
80   std::string Msg;
81   raw_string_ostream OS(Msg);
82 
83   switch (Err) {
84   case instrprof_error::success:
85     OS << "success";
86     break;
87   case instrprof_error::eof:
88     OS << "end of File";
89     break;
90   case instrprof_error::unrecognized_format:
91     OS << "unrecognized instrumentation profile encoding format";
92     break;
93   case instrprof_error::bad_magic:
94     OS << "invalid instrumentation profile data (bad magic)";
95     break;
96   case instrprof_error::bad_header:
97     OS << "invalid instrumentation profile data (file header is corrupt)";
98     break;
99   case instrprof_error::unsupported_version:
100     OS << "unsupported instrumentation profile format version";
101     break;
102   case instrprof_error::unsupported_hash_type:
103     OS << "unsupported instrumentation profile hash type";
104     break;
105   case instrprof_error::too_large:
106     OS << "too much profile data";
107     break;
108   case instrprof_error::truncated:
109     OS << "truncated profile data";
110     break;
111   case instrprof_error::malformed:
112     OS << "malformed instrumentation profile data";
113     break;
114   case instrprof_error::missing_debug_info_for_correlation:
115     OS << "debug info for correlation is required";
116     break;
117   case instrprof_error::unexpected_debug_info_for_correlation:
118     OS << "debug info for correlation is not necessary";
119     break;
120   case instrprof_error::unable_to_correlate_profile:
121     OS << "unable to correlate profile";
122     break;
123   case instrprof_error::invalid_prof:
124     OS << "invalid profile created. Please file a bug "
125           "at: " BUG_REPORT_URL
126           " and include the profraw files that caused this error.";
127     break;
128   case instrprof_error::unknown_function:
129     OS << "no profile data available for function";
130     break;
131   case instrprof_error::hash_mismatch:
132     OS << "function control flow change detected (hash mismatch)";
133     break;
134   case instrprof_error::count_mismatch:
135     OS << "function basic block count change detected (counter mismatch)";
136     break;
137   case instrprof_error::counter_overflow:
138     OS << "counter overflow";
139     break;
140   case instrprof_error::value_site_count_mismatch:
141     OS << "function value site count change detected (counter mismatch)";
142     break;
143   case instrprof_error::compress_failed:
144     OS << "failed to compress data (zlib)";
145     break;
146   case instrprof_error::uncompress_failed:
147     OS << "failed to uncompress data (zlib)";
148     break;
149   case instrprof_error::empty_raw_profile:
150     OS << "empty raw profile file";
151     break;
152   case instrprof_error::zlib_unavailable:
153     OS << "profile uses zlib compression but the profile reader was built "
154           "without zlib support";
155     break;
156   }
157 
158   // If optional error message is not empty, append it to the message.
159   if (!ErrMsg.empty())
160     OS << ": " << ErrMsg;
161 
162   return OS.str();
163 }
164 
165 namespace {
166 
167 // FIXME: This class is only here to support the transition to llvm::Error. It
168 // will be removed once this transition is complete. Clients should prefer to
169 // deal with the Error value directly, rather than converting to error_code.
170 class InstrProfErrorCategoryType : public std::error_category {
171   const char *name() const noexcept override { return "llvm.instrprof"; }
172 
173   std::string message(int IE) const override {
174     return getInstrProfErrString(static_cast<instrprof_error>(IE));
175   }
176 };
177 
178 } // end anonymous namespace
179 
180 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
181 
182 const std::error_category &llvm::instrprof_category() {
183   return *ErrorCategory;
184 }
185 
186 namespace {
187 
188 const char *InstrProfSectNameCommon[] = {
189 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
190   SectNameCommon,
191 #include "llvm/ProfileData/InstrProfData.inc"
192 };
193 
194 const char *InstrProfSectNameCoff[] = {
195 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
196   SectNameCoff,
197 #include "llvm/ProfileData/InstrProfData.inc"
198 };
199 
200 const char *InstrProfSectNamePrefix[] = {
201 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
202   Prefix,
203 #include "llvm/ProfileData/InstrProfData.inc"
204 };
205 
206 } // namespace
207 
208 namespace llvm {
209 
210 cl::opt<bool> DoInstrProfNameCompression(
211     "enable-name-compression",
212     cl::desc("Enable name/filename string compression"), cl::init(true));
213 
214 std::string getInstrProfSectionName(InstrProfSectKind IPSK,
215                                     Triple::ObjectFormatType OF,
216                                     bool AddSegmentInfo) {
217   std::string SectName;
218 
219   if (OF == Triple::MachO && AddSegmentInfo)
220     SectName = InstrProfSectNamePrefix[IPSK];
221 
222   if (OF == Triple::COFF)
223     SectName += InstrProfSectNameCoff[IPSK];
224   else
225     SectName += InstrProfSectNameCommon[IPSK];
226 
227   if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
228     SectName += ",regular,live_support";
229 
230   return SectName;
231 }
232 
233 void SoftInstrProfErrors::addError(instrprof_error IE) {
234   if (IE == instrprof_error::success)
235     return;
236 
237   if (FirstError == instrprof_error::success)
238     FirstError = IE;
239 
240   switch (IE) {
241   case instrprof_error::hash_mismatch:
242     ++NumHashMismatches;
243     break;
244   case instrprof_error::count_mismatch:
245     ++NumCountMismatches;
246     break;
247   case instrprof_error::counter_overflow:
248     ++NumCounterOverflows;
249     break;
250   case instrprof_error::value_site_count_mismatch:
251     ++NumValueSiteCountMismatches;
252     break;
253   default:
254     llvm_unreachable("Not a soft error");
255   }
256 }
257 
258 std::string InstrProfError::message() const {
259   return getInstrProfErrString(Err, Msg);
260 }
261 
262 char InstrProfError::ID = 0;
263 
264 std::string getPGOFuncName(StringRef RawFuncName,
265                            GlobalValue::LinkageTypes Linkage,
266                            StringRef FileName,
267                            uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
268   return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
269 }
270 
271 // Strip NumPrefix level of directory name from PathNameStr. If the number of
272 // directory separators is less than NumPrefix, strip all the directories and
273 // leave base file name only.
274 static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
275   uint32_t Count = NumPrefix;
276   uint32_t Pos = 0, LastPos = 0;
277   for (auto & CI : PathNameStr) {
278     ++Pos;
279     if (llvm::sys::path::is_separator(CI)) {
280       LastPos = Pos;
281       --Count;
282     }
283     if (Count == 0)
284       break;
285   }
286   return PathNameStr.substr(LastPos);
287 }
288 
289 // Return the PGOFuncName. This function has some special handling when called
290 // in LTO optimization. The following only applies when calling in LTO passes
291 // (when \c InLTO is true): LTO's internalization privatizes many global linkage
292 // symbols. This happens after value profile annotation, but those internal
293 // linkage functions should not have a source prefix.
294 // Additionally, for ThinLTO mode, exported internal functions are promoted
295 // and renamed. We need to ensure that the original internal PGO name is
296 // used when computing the GUID that is compared against the profiled GUIDs.
297 // To differentiate compiler generated internal symbols from original ones,
298 // PGOFuncName meta data are created and attached to the original internal
299 // symbols in the value profile annotation step
300 // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
301 // data, its original linkage must be non-internal.
302 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
303   if (!InLTO) {
304     StringRef FileName(F.getParent()->getSourceFileName());
305     uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
306     if (StripLevel < StaticFuncStripDirNamePrefix)
307       StripLevel = StaticFuncStripDirNamePrefix;
308     if (StripLevel)
309       FileName = stripDirPrefix(FileName, StripLevel);
310     return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
311   }
312 
313   // In LTO mode (when InLTO is true), first check if there is a meta data.
314   if (MDNode *MD = getPGOFuncNameMetadata(F)) {
315     StringRef S = cast<MDString>(MD->getOperand(0))->getString();
316     return S.str();
317   }
318 
319   // If there is no meta data, the function must be a global before the value
320   // profile annotation pass. Its current linkage may be internal if it is
321   // internalized in LTO mode.
322   return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
323 }
324 
325 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
326   if (FileName.empty())
327     return PGOFuncName;
328   // Drop the file name including ':'. See also getPGOFuncName.
329   if (PGOFuncName.startswith(FileName))
330     PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
331   return PGOFuncName;
332 }
333 
334 // \p FuncName is the string used as profile lookup key for the function. A
335 // symbol is created to hold the name. Return the legalized symbol name.
336 std::string getPGOFuncNameVarName(StringRef FuncName,
337                                   GlobalValue::LinkageTypes Linkage) {
338   std::string VarName = std::string(getInstrProfNameVarPrefix());
339   VarName += FuncName;
340 
341   if (!GlobalValue::isLocalLinkage(Linkage))
342     return VarName;
343 
344   // Now fix up illegal chars in local VarName that may upset the assembler.
345   const char *InvalidChars = "-:<>/\"'";
346   size_t found = VarName.find_first_of(InvalidChars);
347   while (found != std::string::npos) {
348     VarName[found] = '_';
349     found = VarName.find_first_of(InvalidChars, found + 1);
350   }
351   return VarName;
352 }
353 
354 GlobalVariable *createPGOFuncNameVar(Module &M,
355                                      GlobalValue::LinkageTypes Linkage,
356                                      StringRef PGOFuncName) {
357   // We generally want to match the function's linkage, but available_externally
358   // and extern_weak both have the wrong semantics, and anything that doesn't
359   // need to link across compilation units doesn't need to be visible at all.
360   if (Linkage == GlobalValue::ExternalWeakLinkage)
361     Linkage = GlobalValue::LinkOnceAnyLinkage;
362   else if (Linkage == GlobalValue::AvailableExternallyLinkage)
363     Linkage = GlobalValue::LinkOnceODRLinkage;
364   else if (Linkage == GlobalValue::InternalLinkage ||
365            Linkage == GlobalValue::ExternalLinkage)
366     Linkage = GlobalValue::PrivateLinkage;
367 
368   auto *Value =
369       ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
370   auto FuncNameVar =
371       new GlobalVariable(M, Value->getType(), true, Linkage, Value,
372                          getPGOFuncNameVarName(PGOFuncName, Linkage));
373 
374   // Hide the symbol so that we correctly get a copy for each executable.
375   if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
376     FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
377 
378   return FuncNameVar;
379 }
380 
381 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
382   return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
383 }
384 
385 Error InstrProfSymtab::create(Module &M, bool InLTO) {
386   for (Function &F : M) {
387     // Function may not have a name: like using asm("") to overwrite the name.
388     // Ignore in this case.
389     if (!F.hasName())
390       continue;
391     const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
392     if (Error E = addFuncName(PGOFuncName))
393       return E;
394     MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
395     // In ThinLTO, local function may have been promoted to global and have
396     // suffix ".llvm." added to the function name. We need to add the
397     // stripped function name to the symbol table so that we can find a match
398     // from profile.
399     //
400     // We may have other suffixes similar as ".llvm." which are needed to
401     // be stripped before the matching, but ".__uniq." suffix which is used
402     // to differentiate internal linkage functions in different modules
403     // should be kept. Now this is the only suffix with the pattern ".xxx"
404     // which is kept before matching.
405     const std::string UniqSuffix = ".__uniq.";
406     auto pos = PGOFuncName.find(UniqSuffix);
407     // Search '.' after ".__uniq." if ".__uniq." exists, otherwise
408     // search '.' from the beginning.
409     if (pos != std::string::npos)
410       pos += UniqSuffix.length();
411     else
412       pos = 0;
413     pos = PGOFuncName.find('.', pos);
414     if (pos != std::string::npos && pos != 0) {
415       const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
416       if (Error E = addFuncName(OtherFuncName))
417         return E;
418       MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
419     }
420   }
421   Sorted = false;
422   finalizeSymtab();
423   return Error::success();
424 }
425 
426 uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) {
427   finalizeSymtab();
428   auto It = partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) {
429     return A.first < Address;
430   });
431   // Raw function pointer collected by value profiler may be from
432   // external functions that are not instrumented. They won't have
433   // mapping data to be used by the deserializer. Force the value to
434   // be 0 in this case.
435   if (It != AddrToMD5Map.end() && It->first == Address)
436     return (uint64_t)It->second;
437   return 0;
438 }
439 
440 Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
441                                 bool doCompression, std::string &Result) {
442   assert(!NameStrs.empty() && "No name data to emit");
443 
444   uint8_t Header[16], *P = Header;
445   std::string UncompressedNameStrings =
446       join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
447 
448   assert(StringRef(UncompressedNameStrings)
449                  .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
450          "PGO name is invalid (contains separator token)");
451 
452   unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
453   P += EncLen;
454 
455   auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
456     EncLen = encodeULEB128(CompressedLen, P);
457     P += EncLen;
458     char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
459     unsigned HeaderLen = P - &Header[0];
460     Result.append(HeaderStr, HeaderLen);
461     Result += InputStr;
462     return Error::success();
463   };
464 
465   if (!doCompression) {
466     return WriteStringToResult(0, UncompressedNameStrings);
467   }
468 
469   SmallString<128> CompressedNameStrings;
470   compression::zlib::compress(StringRef(UncompressedNameStrings),
471                               CompressedNameStrings,
472                               compression::zlib::BestSizeCompression);
473 
474   return WriteStringToResult(CompressedNameStrings.size(),
475                              CompressedNameStrings);
476 }
477 
478 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
479   auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
480   StringRef NameStr =
481       Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
482   return NameStr;
483 }
484 
485 Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
486                                 std::string &Result, bool doCompression) {
487   std::vector<std::string> NameStrs;
488   for (auto *NameVar : NameVars) {
489     NameStrs.push_back(std::string(getPGOFuncNameVarInitializer(NameVar)));
490   }
491   return collectPGOFuncNameStrings(
492       NameStrs, compression::zlib::isAvailable() && doCompression, Result);
493 }
494 
495 Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
496   const uint8_t *P = NameStrings.bytes_begin();
497   const uint8_t *EndP = NameStrings.bytes_end();
498   while (P < EndP) {
499     uint32_t N;
500     uint64_t UncompressedSize = decodeULEB128(P, &N);
501     P += N;
502     uint64_t CompressedSize = decodeULEB128(P, &N);
503     P += N;
504     bool isCompressed = (CompressedSize != 0);
505     SmallString<128> UncompressedNameStrings;
506     StringRef NameStrings;
507     if (isCompressed) {
508       if (!llvm::compression::zlib::isAvailable())
509         return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
510 
511       StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
512                                       CompressedSize);
513       if (Error E = compression::zlib::uncompress(CompressedNameStrings,
514                                                   UncompressedNameStrings,
515                                                   UncompressedSize)) {
516         consumeError(std::move(E));
517         return make_error<InstrProfError>(instrprof_error::uncompress_failed);
518       }
519       P += CompressedSize;
520       NameStrings = StringRef(UncompressedNameStrings.data(),
521                               UncompressedNameStrings.size());
522     } else {
523       NameStrings =
524           StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
525       P += UncompressedSize;
526     }
527     // Now parse the name strings.
528     SmallVector<StringRef, 0> Names;
529     NameStrings.split(Names, getInstrProfNameSeparator());
530     for (StringRef &Name : Names)
531       if (Error E = Symtab.addFuncName(Name))
532         return E;
533 
534     while (P < EndP && *P == 0)
535       P++;
536   }
537   return Error::success();
538 }
539 
540 void InstrProfRecord::accumulateCounts(CountSumOrPercent &Sum) const {
541   uint64_t FuncSum = 0;
542   Sum.NumEntries += Counts.size();
543   for (uint64_t Count : Counts)
544     FuncSum += Count;
545   Sum.CountSum += FuncSum;
546 
547   for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
548     uint64_t KindSum = 0;
549     uint32_t NumValueSites = getNumValueSites(VK);
550     for (size_t I = 0; I < NumValueSites; ++I) {
551       uint32_t NV = getNumValueDataForSite(VK, I);
552       std::unique_ptr<InstrProfValueData[]> VD = getValueForSite(VK, I);
553       for (uint32_t V = 0; V < NV; V++)
554         KindSum += VD[V].Count;
555     }
556     Sum.ValueCounts[VK] += KindSum;
557   }
558 }
559 
560 void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord &Input,
561                                        uint32_t ValueKind,
562                                        OverlapStats &Overlap,
563                                        OverlapStats &FuncLevelOverlap) {
564   this->sortByTargetValues();
565   Input.sortByTargetValues();
566   double Score = 0.0f, FuncLevelScore = 0.0f;
567   auto I = ValueData.begin();
568   auto IE = ValueData.end();
569   auto J = Input.ValueData.begin();
570   auto JE = Input.ValueData.end();
571   while (I != IE && J != JE) {
572     if (I->Value == J->Value) {
573       Score += OverlapStats::score(I->Count, J->Count,
574                                    Overlap.Base.ValueCounts[ValueKind],
575                                    Overlap.Test.ValueCounts[ValueKind]);
576       FuncLevelScore += OverlapStats::score(
577           I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind],
578           FuncLevelOverlap.Test.ValueCounts[ValueKind]);
579       ++I;
580     } else if (I->Value < J->Value) {
581       ++I;
582       continue;
583     }
584     ++J;
585   }
586   Overlap.Overlap.ValueCounts[ValueKind] += Score;
587   FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
588 }
589 
590 // Return false on mismatch.
591 void InstrProfRecord::overlapValueProfData(uint32_t ValueKind,
592                                            InstrProfRecord &Other,
593                                            OverlapStats &Overlap,
594                                            OverlapStats &FuncLevelOverlap) {
595   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
596   assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
597   if (!ThisNumValueSites)
598     return;
599 
600   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
601       getOrCreateValueSitesForKind(ValueKind);
602   MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
603       Other.getValueSitesForKind(ValueKind);
604   for (uint32_t I = 0; I < ThisNumValueSites; I++)
605     ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap,
606                                FuncLevelOverlap);
607 }
608 
609 void InstrProfRecord::overlap(InstrProfRecord &Other, OverlapStats &Overlap,
610                               OverlapStats &FuncLevelOverlap,
611                               uint64_t ValueCutoff) {
612   // FuncLevel CountSum for other should already computed and nonzero.
613   assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
614   accumulateCounts(FuncLevelOverlap.Base);
615   bool Mismatch = (Counts.size() != Other.Counts.size());
616 
617   // Check if the value profiles mismatch.
618   if (!Mismatch) {
619     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
620       uint32_t ThisNumValueSites = getNumValueSites(Kind);
621       uint32_t OtherNumValueSites = Other.getNumValueSites(Kind);
622       if (ThisNumValueSites != OtherNumValueSites) {
623         Mismatch = true;
624         break;
625       }
626     }
627   }
628   if (Mismatch) {
629     Overlap.addOneMismatch(FuncLevelOverlap.Test);
630     return;
631   }
632 
633   // Compute overlap for value counts.
634   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
635     overlapValueProfData(Kind, Other, Overlap, FuncLevelOverlap);
636 
637   double Score = 0.0;
638   uint64_t MaxCount = 0;
639   // Compute overlap for edge counts.
640   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
641     Score += OverlapStats::score(Counts[I], Other.Counts[I],
642                                  Overlap.Base.CountSum, Overlap.Test.CountSum);
643     MaxCount = std::max(Other.Counts[I], MaxCount);
644   }
645   Overlap.Overlap.CountSum += Score;
646   Overlap.Overlap.NumEntries += 1;
647 
648   if (MaxCount >= ValueCutoff) {
649     double FuncScore = 0.0;
650     for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
651       FuncScore += OverlapStats::score(Counts[I], Other.Counts[I],
652                                        FuncLevelOverlap.Base.CountSum,
653                                        FuncLevelOverlap.Test.CountSum);
654     FuncLevelOverlap.Overlap.CountSum = FuncScore;
655     FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
656     FuncLevelOverlap.Valid = true;
657   }
658 }
659 
660 void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
661                                      uint64_t Weight,
662                                      function_ref<void(instrprof_error)> Warn) {
663   this->sortByTargetValues();
664   Input.sortByTargetValues();
665   auto I = ValueData.begin();
666   auto IE = ValueData.end();
667   for (const InstrProfValueData &J : Input.ValueData) {
668     while (I != IE && I->Value < J.Value)
669       ++I;
670     if (I != IE && I->Value == J.Value) {
671       bool Overflowed;
672       I->Count = SaturatingMultiplyAdd(J.Count, Weight, I->Count, &Overflowed);
673       if (Overflowed)
674         Warn(instrprof_error::counter_overflow);
675       ++I;
676       continue;
677     }
678     ValueData.insert(I, J);
679   }
680 }
681 
682 void InstrProfValueSiteRecord::scale(uint64_t N, uint64_t D,
683                                      function_ref<void(instrprof_error)> Warn) {
684   for (InstrProfValueData &I : ValueData) {
685     bool Overflowed;
686     I.Count = SaturatingMultiply(I.Count, N, &Overflowed) / D;
687     if (Overflowed)
688       Warn(instrprof_error::counter_overflow);
689   }
690 }
691 
692 // Merge Value Profile data from Src record to this record for ValueKind.
693 // Scale merged value counts by \p Weight.
694 void InstrProfRecord::mergeValueProfData(
695     uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
696     function_ref<void(instrprof_error)> Warn) {
697   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
698   uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
699   if (ThisNumValueSites != OtherNumValueSites) {
700     Warn(instrprof_error::value_site_count_mismatch);
701     return;
702   }
703   if (!ThisNumValueSites)
704     return;
705   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
706       getOrCreateValueSitesForKind(ValueKind);
707   MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
708       Src.getValueSitesForKind(ValueKind);
709   for (uint32_t I = 0; I < ThisNumValueSites; I++)
710     ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
711 }
712 
713 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
714                             function_ref<void(instrprof_error)> Warn) {
715   // If the number of counters doesn't match we either have bad data
716   // or a hash collision.
717   if (Counts.size() != Other.Counts.size()) {
718     Warn(instrprof_error::count_mismatch);
719     return;
720   }
721 
722   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
723     bool Overflowed;
724     Counts[I] =
725         SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
726     if (Overflowed)
727       Warn(instrprof_error::counter_overflow);
728   }
729 
730   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
731     mergeValueProfData(Kind, Other, Weight, Warn);
732 }
733 
734 void InstrProfRecord::scaleValueProfData(
735     uint32_t ValueKind, uint64_t N, uint64_t D,
736     function_ref<void(instrprof_error)> Warn) {
737   for (auto &R : getValueSitesForKind(ValueKind))
738     R.scale(N, D, Warn);
739 }
740 
741 void InstrProfRecord::scale(uint64_t N, uint64_t D,
742                             function_ref<void(instrprof_error)> Warn) {
743   assert(D != 0 && "D cannot be 0");
744   for (auto &Count : this->Counts) {
745     bool Overflowed;
746     Count = SaturatingMultiply(Count, N, &Overflowed) / D;
747     if (Overflowed)
748       Warn(instrprof_error::counter_overflow);
749   }
750   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
751     scaleValueProfData(Kind, N, D, Warn);
752 }
753 
754 // Map indirect call target name hash to name string.
755 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
756                                      InstrProfSymtab *SymTab) {
757   if (!SymTab)
758     return Value;
759 
760   if (ValueKind == IPVK_IndirectCallTarget)
761     return SymTab->getFunctionHashFromAddress(Value);
762 
763   return Value;
764 }
765 
766 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
767                                    InstrProfValueData *VData, uint32_t N,
768                                    InstrProfSymtab *ValueMap) {
769   for (uint32_t I = 0; I < N; I++) {
770     VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
771   }
772   std::vector<InstrProfValueSiteRecord> &ValueSites =
773       getOrCreateValueSitesForKind(ValueKind);
774   if (N == 0)
775     ValueSites.emplace_back();
776   else
777     ValueSites.emplace_back(VData, VData + N);
778 }
779 
780 #define INSTR_PROF_COMMON_API_IMPL
781 #include "llvm/ProfileData/InstrProfData.inc"
782 
783 /*!
784  * ValueProfRecordClosure Interface implementation for  InstrProfRecord
785  *  class. These C wrappers are used as adaptors so that C++ code can be
786  *  invoked as callbacks.
787  */
788 uint32_t getNumValueKindsInstrProf(const void *Record) {
789   return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
790 }
791 
792 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
793   return reinterpret_cast<const InstrProfRecord *>(Record)
794       ->getNumValueSites(VKind);
795 }
796 
797 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
798   return reinterpret_cast<const InstrProfRecord *>(Record)
799       ->getNumValueData(VKind);
800 }
801 
802 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
803                                          uint32_t S) {
804   return reinterpret_cast<const InstrProfRecord *>(R)
805       ->getNumValueDataForSite(VK, S);
806 }
807 
808 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
809                               uint32_t K, uint32_t S) {
810   reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
811 }
812 
813 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
814   ValueProfData *VD =
815       (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
816   memset(VD, 0, TotalSizeInBytes);
817   return VD;
818 }
819 
820 static ValueProfRecordClosure InstrProfRecordClosure = {
821     nullptr,
822     getNumValueKindsInstrProf,
823     getNumValueSitesInstrProf,
824     getNumValueDataInstrProf,
825     getNumValueDataForSiteInstrProf,
826     nullptr,
827     getValueForSiteInstrProf,
828     allocValueProfDataInstrProf};
829 
830 // Wrapper implementation using the closure mechanism.
831 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
832   auto Closure = InstrProfRecordClosure;
833   Closure.Record = &Record;
834   return getValueProfDataSize(&Closure);
835 }
836 
837 // Wrapper implementation using the closure mechanism.
838 std::unique_ptr<ValueProfData>
839 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
840   InstrProfRecordClosure.Record = &Record;
841 
842   std::unique_ptr<ValueProfData> VPD(
843       serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
844   return VPD;
845 }
846 
847 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
848                                     InstrProfSymtab *SymTab) {
849   Record.reserveSites(Kind, NumValueSites);
850 
851   InstrProfValueData *ValueData = getValueProfRecordValueData(this);
852   for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
853     uint8_t ValueDataCount = this->SiteCountArray[VSite];
854     Record.addValueData(Kind, VSite, ValueData, ValueDataCount, SymTab);
855     ValueData += ValueDataCount;
856   }
857 }
858 
859 // For writing/serializing,  Old is the host endianness, and  New is
860 // byte order intended on disk. For Reading/deserialization, Old
861 // is the on-disk source endianness, and New is the host endianness.
862 void ValueProfRecord::swapBytes(support::endianness Old,
863                                 support::endianness New) {
864   using namespace support;
865 
866   if (Old == New)
867     return;
868 
869   if (getHostEndianness() != Old) {
870     sys::swapByteOrder<uint32_t>(NumValueSites);
871     sys::swapByteOrder<uint32_t>(Kind);
872   }
873   uint32_t ND = getValueProfRecordNumValueData(this);
874   InstrProfValueData *VD = getValueProfRecordValueData(this);
875 
876   // No need to swap byte array: SiteCountArrray.
877   for (uint32_t I = 0; I < ND; I++) {
878     sys::swapByteOrder<uint64_t>(VD[I].Value);
879     sys::swapByteOrder<uint64_t>(VD[I].Count);
880   }
881   if (getHostEndianness() == Old) {
882     sys::swapByteOrder<uint32_t>(NumValueSites);
883     sys::swapByteOrder<uint32_t>(Kind);
884   }
885 }
886 
887 void ValueProfData::deserializeTo(InstrProfRecord &Record,
888                                   InstrProfSymtab *SymTab) {
889   if (NumValueKinds == 0)
890     return;
891 
892   ValueProfRecord *VR = getFirstValueProfRecord(this);
893   for (uint32_t K = 0; K < NumValueKinds; K++) {
894     VR->deserializeTo(Record, SymTab);
895     VR = getValueProfRecordNext(VR);
896   }
897 }
898 
899 template <class T>
900 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
901   using namespace support;
902 
903   if (Orig == little)
904     return endian::readNext<T, little, unaligned>(D);
905   else
906     return endian::readNext<T, big, unaligned>(D);
907 }
908 
909 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
910   return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
911                                             ValueProfData());
912 }
913 
914 Error ValueProfData::checkIntegrity() {
915   if (NumValueKinds > IPVK_Last + 1)
916     return make_error<InstrProfError>(
917         instrprof_error::malformed, "number of value profile kinds is invalid");
918   // Total size needs to be multiple of quadword size.
919   if (TotalSize % sizeof(uint64_t))
920     return make_error<InstrProfError>(
921         instrprof_error::malformed, "total size is not multiples of quardword");
922 
923   ValueProfRecord *VR = getFirstValueProfRecord(this);
924   for (uint32_t K = 0; K < this->NumValueKinds; K++) {
925     if (VR->Kind > IPVK_Last)
926       return make_error<InstrProfError>(instrprof_error::malformed,
927                                         "value kind is invalid");
928     VR = getValueProfRecordNext(VR);
929     if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
930       return make_error<InstrProfError>(
931           instrprof_error::malformed,
932           "value profile address is greater than total size");
933   }
934   return Error::success();
935 }
936 
937 Expected<std::unique_ptr<ValueProfData>>
938 ValueProfData::getValueProfData(const unsigned char *D,
939                                 const unsigned char *const BufferEnd,
940                                 support::endianness Endianness) {
941   using namespace support;
942 
943   if (D + sizeof(ValueProfData) > BufferEnd)
944     return make_error<InstrProfError>(instrprof_error::truncated);
945 
946   const unsigned char *Header = D;
947   uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
948   if (D + TotalSize > BufferEnd)
949     return make_error<InstrProfError>(instrprof_error::too_large);
950 
951   std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
952   memcpy(VPD.get(), D, TotalSize);
953   // Byte swap.
954   VPD->swapBytesToHost(Endianness);
955 
956   Error E = VPD->checkIntegrity();
957   if (E)
958     return std::move(E);
959 
960   return std::move(VPD);
961 }
962 
963 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
964   using namespace support;
965 
966   if (Endianness == getHostEndianness())
967     return;
968 
969   sys::swapByteOrder<uint32_t>(TotalSize);
970   sys::swapByteOrder<uint32_t>(NumValueKinds);
971 
972   ValueProfRecord *VR = getFirstValueProfRecord(this);
973   for (uint32_t K = 0; K < NumValueKinds; K++) {
974     VR->swapBytes(Endianness, getHostEndianness());
975     VR = getValueProfRecordNext(VR);
976   }
977 }
978 
979 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
980   using namespace support;
981 
982   if (Endianness == getHostEndianness())
983     return;
984 
985   ValueProfRecord *VR = getFirstValueProfRecord(this);
986   for (uint32_t K = 0; K < NumValueKinds; K++) {
987     ValueProfRecord *NVR = getValueProfRecordNext(VR);
988     VR->swapBytes(getHostEndianness(), Endianness);
989     VR = NVR;
990   }
991   sys::swapByteOrder<uint32_t>(TotalSize);
992   sys::swapByteOrder<uint32_t>(NumValueKinds);
993 }
994 
995 void annotateValueSite(Module &M, Instruction &Inst,
996                        const InstrProfRecord &InstrProfR,
997                        InstrProfValueKind ValueKind, uint32_t SiteIdx,
998                        uint32_t MaxMDCount) {
999   uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
1000   if (!NV)
1001     return;
1002 
1003   uint64_t Sum = 0;
1004   std::unique_ptr<InstrProfValueData[]> VD =
1005       InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
1006 
1007   ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
1008   annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
1009 }
1010 
1011 void annotateValueSite(Module &M, Instruction &Inst,
1012                        ArrayRef<InstrProfValueData> VDs,
1013                        uint64_t Sum, InstrProfValueKind ValueKind,
1014                        uint32_t MaxMDCount) {
1015   LLVMContext &Ctx = M.getContext();
1016   MDBuilder MDHelper(Ctx);
1017   SmallVector<Metadata *, 3> Vals;
1018   // Tag
1019   Vals.push_back(MDHelper.createString("VP"));
1020   // Value Kind
1021   Vals.push_back(MDHelper.createConstant(
1022       ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
1023   // Total Count
1024   Vals.push_back(
1025       MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
1026 
1027   // Value Profile Data
1028   uint32_t MDCount = MaxMDCount;
1029   for (auto &VD : VDs) {
1030     Vals.push_back(MDHelper.createConstant(
1031         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
1032     Vals.push_back(MDHelper.createConstant(
1033         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
1034     if (--MDCount == 0)
1035       break;
1036   }
1037   Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
1038 }
1039 
1040 bool getValueProfDataFromInst(const Instruction &Inst,
1041                               InstrProfValueKind ValueKind,
1042                               uint32_t MaxNumValueData,
1043                               InstrProfValueData ValueData[],
1044                               uint32_t &ActualNumValueData, uint64_t &TotalC,
1045                               bool GetNoICPValue) {
1046   MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
1047   if (!MD)
1048     return false;
1049 
1050   unsigned NOps = MD->getNumOperands();
1051 
1052   if (NOps < 5)
1053     return false;
1054 
1055   // Operand 0 is a string tag "VP":
1056   MDString *Tag = cast<MDString>(MD->getOperand(0));
1057   if (!Tag)
1058     return false;
1059 
1060   if (!Tag->getString().equals("VP"))
1061     return false;
1062 
1063   // Now check kind:
1064   ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
1065   if (!KindInt)
1066     return false;
1067   if (KindInt->getZExtValue() != ValueKind)
1068     return false;
1069 
1070   // Get total count
1071   ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
1072   if (!TotalCInt)
1073     return false;
1074   TotalC = TotalCInt->getZExtValue();
1075 
1076   ActualNumValueData = 0;
1077 
1078   for (unsigned I = 3; I < NOps; I += 2) {
1079     if (ActualNumValueData >= MaxNumValueData)
1080       break;
1081     ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
1082     ConstantInt *Count =
1083         mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
1084     if (!Value || !Count)
1085       return false;
1086     uint64_t CntValue = Count->getZExtValue();
1087     if (!GetNoICPValue && (CntValue == NOMORE_ICP_MAGICNUM))
1088       continue;
1089     ValueData[ActualNumValueData].Value = Value->getZExtValue();
1090     ValueData[ActualNumValueData].Count = CntValue;
1091     ActualNumValueData++;
1092   }
1093   return true;
1094 }
1095 
1096 MDNode *getPGOFuncNameMetadata(const Function &F) {
1097   return F.getMetadata(getPGOFuncNameMetadataName());
1098 }
1099 
1100 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
1101   // Only for internal linkage functions.
1102   if (PGOFuncName == F.getName())
1103       return;
1104   // Don't create duplicated meta-data.
1105   if (getPGOFuncNameMetadata(F))
1106     return;
1107   LLVMContext &C = F.getContext();
1108   MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
1109   F.setMetadata(getPGOFuncNameMetadataName(), N);
1110 }
1111 
1112 bool needsComdatForCounter(const Function &F, const Module &M) {
1113   if (F.hasComdat())
1114     return true;
1115 
1116   if (!Triple(M.getTargetTriple()).supportsCOMDAT())
1117     return false;
1118 
1119   // See createPGOFuncNameVar for more details. To avoid link errors, profile
1120   // counters for function with available_externally linkage needs to be changed
1121   // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
1122   // created. Without using comdat, duplicate entries won't be removed by the
1123   // linker leading to increased data segement size and raw profile size. Even
1124   // worse, since the referenced counter from profile per-function data object
1125   // will be resolved to the common strong definition, the profile counts for
1126   // available_externally functions will end up being duplicated in raw profile
1127   // data. This can result in distorted profile as the counts of those dups
1128   // will be accumulated by the profile merger.
1129   GlobalValue::LinkageTypes Linkage = F.getLinkage();
1130   if (Linkage != GlobalValue::ExternalWeakLinkage &&
1131       Linkage != GlobalValue::AvailableExternallyLinkage)
1132     return false;
1133 
1134   return true;
1135 }
1136 
1137 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
1138 bool isIRPGOFlagSet(const Module *M) {
1139   auto IRInstrVar =
1140       M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1141   if (!IRInstrVar || IRInstrVar->hasLocalLinkage())
1142     return false;
1143 
1144   // For CSPGO+LTO, this variable might be marked as non-prevailing and we only
1145   // have the decl.
1146   if (IRInstrVar->isDeclaration())
1147     return true;
1148 
1149   // Check if the flag is set.
1150   if (!IRInstrVar->hasInitializer())
1151     return false;
1152 
1153   auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
1154   if (!InitVal)
1155     return false;
1156   return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
1157 }
1158 
1159 // Check if we can safely rename this Comdat function.
1160 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
1161   if (F.getName().empty())
1162     return false;
1163   if (!needsComdatForCounter(F, *(F.getParent())))
1164     return false;
1165   // Unsafe to rename the address-taken function (which can be used in
1166   // function comparison).
1167   if (CheckAddressTaken && F.hasAddressTaken())
1168     return false;
1169   // Only safe to do if this function may be discarded if it is not used
1170   // in the compilation unit.
1171   if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
1172     return false;
1173 
1174   // For AvailableExternallyLinkage functions.
1175   if (!F.hasComdat()) {
1176     assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
1177     return true;
1178   }
1179   return true;
1180 }
1181 
1182 // Create the variable for the profile file name.
1183 void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
1184   if (InstrProfileOutput.empty())
1185     return;
1186   Constant *ProfileNameConst =
1187       ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true);
1188   GlobalVariable *ProfileNameVar = new GlobalVariable(
1189       M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
1190       ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
1191   Triple TT(M.getTargetTriple());
1192   if (TT.supportsCOMDAT()) {
1193     ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
1194     ProfileNameVar->setComdat(M.getOrInsertComdat(
1195         StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
1196   }
1197 }
1198 
1199 Error OverlapStats::accumulateCounts(const std::string &BaseFilename,
1200                                      const std::string &TestFilename,
1201                                      bool IsCS) {
1202   auto getProfileSum = [IsCS](const std::string &Filename,
1203                               CountSumOrPercent &Sum) -> Error {
1204     auto ReaderOrErr = InstrProfReader::create(Filename);
1205     if (Error E = ReaderOrErr.takeError()) {
1206       return E;
1207     }
1208     auto Reader = std::move(ReaderOrErr.get());
1209     Reader->accumulateCounts(Sum, IsCS);
1210     return Error::success();
1211   };
1212   auto Ret = getProfileSum(BaseFilename, Base);
1213   if (Ret)
1214     return Ret;
1215   Ret = getProfileSum(TestFilename, Test);
1216   if (Ret)
1217     return Ret;
1218   this->BaseFilename = &BaseFilename;
1219   this->TestFilename = &TestFilename;
1220   Valid = true;
1221   return Error::success();
1222 }
1223 
1224 void OverlapStats::addOneMismatch(const CountSumOrPercent &MismatchFunc) {
1225   Mismatch.NumEntries += 1;
1226   Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
1227   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1228     if (Test.ValueCounts[I] >= 1.0f)
1229       Mismatch.ValueCounts[I] +=
1230           MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
1231   }
1232 }
1233 
1234 void OverlapStats::addOneUnique(const CountSumOrPercent &UniqueFunc) {
1235   Unique.NumEntries += 1;
1236   Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
1237   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1238     if (Test.ValueCounts[I] >= 1.0f)
1239       Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
1240   }
1241 }
1242 
1243 void OverlapStats::dump(raw_fd_ostream &OS) const {
1244   if (!Valid)
1245     return;
1246 
1247   const char *EntryName =
1248       (Level == ProgramLevel ? "functions" : "edge counters");
1249   if (Level == ProgramLevel) {
1250     OS << "Profile overlap infomation for base_profile: " << *BaseFilename
1251        << " and test_profile: " << *TestFilename << "\nProgram level:\n";
1252   } else {
1253     OS << "Function level:\n"
1254        << "  Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
1255   }
1256 
1257   OS << "  # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
1258   if (Mismatch.NumEntries)
1259     OS << "  # of " << EntryName << " mismatch: " << Mismatch.NumEntries
1260        << "\n";
1261   if (Unique.NumEntries)
1262     OS << "  # of " << EntryName
1263        << " only in test_profile: " << Unique.NumEntries << "\n";
1264 
1265   OS << "  Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100)
1266      << "\n";
1267   if (Mismatch.NumEntries)
1268     OS << "  Mismatched count percentage (Edge): "
1269        << format("%.3f%%", Mismatch.CountSum * 100) << "\n";
1270   if (Unique.NumEntries)
1271     OS << "  Percentage of Edge profile only in test_profile: "
1272        << format("%.3f%%", Unique.CountSum * 100) << "\n";
1273   OS << "  Edge profile base count sum: " << format("%.0f", Base.CountSum)
1274      << "\n"
1275      << "  Edge profile test count sum: " << format("%.0f", Test.CountSum)
1276      << "\n";
1277 
1278   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1279     if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
1280       continue;
1281     char ProfileKindName[20];
1282     switch (I) {
1283     case IPVK_IndirectCallTarget:
1284       strncpy(ProfileKindName, "IndirectCall", 19);
1285       break;
1286     case IPVK_MemOPSize:
1287       strncpy(ProfileKindName, "MemOP", 19);
1288       break;
1289     default:
1290       snprintf(ProfileKindName, 19, "VP[%d]", I);
1291       break;
1292     }
1293     OS << "  " << ProfileKindName
1294        << " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100)
1295        << "\n";
1296     if (Mismatch.NumEntries)
1297       OS << "  Mismatched count percentage (" << ProfileKindName
1298          << "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n";
1299     if (Unique.NumEntries)
1300       OS << "  Percentage of " << ProfileKindName
1301          << " profile only in test_profile: "
1302          << format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n";
1303     OS << "  " << ProfileKindName
1304        << " profile base count sum: " << format("%.0f", Base.ValueCounts[I])
1305        << "\n"
1306        << "  " << ProfileKindName
1307        << " profile test count sum: " << format("%.0f", Test.ValueCounts[I])
1308        << "\n";
1309   }
1310 }
1311 
1312 namespace IndexedInstrProf {
1313 // A C++14 compatible version of the offsetof macro.
1314 template <typename T1, typename T2>
1315 inline size_t constexpr offsetOf(T1 T2::*Member) {
1316   constexpr T2 Object{};
1317   return size_t(&(Object.*Member)) - size_t(&Object);
1318 }
1319 
1320 static inline uint64_t read(const unsigned char *Buffer, size_t Offset) {
1321   return *reinterpret_cast<const uint64_t *>(Buffer + Offset);
1322 }
1323 
1324 uint64_t Header::formatVersion() const {
1325   using namespace support;
1326   return endian::byte_swap<uint64_t, little>(Version);
1327 }
1328 
1329 Expected<Header> Header::readFromBuffer(const unsigned char *Buffer) {
1330   using namespace support;
1331   static_assert(std::is_standard_layout<Header>::value,
1332                 "The header should be standard layout type since we use offset "
1333                 "of fields to read.");
1334   Header H;
1335 
1336   H.Magic = read(Buffer, offsetOf(&Header::Magic));
1337   // Check the magic number.
1338   uint64_t Magic = endian::byte_swap<uint64_t, little>(H.Magic);
1339   if (Magic != IndexedInstrProf::Magic)
1340     return make_error<InstrProfError>(instrprof_error::bad_magic);
1341 
1342   // Read the version.
1343   H.Version = read(Buffer, offsetOf(&Header::Version));
1344   if (GET_VERSION(H.formatVersion()) >
1345       IndexedInstrProf::ProfVersion::CurrentVersion)
1346     return make_error<InstrProfError>(instrprof_error::unsupported_version);
1347 
1348   switch (GET_VERSION(H.formatVersion())) {
1349     // When a new field is added in the header add a case statement here to
1350     // populate it.
1351     static_assert(
1352         IndexedInstrProf::ProfVersion::CurrentVersion == Version8,
1353         "Please update the reading code below if a new field has been added, "
1354         "if not add a case statement to fall through to the latest version.");
1355   case 8ull:
1356     H.MemProfOffset = read(Buffer, offsetOf(&Header::MemProfOffset));
1357     LLVM_FALLTHROUGH;
1358   default: // Version7 (when the backwards compatible header was introduced).
1359     H.HashType = read(Buffer, offsetOf(&Header::HashType));
1360     H.HashOffset = read(Buffer, offsetOf(&Header::HashOffset));
1361   }
1362 
1363   return H;
1364 }
1365 
1366 size_t Header::size() const {
1367   switch (GET_VERSION(formatVersion())) {
1368     // When a new field is added to the header add a case statement here to
1369     // compute the size as offset of the new field + size of the new field. This
1370     // relies on the field being added to the end of the list.
1371     static_assert(IndexedInstrProf::ProfVersion::CurrentVersion == Version8,
1372                   "Please update the size computation below if a new field has "
1373                   "been added to the header, if not add a case statement to "
1374                   "fall through to the latest version.");
1375   case 8ull:
1376     return offsetOf(&Header::MemProfOffset) + sizeof(Header::MemProfOffset);
1377   default: // Version7 (when the backwards compatible header was introduced).
1378     return offsetOf(&Header::HashOffset) + sizeof(Header::HashOffset);
1379   }
1380 }
1381 
1382 } // namespace IndexedInstrProf
1383 
1384 } // end namespace llvm
1385