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