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