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