1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
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 // llvm-profdata merges .profdata files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/SmallSet.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/ProfileData/InstrProfReader.h"
18 #include "llvm/ProfileData/InstrProfWriter.h"
19 #include "llvm/ProfileData/ProfileCommon.h"
20 #include "llvm/ProfileData/SampleProfReader.h"
21 #include "llvm/ProfileData/SampleProfWriter.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/FormattedStream.h"
27 #include "llvm/Support/InitLLVM.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/ThreadPool.h"
31 #include "llvm/Support/Threading.h"
32 #include "llvm/Support/WithColor.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <algorithm>
35 
36 using namespace llvm;
37 
38 enum ProfileFormat {
39   PF_None = 0,
40   PF_Text,
41   PF_Compact_Binary,
42   PF_Ext_Binary,
43   PF_GCC,
44   PF_Binary
45 };
46 
47 static void warn(Twine Message, std::string Whence = "",
48                  std::string Hint = "") {
49   WithColor::warning();
50   if (!Whence.empty())
51     errs() << Whence << ": ";
52   errs() << Message << "\n";
53   if (!Hint.empty())
54     WithColor::note() << Hint << "\n";
55 }
56 
57 static void exitWithError(Twine Message, std::string Whence = "",
58                           std::string Hint = "") {
59   WithColor::error();
60   if (!Whence.empty())
61     errs() << Whence << ": ";
62   errs() << Message << "\n";
63   if (!Hint.empty())
64     WithColor::note() << Hint << "\n";
65   ::exit(1);
66 }
67 
68 static void exitWithError(Error E, StringRef Whence = "") {
69   if (E.isA<InstrProfError>()) {
70     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
71       instrprof_error instrError = IPE.get();
72       StringRef Hint = "";
73       if (instrError == instrprof_error::unrecognized_format) {
74         // Hint for common error of forgetting --sample for sample profiles.
75         Hint = "Perhaps you forgot to use the --sample option?";
76       }
77       exitWithError(IPE.message(), std::string(Whence), std::string(Hint));
78     });
79   }
80 
81   exitWithError(toString(std::move(E)), std::string(Whence));
82 }
83 
84 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
85   exitWithError(EC.message(), std::string(Whence));
86 }
87 
88 namespace {
89 enum ProfileKinds { instr, sample };
90 enum FailureMode { failIfAnyAreInvalid, failIfAllAreInvalid };
91 }
92 
93 static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
94                                  StringRef Whence = "") {
95   if (FailMode == failIfAnyAreInvalid)
96     exitWithErrorCode(EC, Whence);
97   else
98     warn(EC.message(), std::string(Whence));
99 }
100 
101 static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
102                                    StringRef WhenceFunction = "",
103                                    bool ShowHint = true) {
104   if (!WhenceFile.empty())
105     errs() << WhenceFile << ": ";
106   if (!WhenceFunction.empty())
107     errs() << WhenceFunction << ": ";
108 
109   auto IPE = instrprof_error::success;
110   E = handleErrors(std::move(E),
111                    [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
112                      IPE = E->get();
113                      return Error(std::move(E));
114                    });
115   errs() << toString(std::move(E)) << "\n";
116 
117   if (ShowHint) {
118     StringRef Hint = "";
119     if (IPE != instrprof_error::success) {
120       switch (IPE) {
121       case instrprof_error::hash_mismatch:
122       case instrprof_error::count_mismatch:
123       case instrprof_error::value_site_count_mismatch:
124         Hint = "Make sure that all profile data to be merged is generated "
125                "from the same binary.";
126         break;
127       default:
128         break;
129       }
130     }
131 
132     if (!Hint.empty())
133       errs() << Hint << "\n";
134   }
135 }
136 
137 namespace {
138 /// A remapper from original symbol names to new symbol names based on a file
139 /// containing a list of mappings from old name to new name.
140 class SymbolRemapper {
141   std::unique_ptr<MemoryBuffer> File;
142   DenseMap<StringRef, StringRef> RemappingTable;
143 
144 public:
145   /// Build a SymbolRemapper from a file containing a list of old/new symbols.
146   static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
147     auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
148     if (!BufOrError)
149       exitWithErrorCode(BufOrError.getError(), InputFile);
150 
151     auto Remapper = std::make_unique<SymbolRemapper>();
152     Remapper->File = std::move(BufOrError.get());
153 
154     for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
155          !LineIt.is_at_eof(); ++LineIt) {
156       std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
157       if (Parts.first.empty() || Parts.second.empty() ||
158           Parts.second.count(' ')) {
159         exitWithError("unexpected line in remapping file",
160                       (InputFile + ":" + Twine(LineIt.line_number())).str(),
161                       "expected 'old_symbol new_symbol'");
162       }
163       Remapper->RemappingTable.insert(Parts);
164     }
165     return Remapper;
166   }
167 
168   /// Attempt to map the given old symbol into a new symbol.
169   ///
170   /// \return The new symbol, or \p Name if no such symbol was found.
171   StringRef operator()(StringRef Name) {
172     StringRef New = RemappingTable.lookup(Name);
173     return New.empty() ? Name : New;
174   }
175 };
176 }
177 
178 struct WeightedFile {
179   std::string Filename;
180   uint64_t Weight;
181 };
182 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
183 
184 /// Keep track of merged data and reported errors.
185 struct WriterContext {
186   std::mutex Lock;
187   InstrProfWriter Writer;
188   std::vector<std::pair<Error, std::string>> Errors;
189   std::mutex &ErrLock;
190   SmallSet<instrprof_error, 4> &WriterErrorCodes;
191 
192   WriterContext(bool IsSparse, std::mutex &ErrLock,
193                 SmallSet<instrprof_error, 4> &WriterErrorCodes)
194       : Lock(), Writer(IsSparse), Errors(), ErrLock(ErrLock),
195         WriterErrorCodes(WriterErrorCodes) {}
196 };
197 
198 /// Computer the overlap b/w profile BaseFilename and TestFileName,
199 /// and store the program level result to Overlap.
200 static void overlapInput(const std::string &BaseFilename,
201                          const std::string &TestFilename, WriterContext *WC,
202                          OverlapStats &Overlap,
203                          const OverlapFuncFilters &FuncFilter,
204                          raw_fd_ostream &OS, bool IsCS) {
205   auto ReaderOrErr = InstrProfReader::create(TestFilename);
206   if (Error E = ReaderOrErr.takeError()) {
207     // Skip the empty profiles by returning sliently.
208     instrprof_error IPE = InstrProfError::take(std::move(E));
209     if (IPE != instrprof_error::empty_raw_profile)
210       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), TestFilename);
211     return;
212   }
213 
214   auto Reader = std::move(ReaderOrErr.get());
215   for (auto &I : *Reader) {
216     OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
217     FuncOverlap.setFuncInfo(I.Name, I.Hash);
218 
219     WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
220     FuncOverlap.dump(OS);
221   }
222 }
223 
224 /// Load an input into a writer context.
225 static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
226                       WriterContext *WC) {
227   std::unique_lock<std::mutex> CtxGuard{WC->Lock};
228 
229   // Copy the filename, because llvm::ThreadPool copied the input "const
230   // WeightedFile &" by value, making a reference to the filename within it
231   // invalid outside of this packaged task.
232   std::string Filename = Input.Filename;
233 
234   auto ReaderOrErr = InstrProfReader::create(Input.Filename);
235   if (Error E = ReaderOrErr.takeError()) {
236     // Skip the empty profiles by returning sliently.
237     instrprof_error IPE = InstrProfError::take(std::move(E));
238     if (IPE != instrprof_error::empty_raw_profile)
239       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename);
240     return;
241   }
242 
243   auto Reader = std::move(ReaderOrErr.get());
244   bool IsIRProfile = Reader->isIRLevelProfile();
245   bool HasCSIRProfile = Reader->hasCSIRLevelProfile();
246   if (WC->Writer.setIsIRLevelProfile(IsIRProfile, HasCSIRProfile)) {
247     WC->Errors.emplace_back(
248         make_error<StringError>(
249             "Merge IR generated profile with Clang generated profile.",
250             std::error_code()),
251         Filename);
252     return;
253   }
254   WC->Writer.setInstrEntryBBEnabled(Reader->instrEntryBBEnabled());
255 
256   for (auto &I : *Reader) {
257     if (Remapper)
258       I.Name = (*Remapper)(I.Name);
259     const StringRef FuncName = I.Name;
260     bool Reported = false;
261     WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
262       if (Reported) {
263         consumeError(std::move(E));
264         return;
265       }
266       Reported = true;
267       // Only show hint the first time an error occurs.
268       instrprof_error IPE = InstrProfError::take(std::move(E));
269       std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
270       bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
271       handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
272                              FuncName, firstTime);
273     });
274   }
275   if (Reader->hasError())
276     if (Error E = Reader->getError())
277       WC->Errors.emplace_back(std::move(E), Filename);
278 }
279 
280 /// Merge the \p Src writer context into \p Dst.
281 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
282   for (auto &ErrorPair : Src->Errors)
283     Dst->Errors.push_back(std::move(ErrorPair));
284   Src->Errors.clear();
285 
286   Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
287     instrprof_error IPE = InstrProfError::take(std::move(E));
288     std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
289     bool firstTime = Dst->WriterErrorCodes.insert(IPE).second;
290     if (firstTime)
291       warn(toString(make_error<InstrProfError>(IPE)));
292   });
293 }
294 
295 static void writeInstrProfile(StringRef OutputFilename,
296                               ProfileFormat OutputFormat,
297                               InstrProfWriter &Writer) {
298   std::error_code EC;
299   raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::OF_None);
300   if (EC)
301     exitWithErrorCode(EC, OutputFilename);
302 
303   if (OutputFormat == PF_Text) {
304     if (Error E = Writer.writeText(Output))
305       exitWithError(std::move(E));
306   } else {
307     Writer.write(Output);
308   }
309 }
310 
311 static void mergeInstrProfile(const WeightedFileVector &Inputs,
312                               SymbolRemapper *Remapper,
313                               StringRef OutputFilename,
314                               ProfileFormat OutputFormat, bool OutputSparse,
315                               unsigned NumThreads, FailureMode FailMode) {
316   if (OutputFilename.compare("-") == 0)
317     exitWithError("Cannot write indexed profdata format to stdout.");
318 
319   if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
320       OutputFormat != PF_Ext_Binary && OutputFormat != PF_Text)
321     exitWithError("Unknown format is specified.");
322 
323   std::mutex ErrorLock;
324   SmallSet<instrprof_error, 4> WriterErrorCodes;
325 
326   // If NumThreads is not specified, auto-detect a good default.
327   if (NumThreads == 0)
328     NumThreads = std::min(hardware_concurrency().compute_thread_count(),
329                           unsigned((Inputs.size() + 1) / 2));
330   // FIXME: There's a bug here, where setting NumThreads = Inputs.size() fails
331   // the merge_empty_profile.test because the InstrProfWriter.ProfileKind isn't
332   // merged, thus the emitted file ends up with a PF_Unknown kind.
333 
334   // Initialize the writer contexts.
335   SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
336   for (unsigned I = 0; I < NumThreads; ++I)
337     Contexts.emplace_back(std::make_unique<WriterContext>(
338         OutputSparse, ErrorLock, WriterErrorCodes));
339 
340   if (NumThreads == 1) {
341     for (const auto &Input : Inputs)
342       loadInput(Input, Remapper, Contexts[0].get());
343   } else {
344     ThreadPool Pool(hardware_concurrency(NumThreads));
345 
346     // Load the inputs in parallel (N/NumThreads serial steps).
347     unsigned Ctx = 0;
348     for (const auto &Input : Inputs) {
349       Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get());
350       Ctx = (Ctx + 1) % NumThreads;
351     }
352     Pool.wait();
353 
354     // Merge the writer contexts together (~ lg(NumThreads) serial steps).
355     unsigned Mid = Contexts.size() / 2;
356     unsigned End = Contexts.size();
357     assert(Mid > 0 && "Expected more than one context");
358     do {
359       for (unsigned I = 0; I < Mid; ++I)
360         Pool.async(mergeWriterContexts, Contexts[I].get(),
361                    Contexts[I + Mid].get());
362       Pool.wait();
363       if (End & 1) {
364         Pool.async(mergeWriterContexts, Contexts[0].get(),
365                    Contexts[End - 1].get());
366         Pool.wait();
367       }
368       End = Mid;
369       Mid /= 2;
370     } while (Mid > 0);
371   }
372 
373   // Handle deferred errors encountered during merging. If the number of errors
374   // is equal to the number of inputs the merge failed.
375   unsigned NumErrors = 0;
376   for (std::unique_ptr<WriterContext> &WC : Contexts) {
377     for (auto &ErrorPair : WC->Errors) {
378       ++NumErrors;
379       warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
380     }
381   }
382   if (NumErrors == Inputs.size() ||
383       (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
384     exitWithError("No profiles could be merged.");
385 
386   writeInstrProfile(OutputFilename, OutputFormat, Contexts[0]->Writer);
387 }
388 
389 /// The profile entry for a function in instrumentation profile.
390 struct InstrProfileEntry {
391   uint64_t MaxCount = 0;
392   float ZeroCounterRatio = 0.0;
393   InstrProfRecord *ProfRecord;
394   InstrProfileEntry(InstrProfRecord *Record);
395   InstrProfileEntry() = default;
396 };
397 
398 InstrProfileEntry::InstrProfileEntry(InstrProfRecord *Record) {
399   ProfRecord = Record;
400   uint64_t CntNum = Record->Counts.size();
401   uint64_t ZeroCntNum = 0;
402   for (size_t I = 0; I < CntNum; ++I) {
403     MaxCount = std::max(MaxCount, Record->Counts[I]);
404     ZeroCntNum += !Record->Counts[I];
405   }
406   ZeroCounterRatio = (float)ZeroCntNum / CntNum;
407 }
408 
409 /// Either set all the counters in the instr profile entry \p IFE to -1
410 /// in order to drop the profile or scale up the counters in \p IFP to
411 /// be above hot threshold. We use the ratio of zero counters in the
412 /// profile of a function to decide the profile is helpful or harmful
413 /// for performance, and to choose whether to scale up or drop it.
414 static void updateInstrProfileEntry(InstrProfileEntry &IFE,
415                                     uint64_t HotInstrThreshold,
416                                     float ZeroCounterThreshold) {
417   InstrProfRecord *ProfRecord = IFE.ProfRecord;
418   if (!IFE.MaxCount || IFE.ZeroCounterRatio > ZeroCounterThreshold) {
419     // If all or most of the counters of the function are zero, the
420     // profile is unaccountable and shuld be dropped. Reset all the
421     // counters to be -1 and PGO profile-use will drop the profile.
422     // All counters being -1 also implies that the function is hot so
423     // PGO profile-use will also set the entry count metadata to be
424     // above hot threshold.
425     for (size_t I = 0; I < ProfRecord->Counts.size(); ++I)
426       ProfRecord->Counts[I] = -1;
427     return;
428   }
429 
430   // Scale up the MaxCount to be multiple times above hot threshold.
431   const unsigned MultiplyFactor = 3;
432   uint64_t Numerator = HotInstrThreshold * MultiplyFactor;
433   uint64_t Denominator = IFE.MaxCount;
434   ProfRecord->scale(Numerator, Denominator, [&](instrprof_error E) {
435     warn(toString(make_error<InstrProfError>(E)));
436   });
437 }
438 
439 const uint64_t ColdPercentileIdx = 15;
440 const uint64_t HotPercentileIdx = 11;
441 
442 /// Adjust the instr profile in \p WC based on the sample profile in
443 /// \p Reader.
444 static void
445 adjustInstrProfile(std::unique_ptr<WriterContext> &WC,
446                    std::unique_ptr<sampleprof::SampleProfileReader> &Reader,
447                    unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
448                    unsigned InstrProfColdThreshold) {
449   // Function to its entry in instr profile.
450   StringMap<InstrProfileEntry> InstrProfileMap;
451   InstrProfSummaryBuilder IPBuilder(ProfileSummaryBuilder::DefaultCutoffs);
452   for (auto &PD : WC->Writer.getProfileData()) {
453     // Populate IPBuilder.
454     for (const auto &PDV : PD.getValue()) {
455       InstrProfRecord Record = PDV.second;
456       IPBuilder.addRecord(Record);
457     }
458 
459     // If a function has multiple entries in instr profile, skip it.
460     if (PD.getValue().size() != 1)
461       continue;
462 
463     // Initialize InstrProfileMap.
464     InstrProfRecord *R = &PD.getValue().begin()->second;
465     InstrProfileMap[PD.getKey()] = InstrProfileEntry(R);
466   }
467 
468   ProfileSummary InstrPS = *IPBuilder.getSummary();
469   ProfileSummary SamplePS = Reader->getSummary();
470 
471   // Compute cold thresholds for instr profile and sample profile.
472   uint64_t ColdSampleThreshold =
473       ProfileSummaryBuilder::getEntryForPercentile(
474           SamplePS.getDetailedSummary(),
475           ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
476           .MinCount;
477   uint64_t HotInstrThreshold =
478       ProfileSummaryBuilder::getEntryForPercentile(
479           InstrPS.getDetailedSummary(),
480           ProfileSummaryBuilder::DefaultCutoffs[HotPercentileIdx])
481           .MinCount;
482   uint64_t ColdInstrThreshold =
483       InstrProfColdThreshold
484           ? InstrProfColdThreshold
485           : ProfileSummaryBuilder::getEntryForPercentile(
486                 InstrPS.getDetailedSummary(),
487                 ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
488                 .MinCount;
489 
490   // Find hot/warm functions in sample profile which is cold in instr profile
491   // and adjust the profiles of those functions in the instr profile.
492   for (const auto &PD : Reader->getProfiles()) {
493     StringRef FName = PD.getKey();
494     const sampleprof::FunctionSamples &FS = PD.getValue();
495     auto It = InstrProfileMap.find(FName);
496     if (FS.getHeadSamples() > ColdSampleThreshold &&
497         It != InstrProfileMap.end() &&
498         It->second.MaxCount <= ColdInstrThreshold &&
499         FS.getBodySamples().size() >= SupplMinSizeThreshold) {
500       updateInstrProfileEntry(It->second, HotInstrThreshold,
501                               ZeroCounterThreshold);
502     }
503   }
504 }
505 
506 /// The main function to supplement instr profile with sample profile.
507 /// \Inputs contains the instr profile. \p SampleFilename specifies the
508 /// sample profile. \p OutputFilename specifies the output profile name.
509 /// \p OutputFormat specifies the output profile format. \p OutputSparse
510 /// specifies whether to generate sparse profile. \p SupplMinSizeThreshold
511 /// specifies the minimal size for the functions whose profile will be
512 /// adjusted. \p ZeroCounterThreshold is the threshold to check whether
513 /// a function contains too many zero counters and whether its profile
514 /// should be dropped. \p InstrProfColdThreshold is the user specified
515 /// cold threshold which will override the cold threshold got from the
516 /// instr profile summary.
517 static void supplementInstrProfile(
518     const WeightedFileVector &Inputs, StringRef SampleFilename,
519     StringRef OutputFilename, ProfileFormat OutputFormat, bool OutputSparse,
520     unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
521     unsigned InstrProfColdThreshold) {
522   if (OutputFilename.compare("-") == 0)
523     exitWithError("Cannot write indexed profdata format to stdout.");
524   if (Inputs.size() != 1)
525     exitWithError("Expect one input to be an instr profile.");
526   if (Inputs[0].Weight != 1)
527     exitWithError("Expect instr profile doesn't have weight.");
528 
529   StringRef InstrFilename = Inputs[0].Filename;
530 
531   // Read sample profile.
532   LLVMContext Context;
533   auto ReaderOrErr =
534       sampleprof::SampleProfileReader::create(SampleFilename.str(), Context);
535   if (std::error_code EC = ReaderOrErr.getError())
536     exitWithErrorCode(EC, SampleFilename);
537   auto Reader = std::move(ReaderOrErr.get());
538   if (std::error_code EC = Reader->read())
539     exitWithErrorCode(EC, SampleFilename);
540 
541   // Read instr profile.
542   std::mutex ErrorLock;
543   SmallSet<instrprof_error, 4> WriterErrorCodes;
544   auto WC = std::make_unique<WriterContext>(OutputSparse, ErrorLock,
545                                             WriterErrorCodes);
546   loadInput(Inputs[0], nullptr, WC.get());
547   if (WC->Errors.size() > 0)
548     exitWithError(std::move(WC->Errors[0].first), InstrFilename);
549 
550   adjustInstrProfile(WC, Reader, SupplMinSizeThreshold, ZeroCounterThreshold,
551                      InstrProfColdThreshold);
552   writeInstrProfile(OutputFilename, OutputFormat, WC->Writer);
553 }
554 
555 /// Make a copy of the given function samples with all symbol names remapped
556 /// by the provided symbol remapper.
557 static sampleprof::FunctionSamples
558 remapSamples(const sampleprof::FunctionSamples &Samples,
559              SymbolRemapper &Remapper, sampleprof_error &Error) {
560   sampleprof::FunctionSamples Result;
561   Result.setName(Remapper(Samples.getName()));
562   Result.addTotalSamples(Samples.getTotalSamples());
563   Result.addHeadSamples(Samples.getHeadSamples());
564   for (const auto &BodySample : Samples.getBodySamples()) {
565     Result.addBodySamples(BodySample.first.LineOffset,
566                           BodySample.first.Discriminator,
567                           BodySample.second.getSamples());
568     for (const auto &Target : BodySample.second.getCallTargets()) {
569       Result.addCalledTargetSamples(BodySample.first.LineOffset,
570                                     BodySample.first.Discriminator,
571                                     Remapper(Target.first()), Target.second);
572     }
573   }
574   for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
575     sampleprof::FunctionSamplesMap &Target =
576         Result.functionSamplesAt(CallsiteSamples.first);
577     for (const auto &Callsite : CallsiteSamples.second) {
578       sampleprof::FunctionSamples Remapped =
579           remapSamples(Callsite.second, Remapper, Error);
580       MergeResult(Error,
581                   Target[std::string(Remapped.getName())].merge(Remapped));
582     }
583   }
584   return Result;
585 }
586 
587 static sampleprof::SampleProfileFormat FormatMap[] = {
588     sampleprof::SPF_None,
589     sampleprof::SPF_Text,
590     sampleprof::SPF_Compact_Binary,
591     sampleprof::SPF_Ext_Binary,
592     sampleprof::SPF_GCC,
593     sampleprof::SPF_Binary};
594 
595 static std::unique_ptr<MemoryBuffer>
596 getInputFileBuf(const StringRef &InputFile) {
597   if (InputFile == "")
598     return {};
599 
600   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
601   if (!BufOrError)
602     exitWithErrorCode(BufOrError.getError(), InputFile);
603 
604   return std::move(*BufOrError);
605 }
606 
607 static void populateProfileSymbolList(MemoryBuffer *Buffer,
608                                       sampleprof::ProfileSymbolList &PSL) {
609   if (!Buffer)
610     return;
611 
612   SmallVector<StringRef, 32> SymbolVec;
613   StringRef Data = Buffer->getBuffer();
614   Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
615 
616   for (StringRef symbol : SymbolVec)
617     PSL.add(symbol);
618 }
619 
620 static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer,
621                                   ProfileFormat OutputFormat,
622                                   MemoryBuffer *Buffer,
623                                   sampleprof::ProfileSymbolList &WriterList,
624                                   bool CompressAllSections, bool UseMD5,
625                                   bool GenPartialProfile) {
626   populateProfileSymbolList(Buffer, WriterList);
627   if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
628     warn("Profile Symbol list is not empty but the output format is not "
629          "ExtBinary format. The list will be lost in the output. ");
630 
631   Writer.setProfileSymbolList(&WriterList);
632 
633   if (CompressAllSections) {
634     if (OutputFormat != PF_Ext_Binary)
635       warn("-compress-all-section is ignored. Specify -extbinary to enable it");
636     else
637       Writer.setToCompressAllSections();
638   }
639   if (UseMD5) {
640     if (OutputFormat != PF_Ext_Binary)
641       warn("-use-md5 is ignored. Specify -extbinary to enable it");
642     else
643       Writer.setUseMD5();
644   }
645   if (GenPartialProfile) {
646     if (OutputFormat != PF_Ext_Binary)
647       warn("-gen-partial-profile is ignored. Specify -extbinary to enable it");
648     else
649       Writer.setPartialProfile();
650   }
651 }
652 
653 static void
654 mergeSampleProfile(const WeightedFileVector &Inputs, SymbolRemapper *Remapper,
655                    StringRef OutputFilename, ProfileFormat OutputFormat,
656                    StringRef ProfileSymbolListFile, bool CompressAllSections,
657                    bool UseMD5, bool GenPartialProfile, FailureMode FailMode) {
658   using namespace sampleprof;
659   StringMap<FunctionSamples> ProfileMap;
660   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
661   LLVMContext Context;
662   sampleprof::ProfileSymbolList WriterList;
663   Optional<bool> ProfileIsProbeBased;
664   for (const auto &Input : Inputs) {
665     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
666     if (std::error_code EC = ReaderOrErr.getError()) {
667       warnOrExitGivenError(FailMode, EC, Input.Filename);
668       continue;
669     }
670 
671     // We need to keep the readers around until after all the files are
672     // read so that we do not lose the function names stored in each
673     // reader's memory. The function names are needed to write out the
674     // merged profile map.
675     Readers.push_back(std::move(ReaderOrErr.get()));
676     const auto Reader = Readers.back().get();
677     if (std::error_code EC = Reader->read()) {
678       warnOrExitGivenError(FailMode, EC, Input.Filename);
679       Readers.pop_back();
680       continue;
681     }
682 
683     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
684     if (ProfileIsProbeBased &&
685         ProfileIsProbeBased != FunctionSamples::ProfileIsProbeBased)
686       exitWithError(
687           "cannot merge probe-based profile with non-probe-based profile");
688     ProfileIsProbeBased = FunctionSamples::ProfileIsProbeBased;
689     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
690                                               E = Profiles.end();
691          I != E; ++I) {
692       sampleprof_error Result = sampleprof_error::success;
693       FunctionSamples Remapped =
694           Remapper ? remapSamples(I->second, *Remapper, Result)
695                    : FunctionSamples();
696       FunctionSamples &Samples = Remapper ? Remapped : I->second;
697       StringRef FName = Samples.getName();
698       MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight));
699       if (Result != sampleprof_error::success) {
700         std::error_code EC = make_error_code(Result);
701         handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
702       }
703     }
704 
705     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
706         Reader->getProfileSymbolList();
707     if (ReaderList)
708       WriterList.merge(*ReaderList);
709   }
710   auto WriterOrErr =
711       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
712   if (std::error_code EC = WriterOrErr.getError())
713     exitWithErrorCode(EC, OutputFilename);
714 
715   auto Writer = std::move(WriterOrErr.get());
716   // WriterList will have StringRef refering to string in Buffer.
717   // Make sure Buffer lives as long as WriterList.
718   auto Buffer = getInputFileBuf(ProfileSymbolListFile);
719   handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList,
720                         CompressAllSections, UseMD5, GenPartialProfile);
721   Writer->write(ProfileMap);
722 }
723 
724 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
725   StringRef WeightStr, FileName;
726   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
727 
728   uint64_t Weight;
729   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
730     exitWithError("Input weight must be a positive integer.");
731 
732   return {std::string(FileName), Weight};
733 }
734 
735 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
736   StringRef Filename = WF.Filename;
737   uint64_t Weight = WF.Weight;
738 
739   // If it's STDIN just pass it on.
740   if (Filename == "-") {
741     WNI.push_back({std::string(Filename), Weight});
742     return;
743   }
744 
745   llvm::sys::fs::file_status Status;
746   llvm::sys::fs::status(Filename, Status);
747   if (!llvm::sys::fs::exists(Status))
748     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
749                       Filename);
750   // If it's a source file, collect it.
751   if (llvm::sys::fs::is_regular_file(Status)) {
752     WNI.push_back({std::string(Filename), Weight});
753     return;
754   }
755 
756   if (llvm::sys::fs::is_directory(Status)) {
757     std::error_code EC;
758     for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
759          F != E && !EC; F.increment(EC)) {
760       if (llvm::sys::fs::is_regular_file(F->path())) {
761         addWeightedInput(WNI, {F->path(), Weight});
762       }
763     }
764     if (EC)
765       exitWithErrorCode(EC, Filename);
766   }
767 }
768 
769 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
770                                     WeightedFileVector &WFV) {
771   if (!Buffer)
772     return;
773 
774   SmallVector<StringRef, 8> Entries;
775   StringRef Data = Buffer->getBuffer();
776   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
777   for (const StringRef &FileWeightEntry : Entries) {
778     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
779     // Skip comments.
780     if (SanitizedEntry.startswith("#"))
781       continue;
782     // If there's no comma, it's an unweighted profile.
783     else if (SanitizedEntry.find(',') == StringRef::npos)
784       addWeightedInput(WFV, {std::string(SanitizedEntry), 1});
785     else
786       addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
787   }
788 }
789 
790 static int merge_main(int argc, const char *argv[]) {
791   cl::list<std::string> InputFilenames(cl::Positional,
792                                        cl::desc("<filename...>"));
793   cl::list<std::string> WeightedInputFilenames("weighted-input",
794                                                cl::desc("<weight>,<filename>"));
795   cl::opt<std::string> InputFilenamesFile(
796       "input-files", cl::init(""),
797       cl::desc("Path to file containing newline-separated "
798                "[<weight>,]<filename> entries"));
799   cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
800                                 cl::aliasopt(InputFilenamesFile));
801   cl::opt<bool> DumpInputFileList(
802       "dump-input-file-list", cl::init(false), cl::Hidden,
803       cl::desc("Dump the list of input files and their weights, then exit"));
804   cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
805                                      cl::desc("Symbol remapping file"));
806   cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
807                            cl::aliasopt(RemappingFile));
808   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
809                                       cl::init("-"), cl::Required,
810                                       cl::desc("Output file"));
811   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
812                             cl::aliasopt(OutputFilename));
813   cl::opt<ProfileKinds> ProfileKind(
814       cl::desc("Profile kind:"), cl::init(instr),
815       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
816                  clEnumVal(sample, "Sample profile")));
817   cl::opt<ProfileFormat> OutputFormat(
818       cl::desc("Format of output profile"), cl::init(PF_Binary),
819       cl::values(
820           clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
821           clEnumValN(PF_Compact_Binary, "compbinary",
822                      "Compact binary encoding"),
823           clEnumValN(PF_Ext_Binary, "extbinary", "Extensible binary encoding"),
824           clEnumValN(PF_Text, "text", "Text encoding"),
825           clEnumValN(PF_GCC, "gcc",
826                      "GCC encoding (only meaningful for -sample)")));
827   cl::opt<FailureMode> FailureMode(
828       "failure-mode", cl::init(failIfAnyAreInvalid), cl::desc("Failure mode:"),
829       cl::values(clEnumValN(failIfAnyAreInvalid, "any",
830                             "Fail if any profile is invalid."),
831                  clEnumValN(failIfAllAreInvalid, "all",
832                             "Fail only if all profiles are invalid.")));
833   cl::opt<bool> OutputSparse("sparse", cl::init(false),
834       cl::desc("Generate a sparse profile (only meaningful for -instr)"));
835   cl::opt<unsigned> NumThreads(
836       "num-threads", cl::init(0),
837       cl::desc("Number of merge threads to use (default: autodetect)"));
838   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
839                         cl::aliasopt(NumThreads));
840   cl::opt<std::string> ProfileSymbolListFile(
841       "prof-sym-list", cl::init(""),
842       cl::desc("Path to file containing the list of function symbols "
843                "used to populate profile symbol list"));
844   cl::opt<bool> CompressAllSections(
845       "compress-all-sections", cl::init(false), cl::Hidden,
846       cl::desc("Compress all sections when writing the profile (only "
847                "meaningful for -extbinary)"));
848   cl::opt<bool> UseMD5(
849       "use-md5", cl::init(false), cl::Hidden,
850       cl::desc("Choose to use MD5 to represent string in name table (only "
851                "meaningful for -extbinary)"));
852   cl::opt<bool> GenPartialProfile(
853       "gen-partial-profile", cl::init(false), cl::Hidden,
854       cl::desc("Generate a partial profile (only meaningful for -extbinary)"));
855   cl::opt<std::string> SupplInstrWithSample(
856       "supplement-instr-with-sample", cl::init(""), cl::Hidden,
857       cl::desc("Supplement an instr profile with sample profile, to correct "
858                "the profile unrepresentativeness issue. The sample "
859                "profile is the input of the flag. Output will be in instr "
860                "format (The flag only works with -instr)"));
861   cl::opt<float> ZeroCounterThreshold(
862       "zero-counter-threshold", cl::init(0.7), cl::Hidden,
863       cl::desc("For the function which is cold in instr profile but hot in "
864                "sample profile, if the ratio of the number of zero counters "
865                "divided by the the total number of counters is above the "
866                "threshold, the profile of the function will be regarded as "
867                "being harmful for performance and will be dropped. "));
868   cl::opt<unsigned> SupplMinSizeThreshold(
869       "suppl-min-size-threshold", cl::init(10), cl::Hidden,
870       cl::desc("If the size of a function is smaller than the threshold, "
871                "assume it can be inlined by PGO early inliner and it won't "
872                "be adjusted based on sample profile. "));
873   cl::opt<unsigned> InstrProfColdThreshold(
874       "instr-prof-cold-threshold", cl::init(0), cl::Hidden,
875       cl::desc("User specified cold threshold for instr profile which will "
876                "override the cold threshold got from profile summary. "));
877 
878   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
879 
880   WeightedFileVector WeightedInputs;
881   for (StringRef Filename : InputFilenames)
882     addWeightedInput(WeightedInputs, {std::string(Filename), 1});
883   for (StringRef WeightedFilename : WeightedInputFilenames)
884     addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
885 
886   // Make sure that the file buffer stays alive for the duration of the
887   // weighted input vector's lifetime.
888   auto Buffer = getInputFileBuf(InputFilenamesFile);
889   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
890 
891   if (WeightedInputs.empty())
892     exitWithError("No input files specified. See " +
893                   sys::path::filename(argv[0]) + " -help");
894 
895   if (DumpInputFileList) {
896     for (auto &WF : WeightedInputs)
897       outs() << WF.Weight << "," << WF.Filename << "\n";
898     return 0;
899   }
900 
901   std::unique_ptr<SymbolRemapper> Remapper;
902   if (!RemappingFile.empty())
903     Remapper = SymbolRemapper::create(RemappingFile);
904 
905   if (!SupplInstrWithSample.empty()) {
906     if (ProfileKind != instr)
907       exitWithError(
908           "-supplement-instr-with-sample can only work with -instr. ");
909 
910     supplementInstrProfile(WeightedInputs, SupplInstrWithSample, OutputFilename,
911                            OutputFormat, OutputSparse, SupplMinSizeThreshold,
912                            ZeroCounterThreshold, InstrProfColdThreshold);
913     return 0;
914   }
915 
916   if (ProfileKind == instr)
917     mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
918                       OutputFormat, OutputSparse, NumThreads, FailureMode);
919   else
920     mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
921                        OutputFormat, ProfileSymbolListFile, CompressAllSections,
922                        UseMD5, GenPartialProfile, FailureMode);
923 
924   return 0;
925 }
926 
927 /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
928 static void overlapInstrProfile(const std::string &BaseFilename,
929                                 const std::string &TestFilename,
930                                 const OverlapFuncFilters &FuncFilter,
931                                 raw_fd_ostream &OS, bool IsCS) {
932   std::mutex ErrorLock;
933   SmallSet<instrprof_error, 4> WriterErrorCodes;
934   WriterContext Context(false, ErrorLock, WriterErrorCodes);
935   WeightedFile WeightedInput{BaseFilename, 1};
936   OverlapStats Overlap;
937   Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS);
938   if (E)
939     exitWithError(std::move(E), "Error in getting profile count sums");
940   if (Overlap.Base.CountSum < 1.0f) {
941     OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
942     exit(0);
943   }
944   if (Overlap.Test.CountSum < 1.0f) {
945     OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
946     exit(0);
947   }
948   loadInput(WeightedInput, nullptr, &Context);
949   overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
950                IsCS);
951   Overlap.dump(OS);
952 }
953 
954 namespace {
955 struct SampleOverlapStats {
956   StringRef BaseName;
957   StringRef TestName;
958   // Number of overlap units
959   uint64_t OverlapCount;
960   // Total samples of overlap units
961   uint64_t OverlapSample;
962   // Number of and total samples of units that only present in base or test
963   // profile
964   uint64_t BaseUniqueCount;
965   uint64_t BaseUniqueSample;
966   uint64_t TestUniqueCount;
967   uint64_t TestUniqueSample;
968   // Number of units and total samples in base or test profile
969   uint64_t BaseCount;
970   uint64_t BaseSample;
971   uint64_t TestCount;
972   uint64_t TestSample;
973   // Number of and total samples of units that present in at least one profile
974   uint64_t UnionCount;
975   uint64_t UnionSample;
976   // Weighted similarity
977   double Similarity;
978   // For SampleOverlapStats instances representing functions, weights of the
979   // function in base and test profiles
980   double BaseWeight;
981   double TestWeight;
982 
983   SampleOverlapStats()
984       : OverlapCount(0), OverlapSample(0), BaseUniqueCount(0),
985         BaseUniqueSample(0), TestUniqueCount(0), TestUniqueSample(0),
986         BaseCount(0), BaseSample(0), TestCount(0), TestSample(0), UnionCount(0),
987         UnionSample(0), Similarity(0.0), BaseWeight(0.0), TestWeight(0.0) {}
988 };
989 } // end anonymous namespace
990 
991 namespace {
992 struct FuncSampleStats {
993   uint64_t SampleSum;
994   uint64_t MaxSample;
995   uint64_t HotBlockCount;
996   FuncSampleStats() : SampleSum(0), MaxSample(0), HotBlockCount(0) {}
997   FuncSampleStats(uint64_t SampleSum, uint64_t MaxSample,
998                   uint64_t HotBlockCount)
999       : SampleSum(SampleSum), MaxSample(MaxSample),
1000         HotBlockCount(HotBlockCount) {}
1001 };
1002 } // end anonymous namespace
1003 
1004 namespace {
1005 enum MatchStatus { MS_Match, MS_FirstUnique, MS_SecondUnique, MS_None };
1006 
1007 // Class for updating merging steps for two sorted maps. The class should be
1008 // instantiated with a map iterator type.
1009 template <class T> class MatchStep {
1010 public:
1011   MatchStep() = delete;
1012 
1013   MatchStep(T FirstIter, T FirstEnd, T SecondIter, T SecondEnd)
1014       : FirstIter(FirstIter), FirstEnd(FirstEnd), SecondIter(SecondIter),
1015         SecondEnd(SecondEnd), Status(MS_None) {}
1016 
1017   bool areBothFinished() const {
1018     return (FirstIter == FirstEnd && SecondIter == SecondEnd);
1019   }
1020 
1021   bool isFirstFinished() const { return FirstIter == FirstEnd; }
1022 
1023   bool isSecondFinished() const { return SecondIter == SecondEnd; }
1024 
1025   /// Advance one step based on the previous match status unless the previous
1026   /// status is MS_None. Then update Status based on the comparison between two
1027   /// container iterators at the current step. If the previous status is
1028   /// MS_None, it means two iterators are at the beginning and no comparison has
1029   /// been made, so we simply update Status without advancing the iterators.
1030   void updateOneStep();
1031 
1032   T getFirstIter() const { return FirstIter; }
1033 
1034   T getSecondIter() const { return SecondIter; }
1035 
1036   MatchStatus getMatchStatus() const { return Status; }
1037 
1038 private:
1039   // Current iterator and end iterator of the first container.
1040   T FirstIter;
1041   T FirstEnd;
1042   // Current iterator and end iterator of the second container.
1043   T SecondIter;
1044   T SecondEnd;
1045   // Match status of the current step.
1046   MatchStatus Status;
1047 };
1048 } // end anonymous namespace
1049 
1050 template <class T> void MatchStep<T>::updateOneStep() {
1051   switch (Status) {
1052   case MS_Match:
1053     ++FirstIter;
1054     ++SecondIter;
1055     break;
1056   case MS_FirstUnique:
1057     ++FirstIter;
1058     break;
1059   case MS_SecondUnique:
1060     ++SecondIter;
1061     break;
1062   case MS_None:
1063     break;
1064   }
1065 
1066   // Update Status according to iterators at the current step.
1067   if (areBothFinished())
1068     return;
1069   if (FirstIter != FirstEnd &&
1070       (SecondIter == SecondEnd || FirstIter->first < SecondIter->first))
1071     Status = MS_FirstUnique;
1072   else if (SecondIter != SecondEnd &&
1073            (FirstIter == FirstEnd || SecondIter->first < FirstIter->first))
1074     Status = MS_SecondUnique;
1075   else
1076     Status = MS_Match;
1077 }
1078 
1079 // Return the sum of line/block samples, the max line/block sample, and the
1080 // number of line/block samples above the given threshold in a function
1081 // including its inlinees.
1082 static void getFuncSampleStats(const sampleprof::FunctionSamples &Func,
1083                                FuncSampleStats &FuncStats,
1084                                uint64_t HotThreshold) {
1085   for (const auto &L : Func.getBodySamples()) {
1086     uint64_t Sample = L.second.getSamples();
1087     FuncStats.SampleSum += Sample;
1088     FuncStats.MaxSample = std::max(FuncStats.MaxSample, Sample);
1089     if (Sample >= HotThreshold)
1090       ++FuncStats.HotBlockCount;
1091   }
1092 
1093   for (const auto &C : Func.getCallsiteSamples()) {
1094     for (const auto &F : C.second)
1095       getFuncSampleStats(F.second, FuncStats, HotThreshold);
1096   }
1097 }
1098 
1099 /// Predicate that determines if a function is hot with a given threshold. We
1100 /// keep it separate from its callsites for possible extension in the future.
1101 static bool isFunctionHot(const FuncSampleStats &FuncStats,
1102                           uint64_t HotThreshold) {
1103   // We intentionally compare the maximum sample count in a function with the
1104   // HotThreshold to get an approximate determination on hot functions.
1105   return (FuncStats.MaxSample >= HotThreshold);
1106 }
1107 
1108 namespace {
1109 class SampleOverlapAggregator {
1110 public:
1111   SampleOverlapAggregator(const std::string &BaseFilename,
1112                           const std::string &TestFilename,
1113                           double LowSimilarityThreshold, double Epsilon,
1114                           const OverlapFuncFilters &FuncFilter)
1115       : BaseFilename(BaseFilename), TestFilename(TestFilename),
1116         LowSimilarityThreshold(LowSimilarityThreshold), Epsilon(Epsilon),
1117         FuncFilter(FuncFilter) {}
1118 
1119   /// Detect 0-sample input profile and report to output stream. This interface
1120   /// should be called after loadProfiles().
1121   bool detectZeroSampleProfile(raw_fd_ostream &OS) const;
1122 
1123   /// Write out function-level similarity statistics for functions specified by
1124   /// options --function, --value-cutoff, and --similarity-cutoff.
1125   void dumpFuncSimilarity(raw_fd_ostream &OS) const;
1126 
1127   /// Write out program-level similarity and overlap statistics.
1128   void dumpProgramSummary(raw_fd_ostream &OS) const;
1129 
1130   /// Write out hot-function and hot-block statistics for base_profile,
1131   /// test_profile, and their overlap. For both cases, the overlap HO is
1132   /// calculated as follows:
1133   ///    Given the number of functions (or blocks) that are hot in both profiles
1134   ///    HCommon and the number of functions (or blocks) that are hot in at
1135   ///    least one profile HUnion, HO = HCommon / HUnion.
1136   void dumpHotFuncAndBlockOverlap(raw_fd_ostream &OS) const;
1137 
1138   /// This function tries matching functions in base and test profiles. For each
1139   /// pair of matched functions, it aggregates the function-level
1140   /// similarity into a profile-level similarity. It also dump function-level
1141   /// similarity information of functions specified by --function,
1142   /// --value-cutoff, and --similarity-cutoff options. The program-level
1143   /// similarity PS is computed as follows:
1144   ///     Given function-level similarity FS(A) for all function A, the
1145   ///     weight of function A in base profile WB(A), and the weight of function
1146   ///     A in test profile WT(A), compute PS(base_profile, test_profile) =
1147   ///     sum_A(FS(A) * avg(WB(A), WT(A))) ranging in [0.0f to 1.0f] with 0.0
1148   ///     meaning no-overlap.
1149   void computeSampleProfileOverlap(raw_fd_ostream &OS);
1150 
1151   /// Initialize ProfOverlap with the sum of samples in base and test
1152   /// profiles. This function also computes and keeps the sum of samples and
1153   /// max sample counts of each function in BaseStats and TestStats for later
1154   /// use to avoid re-computations.
1155   void initializeSampleProfileOverlap();
1156 
1157   /// Load profiles specified by BaseFilename and TestFilename.
1158   std::error_code loadProfiles();
1159 
1160 private:
1161   SampleOverlapStats ProfOverlap;
1162   SampleOverlapStats HotFuncOverlap;
1163   SampleOverlapStats HotBlockOverlap;
1164   std::string BaseFilename;
1165   std::string TestFilename;
1166   std::unique_ptr<sampleprof::SampleProfileReader> BaseReader;
1167   std::unique_ptr<sampleprof::SampleProfileReader> TestReader;
1168   // BaseStats and TestStats hold FuncSampleStats for each function, with
1169   // function name as the key.
1170   StringMap<FuncSampleStats> BaseStats;
1171   StringMap<FuncSampleStats> TestStats;
1172   // Low similarity threshold in floating point number
1173   double LowSimilarityThreshold;
1174   // Block samples above BaseHotThreshold or TestHotThreshold are considered hot
1175   // for tracking hot blocks.
1176   uint64_t BaseHotThreshold;
1177   uint64_t TestHotThreshold;
1178   // A small threshold used to round the results of floating point accumulations
1179   // to resolve imprecision.
1180   const double Epsilon;
1181   std::multimap<double, SampleOverlapStats, std::greater<double>>
1182       FuncSimilarityDump;
1183   // FuncFilter carries specifications in options --value-cutoff and
1184   // --function.
1185   OverlapFuncFilters FuncFilter;
1186   // Column offsets for printing the function-level details table.
1187   static const unsigned int TestWeightCol = 15;
1188   static const unsigned int SimilarityCol = 30;
1189   static const unsigned int OverlapCol = 43;
1190   static const unsigned int BaseUniqueCol = 53;
1191   static const unsigned int TestUniqueCol = 67;
1192   static const unsigned int BaseSampleCol = 81;
1193   static const unsigned int TestSampleCol = 96;
1194   static const unsigned int FuncNameCol = 111;
1195 
1196   /// Return a similarity of two line/block sample counters in the same
1197   /// function in base and test profiles. The line/block-similarity BS(i) is
1198   /// computed as follows:
1199   ///    For an offsets i, given the sample count at i in base profile BB(i),
1200   ///    the sample count at i in test profile BT(i), the sum of sample counts
1201   ///    in this function in base profile SB, and the sum of sample counts in
1202   ///    this function in test profile ST, compute BS(i) = 1.0 - fabs(BB(i)/SB -
1203   ///    BT(i)/ST), ranging in [0.0f to 1.0f] with 0.0 meaning no-overlap.
1204   double computeBlockSimilarity(uint64_t BaseSample, uint64_t TestSample,
1205                                 const SampleOverlapStats &FuncOverlap) const;
1206 
1207   void updateHotBlockOverlap(uint64_t BaseSample, uint64_t TestSample,
1208                              uint64_t HotBlockCount);
1209 
1210   void getHotFunctions(const StringMap<FuncSampleStats> &ProfStats,
1211                        StringMap<FuncSampleStats> &HotFunc,
1212                        uint64_t HotThreshold) const;
1213 
1214   void computeHotFuncOverlap();
1215 
1216   /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
1217   /// Difference for two sample units in a matched function according to the
1218   /// given match status.
1219   void updateOverlapStatsForFunction(uint64_t BaseSample, uint64_t TestSample,
1220                                      uint64_t HotBlockCount,
1221                                      SampleOverlapStats &FuncOverlap,
1222                                      double &Difference, MatchStatus Status);
1223 
1224   /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
1225   /// Difference for unmatched callees that only present in one profile in a
1226   /// matched caller function.
1227   void updateForUnmatchedCallee(const sampleprof::FunctionSamples &Func,
1228                                 SampleOverlapStats &FuncOverlap,
1229                                 double &Difference, MatchStatus Status);
1230 
1231   /// This function updates sample overlap statistics of an overlap function in
1232   /// base and test profile. It also calculates a function-internal similarity
1233   /// FIS as follows:
1234   ///    For offsets i that have samples in at least one profile in this
1235   ///    function A, given BS(i) returned by computeBlockSimilarity(), compute
1236   ///    FIS(A) = (2.0 - sum_i(1.0 - BS(i))) / 2, ranging in [0.0f to 1.0f] with
1237   ///    0.0 meaning no overlap.
1238   double computeSampleFunctionInternalOverlap(
1239       const sampleprof::FunctionSamples &BaseFunc,
1240       const sampleprof::FunctionSamples &TestFunc,
1241       SampleOverlapStats &FuncOverlap);
1242 
1243   /// Function-level similarity (FS) is a weighted value over function internal
1244   /// similarity (FIS). This function computes a function's FS from its FIS by
1245   /// applying the weight.
1246   double weightForFuncSimilarity(double FuncSimilarity, uint64_t BaseFuncSample,
1247                                  uint64_t TestFuncSample) const;
1248 
1249   /// The function-level similarity FS(A) for a function A is computed as
1250   /// follows:
1251   ///     Compute a function-internal similarity FIS(A) by
1252   ///     computeSampleFunctionInternalOverlap(). Then, with the weight of
1253   ///     function A in base profile WB(A), and the weight of function A in test
1254   ///     profile WT(A), compute FS(A) = FIS(A) * (1.0 - fabs(WB(A) - WT(A)))
1255   ///     ranging in [0.0f to 1.0f] with 0.0 meaning no overlap.
1256   double
1257   computeSampleFunctionOverlap(const sampleprof::FunctionSamples *BaseFunc,
1258                                const sampleprof::FunctionSamples *TestFunc,
1259                                SampleOverlapStats *FuncOverlap,
1260                                uint64_t BaseFuncSample,
1261                                uint64_t TestFuncSample);
1262 
1263   /// Profile-level similarity (PS) is a weighted aggregate over function-level
1264   /// similarities (FS). This method weights the FS value by the function
1265   /// weights in the base and test profiles for the aggregation.
1266   double weightByImportance(double FuncSimilarity, uint64_t BaseFuncSample,
1267                             uint64_t TestFuncSample) const;
1268 };
1269 } // end anonymous namespace
1270 
1271 bool SampleOverlapAggregator::detectZeroSampleProfile(
1272     raw_fd_ostream &OS) const {
1273   bool HaveZeroSample = false;
1274   if (ProfOverlap.BaseSample == 0) {
1275     OS << "Sum of sample counts for profile " << BaseFilename << " is 0.\n";
1276     HaveZeroSample = true;
1277   }
1278   if (ProfOverlap.TestSample == 0) {
1279     OS << "Sum of sample counts for profile " << TestFilename << " is 0.\n";
1280     HaveZeroSample = true;
1281   }
1282   return HaveZeroSample;
1283 }
1284 
1285 double SampleOverlapAggregator::computeBlockSimilarity(
1286     uint64_t BaseSample, uint64_t TestSample,
1287     const SampleOverlapStats &FuncOverlap) const {
1288   double BaseFrac = 0.0;
1289   double TestFrac = 0.0;
1290   if (FuncOverlap.BaseSample > 0)
1291     BaseFrac = static_cast<double>(BaseSample) / FuncOverlap.BaseSample;
1292   if (FuncOverlap.TestSample > 0)
1293     TestFrac = static_cast<double>(TestSample) / FuncOverlap.TestSample;
1294   return 1.0 - std::fabs(BaseFrac - TestFrac);
1295 }
1296 
1297 void SampleOverlapAggregator::updateHotBlockOverlap(uint64_t BaseSample,
1298                                                     uint64_t TestSample,
1299                                                     uint64_t HotBlockCount) {
1300   bool IsBaseHot = (BaseSample >= BaseHotThreshold);
1301   bool IsTestHot = (TestSample >= TestHotThreshold);
1302   if (!IsBaseHot && !IsTestHot)
1303     return;
1304 
1305   HotBlockOverlap.UnionCount += HotBlockCount;
1306   if (IsBaseHot)
1307     HotBlockOverlap.BaseCount += HotBlockCount;
1308   if (IsTestHot)
1309     HotBlockOverlap.TestCount += HotBlockCount;
1310   if (IsBaseHot && IsTestHot)
1311     HotBlockOverlap.OverlapCount += HotBlockCount;
1312 }
1313 
1314 void SampleOverlapAggregator::getHotFunctions(
1315     const StringMap<FuncSampleStats> &ProfStats,
1316     StringMap<FuncSampleStats> &HotFunc, uint64_t HotThreshold) const {
1317   for (const auto &F : ProfStats) {
1318     if (isFunctionHot(F.second, HotThreshold))
1319       HotFunc.try_emplace(F.first(), F.second);
1320   }
1321 }
1322 
1323 void SampleOverlapAggregator::computeHotFuncOverlap() {
1324   StringMap<FuncSampleStats> BaseHotFunc;
1325   getHotFunctions(BaseStats, BaseHotFunc, BaseHotThreshold);
1326   HotFuncOverlap.BaseCount = BaseHotFunc.size();
1327 
1328   StringMap<FuncSampleStats> TestHotFunc;
1329   getHotFunctions(TestStats, TestHotFunc, TestHotThreshold);
1330   HotFuncOverlap.TestCount = TestHotFunc.size();
1331   HotFuncOverlap.UnionCount = HotFuncOverlap.TestCount;
1332 
1333   for (const auto &F : BaseHotFunc) {
1334     if (TestHotFunc.count(F.first()))
1335       ++HotFuncOverlap.OverlapCount;
1336     else
1337       ++HotFuncOverlap.UnionCount;
1338   }
1339 }
1340 
1341 void SampleOverlapAggregator::updateOverlapStatsForFunction(
1342     uint64_t BaseSample, uint64_t TestSample, uint64_t HotBlockCount,
1343     SampleOverlapStats &FuncOverlap, double &Difference, MatchStatus Status) {
1344   assert(Status != MS_None &&
1345          "Match status should be updated before updating overlap statistics");
1346   if (Status == MS_FirstUnique) {
1347     TestSample = 0;
1348     FuncOverlap.BaseUniqueSample += BaseSample;
1349   } else if (Status == MS_SecondUnique) {
1350     BaseSample = 0;
1351     FuncOverlap.TestUniqueSample += TestSample;
1352   } else {
1353     ++FuncOverlap.OverlapCount;
1354   }
1355 
1356   FuncOverlap.UnionSample += std::max(BaseSample, TestSample);
1357   FuncOverlap.OverlapSample += std::min(BaseSample, TestSample);
1358   Difference +=
1359       1.0 - computeBlockSimilarity(BaseSample, TestSample, FuncOverlap);
1360   updateHotBlockOverlap(BaseSample, TestSample, HotBlockCount);
1361 }
1362 
1363 void SampleOverlapAggregator::updateForUnmatchedCallee(
1364     const sampleprof::FunctionSamples &Func, SampleOverlapStats &FuncOverlap,
1365     double &Difference, MatchStatus Status) {
1366   assert((Status == MS_FirstUnique || Status == MS_SecondUnique) &&
1367          "Status must be either of the two unmatched cases");
1368   FuncSampleStats FuncStats;
1369   if (Status == MS_FirstUnique) {
1370     getFuncSampleStats(Func, FuncStats, BaseHotThreshold);
1371     updateOverlapStatsForFunction(FuncStats.SampleSum, 0,
1372                                   FuncStats.HotBlockCount, FuncOverlap,
1373                                   Difference, Status);
1374   } else {
1375     getFuncSampleStats(Func, FuncStats, TestHotThreshold);
1376     updateOverlapStatsForFunction(0, FuncStats.SampleSum,
1377                                   FuncStats.HotBlockCount, FuncOverlap,
1378                                   Difference, Status);
1379   }
1380 }
1381 
1382 double SampleOverlapAggregator::computeSampleFunctionInternalOverlap(
1383     const sampleprof::FunctionSamples &BaseFunc,
1384     const sampleprof::FunctionSamples &TestFunc,
1385     SampleOverlapStats &FuncOverlap) {
1386 
1387   using namespace sampleprof;
1388 
1389   double Difference = 0;
1390 
1391   // Accumulate Difference for regular line/block samples in the function.
1392   // We match them through sort-merge join algorithm because
1393   // FunctionSamples::getBodySamples() returns a map of sample counters ordered
1394   // by their offsets.
1395   MatchStep<BodySampleMap::const_iterator> BlockIterStep(
1396       BaseFunc.getBodySamples().cbegin(), BaseFunc.getBodySamples().cend(),
1397       TestFunc.getBodySamples().cbegin(), TestFunc.getBodySamples().cend());
1398   BlockIterStep.updateOneStep();
1399   while (!BlockIterStep.areBothFinished()) {
1400     uint64_t BaseSample =
1401         BlockIterStep.isFirstFinished()
1402             ? 0
1403             : BlockIterStep.getFirstIter()->second.getSamples();
1404     uint64_t TestSample =
1405         BlockIterStep.isSecondFinished()
1406             ? 0
1407             : BlockIterStep.getSecondIter()->second.getSamples();
1408     updateOverlapStatsForFunction(BaseSample, TestSample, 1, FuncOverlap,
1409                                   Difference, BlockIterStep.getMatchStatus());
1410 
1411     BlockIterStep.updateOneStep();
1412   }
1413 
1414   // Accumulate Difference for callsite lines in the function. We match
1415   // them through sort-merge algorithm because
1416   // FunctionSamples::getCallsiteSamples() returns a map of callsite records
1417   // ordered by their offsets.
1418   MatchStep<CallsiteSampleMap::const_iterator> CallsiteIterStep(
1419       BaseFunc.getCallsiteSamples().cbegin(),
1420       BaseFunc.getCallsiteSamples().cend(),
1421       TestFunc.getCallsiteSamples().cbegin(),
1422       TestFunc.getCallsiteSamples().cend());
1423   CallsiteIterStep.updateOneStep();
1424   while (!CallsiteIterStep.areBothFinished()) {
1425     MatchStatus CallsiteStepStatus = CallsiteIterStep.getMatchStatus();
1426     assert(CallsiteStepStatus != MS_None &&
1427            "Match status should be updated before entering loop body");
1428 
1429     if (CallsiteStepStatus != MS_Match) {
1430       auto Callsite = (CallsiteStepStatus == MS_FirstUnique)
1431                           ? CallsiteIterStep.getFirstIter()
1432                           : CallsiteIterStep.getSecondIter();
1433       for (const auto &F : Callsite->second)
1434         updateForUnmatchedCallee(F.second, FuncOverlap, Difference,
1435                                  CallsiteStepStatus);
1436     } else {
1437       // There may be multiple inlinees at the same offset, so we need to try
1438       // matching all of them. This match is implemented through sort-merge
1439       // algorithm because callsite records at the same offset are ordered by
1440       // function names.
1441       MatchStep<FunctionSamplesMap::const_iterator> CalleeIterStep(
1442           CallsiteIterStep.getFirstIter()->second.cbegin(),
1443           CallsiteIterStep.getFirstIter()->second.cend(),
1444           CallsiteIterStep.getSecondIter()->second.cbegin(),
1445           CallsiteIterStep.getSecondIter()->second.cend());
1446       CalleeIterStep.updateOneStep();
1447       while (!CalleeIterStep.areBothFinished()) {
1448         MatchStatus CalleeStepStatus = CalleeIterStep.getMatchStatus();
1449         if (CalleeStepStatus != MS_Match) {
1450           auto Callee = (CalleeStepStatus == MS_FirstUnique)
1451                             ? CalleeIterStep.getFirstIter()
1452                             : CalleeIterStep.getSecondIter();
1453           updateForUnmatchedCallee(Callee->second, FuncOverlap, Difference,
1454                                    CalleeStepStatus);
1455         } else {
1456           // An inlined function can contain other inlinees inside, so compute
1457           // the Difference recursively.
1458           Difference += 2.0 - 2 * computeSampleFunctionInternalOverlap(
1459                                       CalleeIterStep.getFirstIter()->second,
1460                                       CalleeIterStep.getSecondIter()->second,
1461                                       FuncOverlap);
1462         }
1463         CalleeIterStep.updateOneStep();
1464       }
1465     }
1466     CallsiteIterStep.updateOneStep();
1467   }
1468 
1469   // Difference reflects the total differences of line/block samples in this
1470   // function and ranges in [0.0f to 2.0f]. Take (2.0 - Difference) / 2 to
1471   // reflect the similarity between function profiles in [0.0f to 1.0f].
1472   return (2.0 - Difference) / 2;
1473 }
1474 
1475 double SampleOverlapAggregator::weightForFuncSimilarity(
1476     double FuncInternalSimilarity, uint64_t BaseFuncSample,
1477     uint64_t TestFuncSample) const {
1478   // Compute the weight as the distance between the function weights in two
1479   // profiles.
1480   double BaseFrac = 0.0;
1481   double TestFrac = 0.0;
1482   assert(ProfOverlap.BaseSample > 0 &&
1483          "Total samples in base profile should be greater than 0");
1484   BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample;
1485   assert(ProfOverlap.TestSample > 0 &&
1486          "Total samples in test profile should be greater than 0");
1487   TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample;
1488   double WeightDistance = std::fabs(BaseFrac - TestFrac);
1489 
1490   // Take WeightDistance into the similarity.
1491   return FuncInternalSimilarity * (1 - WeightDistance);
1492 }
1493 
1494 double
1495 SampleOverlapAggregator::weightByImportance(double FuncSimilarity,
1496                                             uint64_t BaseFuncSample,
1497                                             uint64_t TestFuncSample) const {
1498 
1499   double BaseFrac = 0.0;
1500   double TestFrac = 0.0;
1501   assert(ProfOverlap.BaseSample > 0 &&
1502          "Total samples in base profile should be greater than 0");
1503   BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample / 2.0;
1504   assert(ProfOverlap.TestSample > 0 &&
1505          "Total samples in test profile should be greater than 0");
1506   TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample / 2.0;
1507   return FuncSimilarity * (BaseFrac + TestFrac);
1508 }
1509 
1510 double SampleOverlapAggregator::computeSampleFunctionOverlap(
1511     const sampleprof::FunctionSamples *BaseFunc,
1512     const sampleprof::FunctionSamples *TestFunc,
1513     SampleOverlapStats *FuncOverlap, uint64_t BaseFuncSample,
1514     uint64_t TestFuncSample) {
1515   // Default function internal similarity before weighted, meaning two functions
1516   // has no overlap.
1517   const double DefaultFuncInternalSimilarity = 0;
1518   double FuncSimilarity;
1519   double FuncInternalSimilarity;
1520 
1521   // If BaseFunc or TestFunc is nullptr, it means the functions do not overlap.
1522   // In this case, we use DefaultFuncInternalSimilarity as the function internal
1523   // similarity.
1524   if (!BaseFunc || !TestFunc) {
1525     FuncInternalSimilarity = DefaultFuncInternalSimilarity;
1526   } else {
1527     assert(FuncOverlap != nullptr &&
1528            "FuncOverlap should be provided in this case");
1529     FuncInternalSimilarity = computeSampleFunctionInternalOverlap(
1530         *BaseFunc, *TestFunc, *FuncOverlap);
1531     // Now, FuncInternalSimilarity may be a little less than 0 due to
1532     // imprecision of floating point accumulations. Make it zero if the
1533     // difference is below Epsilon.
1534     FuncInternalSimilarity = (std::fabs(FuncInternalSimilarity - 0) < Epsilon)
1535                                  ? 0
1536                                  : FuncInternalSimilarity;
1537   }
1538   FuncSimilarity = weightForFuncSimilarity(FuncInternalSimilarity,
1539                                            BaseFuncSample, TestFuncSample);
1540   return FuncSimilarity;
1541 }
1542 
1543 void SampleOverlapAggregator::computeSampleProfileOverlap(raw_fd_ostream &OS) {
1544   using namespace sampleprof;
1545 
1546   StringMap<const FunctionSamples *> BaseFuncProf;
1547   const auto &BaseProfiles = BaseReader->getProfiles();
1548   for (const auto &BaseFunc : BaseProfiles) {
1549     BaseFuncProf.try_emplace(BaseFunc.second.getName(), &(BaseFunc.second));
1550   }
1551   ProfOverlap.UnionCount = BaseFuncProf.size();
1552 
1553   const auto &TestProfiles = TestReader->getProfiles();
1554   for (const auto &TestFunc : TestProfiles) {
1555     SampleOverlapStats FuncOverlap;
1556     FuncOverlap.TestName = TestFunc.second.getName();
1557     assert(TestStats.count(FuncOverlap.TestName) &&
1558            "TestStats should have records for all functions in test profile "
1559            "except inlinees");
1560     FuncOverlap.TestSample = TestStats[FuncOverlap.TestName].SampleSum;
1561 
1562     const auto Match = BaseFuncProf.find(FuncOverlap.TestName);
1563     if (Match == BaseFuncProf.end()) {
1564       const FuncSampleStats &FuncStats = TestStats[FuncOverlap.TestName];
1565       ++ProfOverlap.TestUniqueCount;
1566       ProfOverlap.TestUniqueSample += FuncStats.SampleSum;
1567       FuncOverlap.TestUniqueSample = FuncStats.SampleSum;
1568 
1569       updateHotBlockOverlap(0, FuncStats.SampleSum, FuncStats.HotBlockCount);
1570 
1571       double FuncSimilarity = computeSampleFunctionOverlap(
1572           nullptr, nullptr, nullptr, 0, FuncStats.SampleSum);
1573       ProfOverlap.Similarity +=
1574           weightByImportance(FuncSimilarity, 0, FuncStats.SampleSum);
1575 
1576       ++ProfOverlap.UnionCount;
1577       ProfOverlap.UnionSample += FuncStats.SampleSum;
1578     } else {
1579       ++ProfOverlap.OverlapCount;
1580 
1581       // Two functions match with each other. Compute function-level overlap and
1582       // aggregate them into profile-level overlap.
1583       FuncOverlap.BaseName = Match->second->getName();
1584       assert(BaseStats.count(FuncOverlap.BaseName) &&
1585              "BaseStats should have records for all functions in base profile "
1586              "except inlinees");
1587       FuncOverlap.BaseSample = BaseStats[FuncOverlap.BaseName].SampleSum;
1588 
1589       FuncOverlap.Similarity = computeSampleFunctionOverlap(
1590           Match->second, &TestFunc.second, &FuncOverlap, FuncOverlap.BaseSample,
1591           FuncOverlap.TestSample);
1592       ProfOverlap.Similarity +=
1593           weightByImportance(FuncOverlap.Similarity, FuncOverlap.BaseSample,
1594                              FuncOverlap.TestSample);
1595       ProfOverlap.OverlapSample += FuncOverlap.OverlapSample;
1596       ProfOverlap.UnionSample += FuncOverlap.UnionSample;
1597 
1598       // Accumulate the percentage of base unique and test unique samples into
1599       // ProfOverlap.
1600       ProfOverlap.BaseUniqueSample += FuncOverlap.BaseUniqueSample;
1601       ProfOverlap.TestUniqueSample += FuncOverlap.TestUniqueSample;
1602 
1603       // Remove matched base functions for later reporting functions not found
1604       // in test profile.
1605       BaseFuncProf.erase(Match);
1606     }
1607 
1608     // Print function-level similarity information if specified by options.
1609     assert(TestStats.count(FuncOverlap.TestName) &&
1610            "TestStats should have records for all functions in test profile "
1611            "except inlinees");
1612     if (TestStats[FuncOverlap.TestName].MaxSample >= FuncFilter.ValueCutoff ||
1613         (Match != BaseFuncProf.end() &&
1614          FuncOverlap.Similarity < LowSimilarityThreshold) ||
1615         (Match != BaseFuncProf.end() && !FuncFilter.NameFilter.empty() &&
1616          FuncOverlap.BaseName.find(FuncFilter.NameFilter) !=
1617              FuncOverlap.BaseName.npos)) {
1618       assert(ProfOverlap.BaseSample > 0 &&
1619              "Total samples in base profile should be greater than 0");
1620       FuncOverlap.BaseWeight =
1621           static_cast<double>(FuncOverlap.BaseSample) / ProfOverlap.BaseSample;
1622       assert(ProfOverlap.TestSample > 0 &&
1623              "Total samples in test profile should be greater than 0");
1624       FuncOverlap.TestWeight =
1625           static_cast<double>(FuncOverlap.TestSample) / ProfOverlap.TestSample;
1626       FuncSimilarityDump.emplace(FuncOverlap.BaseWeight, FuncOverlap);
1627     }
1628   }
1629 
1630   // Traverse through functions in base profile but not in test profile.
1631   for (const auto &F : BaseFuncProf) {
1632     assert(BaseStats.count(F.second->getName()) &&
1633            "BaseStats should have records for all functions in base profile "
1634            "except inlinees");
1635     const FuncSampleStats &FuncStats = BaseStats[F.second->getName()];
1636     ++ProfOverlap.BaseUniqueCount;
1637     ProfOverlap.BaseUniqueSample += FuncStats.SampleSum;
1638 
1639     updateHotBlockOverlap(FuncStats.SampleSum, 0, FuncStats.HotBlockCount);
1640 
1641     double FuncSimilarity = computeSampleFunctionOverlap(
1642         nullptr, nullptr, nullptr, FuncStats.SampleSum, 0);
1643     ProfOverlap.Similarity +=
1644         weightByImportance(FuncSimilarity, FuncStats.SampleSum, 0);
1645 
1646     ProfOverlap.UnionSample += FuncStats.SampleSum;
1647   }
1648 
1649   // Now, ProfSimilarity may be a little greater than 1 due to imprecision
1650   // of floating point accumulations. Make it 1.0 if the difference is below
1651   // Epsilon.
1652   ProfOverlap.Similarity = (std::fabs(ProfOverlap.Similarity - 1) < Epsilon)
1653                                ? 1
1654                                : ProfOverlap.Similarity;
1655 
1656   computeHotFuncOverlap();
1657 }
1658 
1659 void SampleOverlapAggregator::initializeSampleProfileOverlap() {
1660   const auto &BaseProf = BaseReader->getProfiles();
1661   for (const auto &I : BaseProf) {
1662     ++ProfOverlap.BaseCount;
1663     FuncSampleStats FuncStats;
1664     getFuncSampleStats(I.second, FuncStats, BaseHotThreshold);
1665     ProfOverlap.BaseSample += FuncStats.SampleSum;
1666     BaseStats.try_emplace(I.second.getName(), FuncStats);
1667   }
1668 
1669   const auto &TestProf = TestReader->getProfiles();
1670   for (const auto &I : TestProf) {
1671     ++ProfOverlap.TestCount;
1672     FuncSampleStats FuncStats;
1673     getFuncSampleStats(I.second, FuncStats, TestHotThreshold);
1674     ProfOverlap.TestSample += FuncStats.SampleSum;
1675     TestStats.try_emplace(I.second.getName(), FuncStats);
1676   }
1677 
1678   ProfOverlap.BaseName = StringRef(BaseFilename);
1679   ProfOverlap.TestName = StringRef(TestFilename);
1680 }
1681 
1682 void SampleOverlapAggregator::dumpFuncSimilarity(raw_fd_ostream &OS) const {
1683   using namespace sampleprof;
1684 
1685   if (FuncSimilarityDump.empty())
1686     return;
1687 
1688   formatted_raw_ostream FOS(OS);
1689   FOS << "Function-level details:\n";
1690   FOS << "Base weight";
1691   FOS.PadToColumn(TestWeightCol);
1692   FOS << "Test weight";
1693   FOS.PadToColumn(SimilarityCol);
1694   FOS << "Similarity";
1695   FOS.PadToColumn(OverlapCol);
1696   FOS << "Overlap";
1697   FOS.PadToColumn(BaseUniqueCol);
1698   FOS << "Base unique";
1699   FOS.PadToColumn(TestUniqueCol);
1700   FOS << "Test unique";
1701   FOS.PadToColumn(BaseSampleCol);
1702   FOS << "Base samples";
1703   FOS.PadToColumn(TestSampleCol);
1704   FOS << "Test samples";
1705   FOS.PadToColumn(FuncNameCol);
1706   FOS << "Function name\n";
1707   for (const auto &F : FuncSimilarityDump) {
1708     double OverlapPercent =
1709         F.second.UnionSample > 0
1710             ? static_cast<double>(F.second.OverlapSample) / F.second.UnionSample
1711             : 0;
1712     double BaseUniquePercent =
1713         F.second.BaseSample > 0
1714             ? static_cast<double>(F.second.BaseUniqueSample) /
1715                   F.second.BaseSample
1716             : 0;
1717     double TestUniquePercent =
1718         F.second.TestSample > 0
1719             ? static_cast<double>(F.second.TestUniqueSample) /
1720                   F.second.TestSample
1721             : 0;
1722 
1723     FOS << format("%.2f%%", F.second.BaseWeight * 100);
1724     FOS.PadToColumn(TestWeightCol);
1725     FOS << format("%.2f%%", F.second.TestWeight * 100);
1726     FOS.PadToColumn(SimilarityCol);
1727     FOS << format("%.2f%%", F.second.Similarity * 100);
1728     FOS.PadToColumn(OverlapCol);
1729     FOS << format("%.2f%%", OverlapPercent * 100);
1730     FOS.PadToColumn(BaseUniqueCol);
1731     FOS << format("%.2f%%", BaseUniquePercent * 100);
1732     FOS.PadToColumn(TestUniqueCol);
1733     FOS << format("%.2f%%", TestUniquePercent * 100);
1734     FOS.PadToColumn(BaseSampleCol);
1735     FOS << F.second.BaseSample;
1736     FOS.PadToColumn(TestSampleCol);
1737     FOS << F.second.TestSample;
1738     FOS.PadToColumn(FuncNameCol);
1739     FOS << F.second.TestName << "\n";
1740   }
1741 }
1742 
1743 void SampleOverlapAggregator::dumpProgramSummary(raw_fd_ostream &OS) const {
1744   OS << "Profile overlap infomation for base_profile: " << ProfOverlap.BaseName
1745      << " and test_profile: " << ProfOverlap.TestName << "\nProgram level:\n";
1746 
1747   OS << "  Whole program profile similarity: "
1748      << format("%.3f%%", ProfOverlap.Similarity * 100) << "\n";
1749 
1750   assert(ProfOverlap.UnionSample > 0 &&
1751          "Total samples in two profile should be greater than 0");
1752   double OverlapPercent =
1753       static_cast<double>(ProfOverlap.OverlapSample) / ProfOverlap.UnionSample;
1754   assert(ProfOverlap.BaseSample > 0 &&
1755          "Total samples in base profile should be greater than 0");
1756   double BaseUniquePercent = static_cast<double>(ProfOverlap.BaseUniqueSample) /
1757                              ProfOverlap.BaseSample;
1758   assert(ProfOverlap.TestSample > 0 &&
1759          "Total samples in test profile should be greater than 0");
1760   double TestUniquePercent = static_cast<double>(ProfOverlap.TestUniqueSample) /
1761                              ProfOverlap.TestSample;
1762 
1763   OS << "  Whole program sample overlap: "
1764      << format("%.3f%%", OverlapPercent * 100) << "\n";
1765   OS << "    percentage of samples unique in base profile: "
1766      << format("%.3f%%", BaseUniquePercent * 100) << "\n";
1767   OS << "    percentage of samples unique in test profile: "
1768      << format("%.3f%%", TestUniquePercent * 100) << "\n";
1769   OS << "    total samples in base profile: " << ProfOverlap.BaseSample << "\n"
1770      << "    total samples in test profile: " << ProfOverlap.TestSample << "\n";
1771 
1772   assert(ProfOverlap.UnionCount > 0 &&
1773          "There should be at least one function in two input profiles");
1774   double FuncOverlapPercent =
1775       static_cast<double>(ProfOverlap.OverlapCount) / ProfOverlap.UnionCount;
1776   OS << "  Function overlap: " << format("%.3f%%", FuncOverlapPercent * 100)
1777      << "\n";
1778   OS << "    overlap functions: " << ProfOverlap.OverlapCount << "\n";
1779   OS << "    functions unique in base profile: " << ProfOverlap.BaseUniqueCount
1780      << "\n";
1781   OS << "    functions unique in test profile: " << ProfOverlap.TestUniqueCount
1782      << "\n";
1783 }
1784 
1785 void SampleOverlapAggregator::dumpHotFuncAndBlockOverlap(
1786     raw_fd_ostream &OS) const {
1787   assert(HotFuncOverlap.UnionCount > 0 &&
1788          "There should be at least one hot function in two input profiles");
1789   OS << "  Hot-function overlap: "
1790      << format("%.3f%%", static_cast<double>(HotFuncOverlap.OverlapCount) /
1791                              HotFuncOverlap.UnionCount * 100)
1792      << "\n";
1793   OS << "    overlap hot functions: " << HotFuncOverlap.OverlapCount << "\n";
1794   OS << "    hot functions unique in base profile: "
1795      << HotFuncOverlap.BaseCount - HotFuncOverlap.OverlapCount << "\n";
1796   OS << "    hot functions unique in test profile: "
1797      << HotFuncOverlap.TestCount - HotFuncOverlap.OverlapCount << "\n";
1798 
1799   assert(HotBlockOverlap.UnionCount > 0 &&
1800          "There should be at least one hot block in two input profiles");
1801   OS << "  Hot-block overlap: "
1802      << format("%.3f%%", static_cast<double>(HotBlockOverlap.OverlapCount) /
1803                              HotBlockOverlap.UnionCount * 100)
1804      << "\n";
1805   OS << "    overlap hot blocks: " << HotBlockOverlap.OverlapCount << "\n";
1806   OS << "    hot blocks unique in base profile: "
1807      << HotBlockOverlap.BaseCount - HotBlockOverlap.OverlapCount << "\n";
1808   OS << "    hot blocks unique in test profile: "
1809      << HotBlockOverlap.TestCount - HotBlockOverlap.OverlapCount << "\n";
1810 }
1811 
1812 std::error_code SampleOverlapAggregator::loadProfiles() {
1813   using namespace sampleprof;
1814 
1815   LLVMContext Context;
1816   auto BaseReaderOrErr = SampleProfileReader::create(BaseFilename, Context);
1817   if (std::error_code EC = BaseReaderOrErr.getError())
1818     exitWithErrorCode(EC, BaseFilename);
1819 
1820   auto TestReaderOrErr = SampleProfileReader::create(TestFilename, Context);
1821   if (std::error_code EC = TestReaderOrErr.getError())
1822     exitWithErrorCode(EC, TestFilename);
1823 
1824   BaseReader = std::move(BaseReaderOrErr.get());
1825   TestReader = std::move(TestReaderOrErr.get());
1826 
1827   if (std::error_code EC = BaseReader->read())
1828     exitWithErrorCode(EC, BaseFilename);
1829   if (std::error_code EC = TestReader->read())
1830     exitWithErrorCode(EC, TestFilename);
1831   if (BaseReader->profileIsProbeBased() != TestReader->profileIsProbeBased())
1832     exitWithError(
1833         "cannot compare probe-based profile with non-probe-based profile");
1834 
1835   // Load BaseHotThreshold and TestHotThreshold as 99-percentile threshold in
1836   // profile summary.
1837   const uint64_t HotCutoff = 990000;
1838   ProfileSummary &BasePS = BaseReader->getSummary();
1839   for (const auto &SummaryEntry : BasePS.getDetailedSummary()) {
1840     if (SummaryEntry.Cutoff == HotCutoff) {
1841       BaseHotThreshold = SummaryEntry.MinCount;
1842       break;
1843     }
1844   }
1845 
1846   ProfileSummary &TestPS = TestReader->getSummary();
1847   for (const auto &SummaryEntry : TestPS.getDetailedSummary()) {
1848     if (SummaryEntry.Cutoff == HotCutoff) {
1849       TestHotThreshold = SummaryEntry.MinCount;
1850       break;
1851     }
1852   }
1853   return std::error_code();
1854 }
1855 
1856 void overlapSampleProfile(const std::string &BaseFilename,
1857                           const std::string &TestFilename,
1858                           const OverlapFuncFilters &FuncFilter,
1859                           uint64_t SimilarityCutoff, raw_fd_ostream &OS) {
1860   using namespace sampleprof;
1861 
1862   // We use 0.000005 to initialize OverlapAggr.Epsilon because the final metrics
1863   // report 2--3 places after decimal point in percentage numbers.
1864   SampleOverlapAggregator OverlapAggr(
1865       BaseFilename, TestFilename,
1866       static_cast<double>(SimilarityCutoff) / 1000000, 0.000005, FuncFilter);
1867   if (std::error_code EC = OverlapAggr.loadProfiles())
1868     exitWithErrorCode(EC);
1869 
1870   OverlapAggr.initializeSampleProfileOverlap();
1871   if (OverlapAggr.detectZeroSampleProfile(OS))
1872     return;
1873 
1874   OverlapAggr.computeSampleProfileOverlap(OS);
1875 
1876   OverlapAggr.dumpProgramSummary(OS);
1877   OverlapAggr.dumpHotFuncAndBlockOverlap(OS);
1878   OverlapAggr.dumpFuncSimilarity(OS);
1879 }
1880 
1881 static int overlap_main(int argc, const char *argv[]) {
1882   cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
1883                                     cl::desc("<base profile file>"));
1884   cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
1885                                     cl::desc("<test profile file>"));
1886   cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
1887                               cl::desc("Output file"));
1888   cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
1889   cl::opt<bool> IsCS("cs", cl::init(false),
1890                      cl::desc("For context sensitive counts"));
1891   cl::opt<unsigned long long> ValueCutoff(
1892       "value-cutoff", cl::init(-1),
1893       cl::desc(
1894           "Function level overlap information for every function in test "
1895           "profile with max count value greater then the parameter value"));
1896   cl::opt<std::string> FuncNameFilter(
1897       "function",
1898       cl::desc("Function level overlap information for matching functions"));
1899   cl::opt<unsigned long long> SimilarityCutoff(
1900       "similarity-cutoff", cl::init(0),
1901       cl::desc(
1902           "For sample profiles, list function names for overlapped functions "
1903           "with similarities below the cutoff (percentage times 10000)."));
1904   cl::opt<ProfileKinds> ProfileKind(
1905       cl::desc("Profile kind:"), cl::init(instr),
1906       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
1907                  clEnumVal(sample, "Sample profile")));
1908   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
1909 
1910   std::error_code EC;
1911   raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_Text);
1912   if (EC)
1913     exitWithErrorCode(EC, Output);
1914 
1915   if (ProfileKind == instr)
1916     overlapInstrProfile(BaseFilename, TestFilename,
1917                         OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
1918                         IsCS);
1919   else
1920     overlapSampleProfile(BaseFilename, TestFilename,
1921                          OverlapFuncFilters{ValueCutoff, FuncNameFilter},
1922                          SimilarityCutoff, OS);
1923 
1924   return 0;
1925 }
1926 
1927 typedef struct ValueSitesStats {
1928   ValueSitesStats()
1929       : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
1930         TotalNumValues(0) {}
1931   uint64_t TotalNumValueSites;
1932   uint64_t TotalNumValueSitesWithValueProfile;
1933   uint64_t TotalNumValues;
1934   std::vector<unsigned> ValueSitesHistogram;
1935 } ValueSitesStats;
1936 
1937 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
1938                                   ValueSitesStats &Stats, raw_fd_ostream &OS,
1939                                   InstrProfSymtab *Symtab) {
1940   uint32_t NS = Func.getNumValueSites(VK);
1941   Stats.TotalNumValueSites += NS;
1942   for (size_t I = 0; I < NS; ++I) {
1943     uint32_t NV = Func.getNumValueDataForSite(VK, I);
1944     std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
1945     Stats.TotalNumValues += NV;
1946     if (NV) {
1947       Stats.TotalNumValueSitesWithValueProfile++;
1948       if (NV > Stats.ValueSitesHistogram.size())
1949         Stats.ValueSitesHistogram.resize(NV, 0);
1950       Stats.ValueSitesHistogram[NV - 1]++;
1951     }
1952 
1953     uint64_t SiteSum = 0;
1954     for (uint32_t V = 0; V < NV; V++)
1955       SiteSum += VD[V].Count;
1956     if (SiteSum == 0)
1957       SiteSum = 1;
1958 
1959     for (uint32_t V = 0; V < NV; V++) {
1960       OS << "\t[ " << format("%2u", I) << ", ";
1961       if (Symtab == nullptr)
1962         OS << format("%4" PRIu64, VD[V].Value);
1963       else
1964         OS << Symtab->getFuncName(VD[V].Value);
1965       OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
1966          << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
1967     }
1968   }
1969 }
1970 
1971 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
1972                                 ValueSitesStats &Stats) {
1973   OS << "  Total number of sites: " << Stats.TotalNumValueSites << "\n";
1974   OS << "  Total number of sites with values: "
1975      << Stats.TotalNumValueSitesWithValueProfile << "\n";
1976   OS << "  Total number of profiled values: " << Stats.TotalNumValues << "\n";
1977 
1978   OS << "  Value sites histogram:\n\tNumTargets, SiteCount\n";
1979   for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
1980     if (Stats.ValueSitesHistogram[I] > 0)
1981       OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
1982   }
1983 }
1984 
1985 static int showInstrProfile(const std::string &Filename, bool ShowCounts,
1986                             uint32_t TopN, bool ShowIndirectCallTargets,
1987                             bool ShowMemOPSizes, bool ShowDetailedSummary,
1988                             std::vector<uint32_t> DetailedSummaryCutoffs,
1989                             bool ShowAllFunctions, bool ShowCS,
1990                             uint64_t ValueCutoff, bool OnlyListBelow,
1991                             const std::string &ShowFunction, bool TextFormat,
1992                             raw_fd_ostream &OS) {
1993   auto ReaderOrErr = InstrProfReader::create(Filename);
1994   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
1995   if (ShowDetailedSummary && Cutoffs.empty()) {
1996     Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
1997   }
1998   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
1999   if (Error E = ReaderOrErr.takeError())
2000     exitWithError(std::move(E), Filename);
2001 
2002   auto Reader = std::move(ReaderOrErr.get());
2003   bool IsIRInstr = Reader->isIRLevelProfile();
2004   size_t ShownFunctions = 0;
2005   size_t BelowCutoffFunctions = 0;
2006   int NumVPKind = IPVK_Last - IPVK_First + 1;
2007   std::vector<ValueSitesStats> VPStats(NumVPKind);
2008 
2009   auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
2010                    const std::pair<std::string, uint64_t> &v2) {
2011     return v1.second > v2.second;
2012   };
2013 
2014   std::priority_queue<std::pair<std::string, uint64_t>,
2015                       std::vector<std::pair<std::string, uint64_t>>,
2016                       decltype(MinCmp)>
2017       HottestFuncs(MinCmp);
2018 
2019   if (!TextFormat && OnlyListBelow) {
2020     OS << "The list of functions with the maximum counter less than "
2021        << ValueCutoff << ":\n";
2022   }
2023 
2024   // Add marker so that IR-level instrumentation round-trips properly.
2025   if (TextFormat && IsIRInstr)
2026     OS << ":ir\n";
2027 
2028   for (const auto &Func : *Reader) {
2029     if (Reader->isIRLevelProfile()) {
2030       bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
2031       if (FuncIsCS != ShowCS)
2032         continue;
2033     }
2034     bool Show =
2035         ShowAllFunctions || (!ShowFunction.empty() &&
2036                              Func.Name.find(ShowFunction) != Func.Name.npos);
2037 
2038     bool doTextFormatDump = (Show && TextFormat);
2039 
2040     if (doTextFormatDump) {
2041       InstrProfSymtab &Symtab = Reader->getSymtab();
2042       InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
2043                                          OS);
2044       continue;
2045     }
2046 
2047     assert(Func.Counts.size() > 0 && "function missing entry counter");
2048     Builder.addRecord(Func);
2049 
2050     uint64_t FuncMax = 0;
2051     uint64_t FuncSum = 0;
2052     for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
2053       if (Func.Counts[I] == (uint64_t)-1)
2054         continue;
2055       FuncMax = std::max(FuncMax, Func.Counts[I]);
2056       FuncSum += Func.Counts[I];
2057     }
2058 
2059     if (FuncMax < ValueCutoff) {
2060       ++BelowCutoffFunctions;
2061       if (OnlyListBelow) {
2062         OS << "  " << Func.Name << ": (Max = " << FuncMax
2063            << " Sum = " << FuncSum << ")\n";
2064       }
2065       continue;
2066     } else if (OnlyListBelow)
2067       continue;
2068 
2069     if (TopN) {
2070       if (HottestFuncs.size() == TopN) {
2071         if (HottestFuncs.top().second < FuncMax) {
2072           HottestFuncs.pop();
2073           HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
2074         }
2075       } else
2076         HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
2077     }
2078 
2079     if (Show) {
2080       if (!ShownFunctions)
2081         OS << "Counters:\n";
2082 
2083       ++ShownFunctions;
2084 
2085       OS << "  " << Func.Name << ":\n"
2086          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
2087          << "    Counters: " << Func.Counts.size() << "\n";
2088       if (!IsIRInstr)
2089         OS << "    Function count: " << Func.Counts[0] << "\n";
2090 
2091       if (ShowIndirectCallTargets)
2092         OS << "    Indirect Call Site Count: "
2093            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
2094 
2095       uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
2096       if (ShowMemOPSizes && NumMemOPCalls > 0)
2097         OS << "    Number of Memory Intrinsics Calls: " << NumMemOPCalls
2098            << "\n";
2099 
2100       if (ShowCounts) {
2101         OS << "    Block counts: [";
2102         size_t Start = (IsIRInstr ? 0 : 1);
2103         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
2104           OS << (I == Start ? "" : ", ") << Func.Counts[I];
2105         }
2106         OS << "]\n";
2107       }
2108 
2109       if (ShowIndirectCallTargets) {
2110         OS << "    Indirect Target Results:\n";
2111         traverseAllValueSites(Func, IPVK_IndirectCallTarget,
2112                               VPStats[IPVK_IndirectCallTarget], OS,
2113                               &(Reader->getSymtab()));
2114       }
2115 
2116       if (ShowMemOPSizes && NumMemOPCalls > 0) {
2117         OS << "    Memory Intrinsic Size Results:\n";
2118         traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
2119                               nullptr);
2120       }
2121     }
2122   }
2123   if (Reader->hasError())
2124     exitWithError(Reader->getError(), Filename);
2125 
2126   if (TextFormat)
2127     return 0;
2128   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
2129   bool IsIR = Reader->isIRLevelProfile();
2130   OS << "Instrumentation level: " << (IsIR ? "IR" : "Front-end");
2131   if (IsIR)
2132     OS << "  entry_first = " << Reader->instrEntryBBEnabled();
2133   OS << "\n";
2134   if (ShowAllFunctions || !ShowFunction.empty())
2135     OS << "Functions shown: " << ShownFunctions << "\n";
2136   OS << "Total functions: " << PS->getNumFunctions() << "\n";
2137   if (ValueCutoff > 0) {
2138     OS << "Number of functions with maximum count (< " << ValueCutoff
2139        << "): " << BelowCutoffFunctions << "\n";
2140     OS << "Number of functions with maximum count (>= " << ValueCutoff
2141        << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
2142   }
2143   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
2144   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
2145 
2146   if (TopN) {
2147     std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
2148     while (!HottestFuncs.empty()) {
2149       SortedHottestFuncs.emplace_back(HottestFuncs.top());
2150       HottestFuncs.pop();
2151     }
2152     OS << "Top " << TopN
2153        << " functions with the largest internal block counts: \n";
2154     for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
2155       OS << "  " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
2156   }
2157 
2158   if (ShownFunctions && ShowIndirectCallTargets) {
2159     OS << "Statistics for indirect call sites profile:\n";
2160     showValueSitesStats(OS, IPVK_IndirectCallTarget,
2161                         VPStats[IPVK_IndirectCallTarget]);
2162   }
2163 
2164   if (ShownFunctions && ShowMemOPSizes) {
2165     OS << "Statistics for memory intrinsic calls sizes profile:\n";
2166     showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
2167   }
2168 
2169   if (ShowDetailedSummary) {
2170     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
2171     OS << "Total count: " << PS->getTotalCount() << "\n";
2172     PS->printDetailedSummary(OS);
2173   }
2174   return 0;
2175 }
2176 
2177 static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
2178                             raw_fd_ostream &OS) {
2179   if (!Reader->dumpSectionInfo(OS)) {
2180     WithColor::warning() << "-show-sec-info-only is only supported for "
2181                          << "sample profile in extbinary format and is "
2182                          << "ignored for other formats.\n";
2183     return;
2184   }
2185 }
2186 
2187 namespace {
2188 struct HotFuncInfo {
2189   StringRef FuncName;
2190   uint64_t TotalCount;
2191   double TotalCountPercent;
2192   uint64_t MaxCount;
2193   uint64_t EntryCount;
2194 
2195   HotFuncInfo()
2196       : FuncName(), TotalCount(0), TotalCountPercent(0.0f), MaxCount(0),
2197         EntryCount(0) {}
2198 
2199   HotFuncInfo(StringRef FN, uint64_t TS, double TSP, uint64_t MS, uint64_t ES)
2200       : FuncName(FN), TotalCount(TS), TotalCountPercent(TSP), MaxCount(MS),
2201         EntryCount(ES) {}
2202 };
2203 } // namespace
2204 
2205 // Print out detailed information about hot functions in PrintValues vector.
2206 // Users specify titles and offset of every columns through ColumnTitle and
2207 // ColumnOffset. The size of ColumnTitle and ColumnOffset need to be the same
2208 // and at least 4. Besides, users can optionally give a HotFuncMetric string to
2209 // print out or let it be an empty string.
2210 static void dumpHotFunctionList(const std::vector<std::string> &ColumnTitle,
2211                                 const std::vector<int> &ColumnOffset,
2212                                 const std::vector<HotFuncInfo> &PrintValues,
2213                                 uint64_t HotFuncCount, uint64_t TotalFuncCount,
2214                                 uint64_t HotProfCount, uint64_t TotalProfCount,
2215                                 const std::string &HotFuncMetric,
2216                                 raw_fd_ostream &OS) {
2217   assert(ColumnOffset.size() == ColumnTitle.size() &&
2218          "ColumnOffset and ColumnTitle should have the same size");
2219   assert(ColumnTitle.size() >= 4 &&
2220          "ColumnTitle should have at least 4 elements");
2221   assert(TotalFuncCount > 0 &&
2222          "There should be at least one function in the profile");
2223   double TotalProfPercent = 0;
2224   if (TotalProfCount > 0)
2225     TotalProfPercent = static_cast<double>(HotProfCount) / TotalProfCount * 100;
2226 
2227   formatted_raw_ostream FOS(OS);
2228   FOS << HotFuncCount << " out of " << TotalFuncCount
2229       << " functions with profile ("
2230       << format("%.2f%%",
2231                 (static_cast<double>(HotFuncCount) / TotalFuncCount * 100))
2232       << ") are considered hot functions";
2233   if (!HotFuncMetric.empty())
2234     FOS << " (" << HotFuncMetric << ")";
2235   FOS << ".\n";
2236   FOS << HotProfCount << " out of " << TotalProfCount << " profile counts ("
2237       << format("%.2f%%", TotalProfPercent) << ") are from hot functions.\n";
2238 
2239   for (size_t I = 0; I < ColumnTitle.size(); ++I) {
2240     FOS.PadToColumn(ColumnOffset[I]);
2241     FOS << ColumnTitle[I];
2242   }
2243   FOS << "\n";
2244 
2245   for (const HotFuncInfo &R : PrintValues) {
2246     FOS.PadToColumn(ColumnOffset[0]);
2247     FOS << R.TotalCount << " (" << format("%.2f%%", R.TotalCountPercent) << ")";
2248     FOS.PadToColumn(ColumnOffset[1]);
2249     FOS << R.MaxCount;
2250     FOS.PadToColumn(ColumnOffset[2]);
2251     FOS << R.EntryCount;
2252     FOS.PadToColumn(ColumnOffset[3]);
2253     FOS << R.FuncName << "\n";
2254   }
2255   return;
2256 }
2257 
2258 static int
2259 showHotFunctionList(const StringMap<sampleprof::FunctionSamples> &Profiles,
2260                     ProfileSummary &PS, raw_fd_ostream &OS) {
2261   using namespace sampleprof;
2262 
2263   const uint32_t HotFuncCutoff = 990000;
2264   auto &SummaryVector = PS.getDetailedSummary();
2265   uint64_t MinCountThreshold = 0;
2266   for (const ProfileSummaryEntry &SummaryEntry : SummaryVector) {
2267     if (SummaryEntry.Cutoff == HotFuncCutoff) {
2268       MinCountThreshold = SummaryEntry.MinCount;
2269       break;
2270     }
2271   }
2272 
2273   // Traverse all functions in the profile and keep only hot functions.
2274   // The following loop also calculates the sum of total samples of all
2275   // functions.
2276   std::multimap<uint64_t, std::pair<const FunctionSamples *, const uint64_t>,
2277                 std::greater<uint64_t>>
2278       HotFunc;
2279   uint64_t ProfileTotalSample = 0;
2280   uint64_t HotFuncSample = 0;
2281   uint64_t HotFuncCount = 0;
2282 
2283   for (const auto &I : Profiles) {
2284     FuncSampleStats FuncStats;
2285     const FunctionSamples &FuncProf = I.second;
2286     ProfileTotalSample += FuncProf.getTotalSamples();
2287     getFuncSampleStats(FuncProf, FuncStats, MinCountThreshold);
2288 
2289     if (isFunctionHot(FuncStats, MinCountThreshold)) {
2290       HotFunc.emplace(FuncProf.getTotalSamples(),
2291                       std::make_pair(&(I.second), FuncStats.MaxSample));
2292       HotFuncSample += FuncProf.getTotalSamples();
2293       ++HotFuncCount;
2294     }
2295   }
2296 
2297   std::vector<std::string> ColumnTitle{"Total sample (%)", "Max sample",
2298                                        "Entry sample", "Function name"};
2299   std::vector<int> ColumnOffset{0, 24, 42, 58};
2300   std::string Metric =
2301       std::string("max sample >= ") + std::to_string(MinCountThreshold);
2302   std::vector<HotFuncInfo> PrintValues;
2303   for (const auto &FuncPair : HotFunc) {
2304     const FunctionSamples &Func = *FuncPair.second.first;
2305     double TotalSamplePercent =
2306         (ProfileTotalSample > 0)
2307             ? (Func.getTotalSamples() * 100.0) / ProfileTotalSample
2308             : 0;
2309     PrintValues.emplace_back(
2310         HotFuncInfo(Func.getName(), Func.getTotalSamples(), TotalSamplePercent,
2311                     FuncPair.second.second, Func.getEntrySamples()));
2312   }
2313   dumpHotFunctionList(ColumnTitle, ColumnOffset, PrintValues, HotFuncCount,
2314                       Profiles.size(), HotFuncSample, ProfileTotalSample,
2315                       Metric, OS);
2316 
2317   return 0;
2318 }
2319 
2320 static int showSampleProfile(const std::string &Filename, bool ShowCounts,
2321                              bool ShowAllFunctions, bool ShowDetailedSummary,
2322                              const std::string &ShowFunction,
2323                              bool ShowProfileSymbolList,
2324                              bool ShowSectionInfoOnly, bool ShowHotFuncList,
2325                              raw_fd_ostream &OS) {
2326   using namespace sampleprof;
2327   LLVMContext Context;
2328   auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
2329   if (std::error_code EC = ReaderOrErr.getError())
2330     exitWithErrorCode(EC, Filename);
2331 
2332   auto Reader = std::move(ReaderOrErr.get());
2333 
2334   if (ShowSectionInfoOnly) {
2335     showSectionInfo(Reader.get(), OS);
2336     return 0;
2337   }
2338 
2339   if (std::error_code EC = Reader->read())
2340     exitWithErrorCode(EC, Filename);
2341 
2342   if (ShowAllFunctions || ShowFunction.empty())
2343     Reader->dump(OS);
2344   else
2345     Reader->dumpFunctionProfile(ShowFunction, OS);
2346 
2347   if (ShowProfileSymbolList) {
2348     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
2349         Reader->getProfileSymbolList();
2350     ReaderList->dump(OS);
2351   }
2352 
2353   if (ShowDetailedSummary) {
2354     auto &PS = Reader->getSummary();
2355     PS.printSummary(OS);
2356     PS.printDetailedSummary(OS);
2357   }
2358 
2359   if (ShowHotFuncList)
2360     showHotFunctionList(Reader->getProfiles(), Reader->getSummary(), OS);
2361 
2362   return 0;
2363 }
2364 
2365 static int show_main(int argc, const char *argv[]) {
2366   cl::opt<std::string> Filename(cl::Positional, cl::Required,
2367                                 cl::desc("<profdata-file>"));
2368 
2369   cl::opt<bool> ShowCounts("counts", cl::init(false),
2370                            cl::desc("Show counter values for shown functions"));
2371   cl::opt<bool> TextFormat(
2372       "text", cl::init(false),
2373       cl::desc("Show instr profile data in text dump format"));
2374   cl::opt<bool> ShowIndirectCallTargets(
2375       "ic-targets", cl::init(false),
2376       cl::desc("Show indirect call site target values for shown functions"));
2377   cl::opt<bool> ShowMemOPSizes(
2378       "memop-sizes", cl::init(false),
2379       cl::desc("Show the profiled sizes of the memory intrinsic calls "
2380                "for shown functions"));
2381   cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
2382                                     cl::desc("Show detailed profile summary"));
2383   cl::list<uint32_t> DetailedSummaryCutoffs(
2384       cl::CommaSeparated, "detailed-summary-cutoffs",
2385       cl::desc(
2386           "Cutoff percentages (times 10000) for generating detailed summary"),
2387       cl::value_desc("800000,901000,999999"));
2388   cl::opt<bool> ShowHotFuncList(
2389       "hot-func-list", cl::init(false),
2390       cl::desc("Show profile summary of a list of hot functions"));
2391   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
2392                                  cl::desc("Details for every function"));
2393   cl::opt<bool> ShowCS("showcs", cl::init(false),
2394                        cl::desc("Show context sensitive counts"));
2395   cl::opt<std::string> ShowFunction("function",
2396                                     cl::desc("Details for matching functions"));
2397 
2398   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
2399                                       cl::init("-"), cl::desc("Output file"));
2400   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
2401                             cl::aliasopt(OutputFilename));
2402   cl::opt<ProfileKinds> ProfileKind(
2403       cl::desc("Profile kind:"), cl::init(instr),
2404       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
2405                  clEnumVal(sample, "Sample profile")));
2406   cl::opt<uint32_t> TopNFunctions(
2407       "topn", cl::init(0),
2408       cl::desc("Show the list of functions with the largest internal counts"));
2409   cl::opt<uint32_t> ValueCutoff(
2410       "value-cutoff", cl::init(0),
2411       cl::desc("Set the count value cutoff. Functions with the maximum count "
2412                "less than this value will not be printed out. (Default is 0)"));
2413   cl::opt<bool> OnlyListBelow(
2414       "list-below-cutoff", cl::init(false),
2415       cl::desc("Only output names of functions whose max count values are "
2416                "below the cutoff value"));
2417   cl::opt<bool> ShowProfileSymbolList(
2418       "show-prof-sym-list", cl::init(false),
2419       cl::desc("Show profile symbol list if it exists in the profile. "));
2420   cl::opt<bool> ShowSectionInfoOnly(
2421       "show-sec-info-only", cl::init(false),
2422       cl::desc("Show the information of each section in the sample profile. "
2423                "The flag is only usable when the sample profile is in "
2424                "extbinary format"));
2425 
2426   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
2427 
2428   if (OutputFilename.empty())
2429     OutputFilename = "-";
2430 
2431   if (!Filename.compare(OutputFilename)) {
2432     errs() << sys::path::filename(argv[0])
2433            << ": Input file name cannot be the same as the output file name!\n";
2434     return 1;
2435   }
2436 
2437   std::error_code EC;
2438   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_Text);
2439   if (EC)
2440     exitWithErrorCode(EC, OutputFilename);
2441 
2442   if (ShowAllFunctions && !ShowFunction.empty())
2443     WithColor::warning() << "-function argument ignored: showing all functions\n";
2444 
2445   if (ProfileKind == instr)
2446     return showInstrProfile(Filename, ShowCounts, TopNFunctions,
2447                             ShowIndirectCallTargets, ShowMemOPSizes,
2448                             ShowDetailedSummary, DetailedSummaryCutoffs,
2449                             ShowAllFunctions, ShowCS, ValueCutoff,
2450                             OnlyListBelow, ShowFunction, TextFormat, OS);
2451   else
2452     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
2453                              ShowDetailedSummary, ShowFunction,
2454                              ShowProfileSymbolList, ShowSectionInfoOnly,
2455                              ShowHotFuncList, OS);
2456 }
2457 
2458 int main(int argc, const char *argv[]) {
2459   InitLLVM X(argc, argv);
2460 
2461   StringRef ProgName(sys::path::filename(argv[0]));
2462   if (argc > 1) {
2463     int (*func)(int, const char *[]) = nullptr;
2464 
2465     if (strcmp(argv[1], "merge") == 0)
2466       func = merge_main;
2467     else if (strcmp(argv[1], "show") == 0)
2468       func = show_main;
2469     else if (strcmp(argv[1], "overlap") == 0)
2470       func = overlap_main;
2471 
2472     if (func) {
2473       std::string Invocation(ProgName.str() + " " + argv[1]);
2474       argv[1] = Invocation.c_str();
2475       return func(argc - 1, argv + 1);
2476     }
2477 
2478     if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
2479         strcmp(argv[1], "--help") == 0) {
2480 
2481       errs() << "OVERVIEW: LLVM profile data tools\n\n"
2482              << "USAGE: " << ProgName << " <command> [args...]\n"
2483              << "USAGE: " << ProgName << " <command> -help\n\n"
2484              << "See each individual command --help for more details.\n"
2485              << "Available commands: merge, show, overlap\n";
2486       return 0;
2487     }
2488   }
2489 
2490   if (argc < 2)
2491     errs() << ProgName << ": No command specified!\n";
2492   else
2493     errs() << ProgName << ": Unknown command!\n";
2494 
2495   errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
2496   return 1;
2497 }
2498