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