xref: /llvm-project/llvm/tools/llvm-profdata/llvm-profdata.cpp (revision a2453097e3b4010162efacb4e7edcb121da8607f)
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/Debuginfod/HTTPClient.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/MemProfReader.h"
24 #include "llvm/ProfileData/MemProfYAML.h"
25 #include "llvm/ProfileData/ProfileCommon.h"
26 #include "llvm/ProfileData/SampleProfReader.h"
27 #include "llvm/ProfileData/SampleProfWriter.h"
28 #include "llvm/Support/BalancedPartitioning.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Discriminator.h"
31 #include "llvm/Support/Errc.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/LLVMDriver.h"
36 #include "llvm/Support/MD5.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Regex.h"
40 #include "llvm/Support/ThreadPool.h"
41 #include "llvm/Support/Threading.h"
42 #include "llvm/Support/VirtualFileSystem.h"
43 #include "llvm/Support/WithColor.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <algorithm>
46 #include <cmath>
47 #include <optional>
48 #include <queue>
49 
50 using namespace llvm;
51 using ProfCorrelatorKind = InstrProfCorrelator::ProfCorrelatorKind;
52 
53 // https://llvm.org/docs/CommandGuide/llvm-profdata.html has documentations
54 // on each subcommand.
55 cl::SubCommand ShowSubcommand(
56     "show",
57     "Takes a profile data file and displays the profiles. See detailed "
58     "documentation in "
59     "https://llvm.org/docs/CommandGuide/llvm-profdata.html#profdata-show");
60 cl::SubCommand OrderSubcommand(
61     "order",
62     "Reads temporal profiling traces from a profile and outputs a function "
63     "order that reduces the number of page faults for those traces. See "
64     "detailed documentation in "
65     "https://llvm.org/docs/CommandGuide/llvm-profdata.html#profdata-order");
66 cl::SubCommand OverlapSubcommand(
67     "overlap",
68     "Computes and displays the overlap between two profiles. See detailed "
69     "documentation in "
70     "https://llvm.org/docs/CommandGuide/llvm-profdata.html#profdata-overlap");
71 cl::SubCommand MergeSubcommand(
72     "merge",
73     "Takes several profiles and merge them together. See detailed "
74     "documentation in "
75     "https://llvm.org/docs/CommandGuide/llvm-profdata.html#profdata-merge");
76 
77 namespace {
78 enum ProfileKinds { instr, sample, memory };
79 enum FailureMode { warnOnly, failIfAnyAreInvalid, failIfAllAreInvalid };
80 
81 enum ProfileFormat {
82   PF_None = 0,
83   PF_Text,
84   PF_Compact_Binary, // Deprecated
85   PF_Ext_Binary,
86   PF_GCC,
87   PF_Binary
88 };
89 
90 enum class ShowFormat { Text, Json, Yaml };
91 } // namespace
92 
93 // Common options.
94 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
95                                     cl::init("-"), cl::desc("Output file"),
96                                     cl::sub(ShowSubcommand),
97                                     cl::sub(OrderSubcommand),
98                                     cl::sub(OverlapSubcommand),
99                                     cl::sub(MergeSubcommand));
100 // NOTE: cl::alias must not have cl::sub(), since aliased option's cl::sub()
101 // will be used. llvm::cl::alias::done() method asserts this condition.
102 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
103                           cl::aliasopt(OutputFilename));
104 
105 // Options common to at least two commands.
106 cl::opt<ProfileKinds> ProfileKind(
107     cl::desc("Profile kind:"), cl::sub(MergeSubcommand),
108     cl::sub(OverlapSubcommand), cl::init(instr),
109     cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
110                clEnumVal(sample, "Sample profile")));
111 cl::opt<std::string> Filename(cl::Positional, cl::desc("<profdata-file>"),
112                               cl::sub(ShowSubcommand),
113                               cl::sub(OrderSubcommand));
114 cl::opt<unsigned> MaxDbgCorrelationWarnings(
115     "max-debug-info-correlation-warnings",
116     cl::desc("The maximum number of warnings to emit when correlating "
117              "profile from debug info (0 = no limit)"),
118     cl::sub(MergeSubcommand), cl::sub(ShowSubcommand), cl::init(5));
119 cl::opt<std::string> ProfiledBinary(
120     "profiled-binary", cl::init(""),
121     cl::desc("Path to binary from which the profile was collected."),
122     cl::sub(ShowSubcommand), cl::sub(MergeSubcommand));
123 cl::opt<std::string> DebugInfoFilename(
124     "debug-info", cl::init(""),
125     cl::desc(
126         "For show, read and extract profile metadata from debug info and show "
127         "the functions it found. For merge, use the provided debug info to "
128         "correlate the raw profile."),
129     cl::sub(ShowSubcommand), cl::sub(MergeSubcommand));
130 cl::opt<std::string>
131     BinaryFilename("binary-file", cl::init(""),
132                    cl::desc("For merge, use the provided unstripped bianry to "
133                             "correlate the raw profile."),
134                    cl::sub(MergeSubcommand));
135 cl::list<std::string> DebugFileDirectory(
136     "debug-file-directory",
137     cl::desc("Directories to search for object files by build ID"));
138 cl::opt<bool> DebugInfod("debuginfod", cl::init(false), cl::Hidden,
139                          cl::sub(MergeSubcommand),
140                          cl::desc("Enable debuginfod"));
141 cl::opt<ProfCorrelatorKind> BIDFetcherProfileCorrelate(
142     "correlate",
143     cl::desc("Use debug-info or binary correlation to correlate profiles with "
144              "build id fetcher"),
145     cl::init(InstrProfCorrelator::NONE),
146     cl::values(clEnumValN(InstrProfCorrelator::NONE, "",
147                           "No profile correlation"),
148                clEnumValN(InstrProfCorrelator::DEBUG_INFO, "debug-info",
149                           "Use debug info to correlate"),
150                clEnumValN(InstrProfCorrelator::BINARY, "binary",
151                           "Use binary to correlate")));
152 cl::opt<std::string> FuncNameFilter(
153     "function",
154     cl::desc("Only functions matching the filter are shown in the output. For "
155              "overlapping CSSPGO, this takes a function name with calling "
156              "context."),
157     cl::sub(ShowSubcommand), cl::sub(OverlapSubcommand),
158     cl::sub(MergeSubcommand));
159 
160 // TODO: Consider creating a template class (e.g., MergeOption, ShowOption) to
161 // factor out the common cl::sub in cl::opt constructor for subcommand-specific
162 // options.
163 
164 // Options specific to merge subcommand.
165 cl::list<std::string> InputFilenames(cl::Positional, cl::sub(MergeSubcommand),
166                                      cl::desc("<filename...>"));
167 cl::list<std::string> WeightedInputFilenames("weighted-input",
168                                              cl::sub(MergeSubcommand),
169                                              cl::desc("<weight>,<filename>"));
170 cl::opt<ProfileFormat> OutputFormat(
171     cl::desc("Format of output profile"), cl::sub(MergeSubcommand),
172     cl::init(PF_Ext_Binary),
173     cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding"),
174                clEnumValN(PF_Ext_Binary, "extbinary",
175                           "Extensible binary encoding "
176                           "(default)"),
177                clEnumValN(PF_Text, "text", "Text encoding"),
178                clEnumValN(PF_GCC, "gcc",
179                           "GCC encoding (only meaningful for -sample)")));
180 cl::opt<std::string>
181     InputFilenamesFile("input-files", cl::init(""), cl::sub(MergeSubcommand),
182                        cl::desc("Path to file containing newline-separated "
183                                 "[<weight>,]<filename> entries"));
184 cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
185                               cl::aliasopt(InputFilenamesFile));
186 cl::opt<bool> DumpInputFileList(
187     "dump-input-file-list", cl::init(false), cl::Hidden,
188     cl::sub(MergeSubcommand),
189     cl::desc("Dump the list of input files and their weights, then exit"));
190 cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
191                                    cl::sub(MergeSubcommand),
192                                    cl::desc("Symbol remapping file"));
193 cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
194                          cl::aliasopt(RemappingFile));
195 cl::opt<bool>
196     UseMD5("use-md5", cl::init(false), cl::Hidden,
197            cl::desc("Choose to use MD5 to represent string in name table (only "
198                     "meaningful for -extbinary)"),
199            cl::sub(MergeSubcommand));
200 cl::opt<bool> CompressAllSections(
201     "compress-all-sections", cl::init(false), cl::Hidden,
202     cl::sub(MergeSubcommand),
203     cl::desc("Compress all sections when writing the profile (only "
204              "meaningful for -extbinary)"));
205 cl::opt<bool> SampleMergeColdContext(
206     "sample-merge-cold-context", cl::init(false), cl::Hidden,
207     cl::sub(MergeSubcommand),
208     cl::desc(
209         "Merge context sample profiles whose count is below cold threshold"));
210 cl::opt<bool> SampleTrimColdContext(
211     "sample-trim-cold-context", cl::init(false), cl::Hidden,
212     cl::sub(MergeSubcommand),
213     cl::desc(
214         "Trim context sample profiles whose count is below cold threshold"));
215 cl::opt<uint32_t> SampleColdContextFrameDepth(
216     "sample-frame-depth-for-cold-context", cl::init(1),
217     cl::sub(MergeSubcommand),
218     cl::desc("Keep the last K frames while merging cold profile. 1 means the "
219              "context-less base profile"));
220 cl::opt<size_t> OutputSizeLimit(
221     "output-size-limit", cl::init(0), cl::Hidden, cl::sub(MergeSubcommand),
222     cl::desc("Trim cold functions until profile size is below specified "
223              "limit in bytes. This uses a heursitic and functions may be "
224              "excessively trimmed"));
225 cl::opt<bool> GenPartialProfile(
226     "gen-partial-profile", cl::init(false), cl::Hidden,
227     cl::sub(MergeSubcommand),
228     cl::desc("Generate a partial profile (only meaningful for -extbinary)"));
229 cl::opt<bool> SplitLayout(
230     "split-layout", cl::init(false), cl::Hidden,
231     cl::sub(MergeSubcommand),
232     cl::desc("Split the profile to two sections with one containing sample "
233              "profiles with inlined functions and the other without (only "
234              "meaningful for -extbinary)"));
235 cl::opt<std::string> SupplInstrWithSample(
236     "supplement-instr-with-sample", cl::init(""), cl::Hidden,
237     cl::sub(MergeSubcommand),
238     cl::desc("Supplement an instr profile with sample profile, to correct "
239              "the profile unrepresentativeness issue. The sample "
240              "profile is the input of the flag. Output will be in instr "
241              "format (The flag only works with -instr)"));
242 cl::opt<float> ZeroCounterThreshold(
243     "zero-counter-threshold", cl::init(0.7), cl::Hidden,
244     cl::sub(MergeSubcommand),
245     cl::desc("For the function which is cold in instr profile but hot in "
246              "sample profile, if the ratio of the number of zero counters "
247              "divided by the total number of counters is above the "
248              "threshold, the profile of the function will be regarded as "
249              "being harmful for performance and will be dropped."));
250 cl::opt<unsigned> SupplMinSizeThreshold(
251     "suppl-min-size-threshold", cl::init(10), cl::Hidden,
252     cl::sub(MergeSubcommand),
253     cl::desc("If the size of a function is smaller than the threshold, "
254              "assume it can be inlined by PGO early inliner and it won't "
255              "be adjusted based on sample profile."));
256 cl::opt<unsigned> InstrProfColdThreshold(
257     "instr-prof-cold-threshold", cl::init(0), cl::Hidden,
258     cl::sub(MergeSubcommand),
259     cl::desc("User specified cold threshold for instr profile which will "
260              "override the cold threshold got from profile summary. "));
261 // WARNING: This reservoir size value is propagated to any input indexed
262 // profiles for simplicity. Changing this value between invocations could
263 // result in sample bias.
264 cl::opt<uint64_t> TemporalProfTraceReservoirSize(
265     "temporal-profile-trace-reservoir-size", cl::init(100),
266     cl::sub(MergeSubcommand),
267     cl::desc("The maximum number of stored temporal profile traces (default: "
268              "100)"));
269 cl::opt<uint64_t> TemporalProfMaxTraceLength(
270     "temporal-profile-max-trace-length", cl::init(10000),
271     cl::sub(MergeSubcommand),
272     cl::desc("The maximum length of a single temporal profile trace "
273              "(default: 10000)"));
274 cl::opt<std::string> FuncNameNegativeFilter(
275     "no-function", cl::init(""),
276     cl::sub(MergeSubcommand),
277     cl::desc("Exclude functions matching the filter from the output."));
278 
279 cl::opt<FailureMode>
280     FailMode("failure-mode", cl::init(failIfAnyAreInvalid),
281              cl::desc("Failure mode:"), cl::sub(MergeSubcommand),
282              cl::values(clEnumValN(warnOnly, "warn",
283                                    "Do not fail and just print warnings."),
284                         clEnumValN(failIfAnyAreInvalid, "any",
285                                    "Fail if any profile is invalid."),
286                         clEnumValN(failIfAllAreInvalid, "all",
287                                    "Fail only if all profiles are invalid.")));
288 
289 cl::opt<bool> OutputSparse(
290     "sparse", cl::init(false), cl::sub(MergeSubcommand),
291     cl::desc("Generate a sparse profile (only meaningful for -instr)"));
292 cl::opt<unsigned> NumThreads(
293     "num-threads", cl::init(0), cl::sub(MergeSubcommand),
294     cl::desc("Number of merge threads to use (default: autodetect)"));
295 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
296                       cl::aliasopt(NumThreads));
297 
298 cl::opt<std::string> ProfileSymbolListFile(
299     "prof-sym-list", cl::init(""), cl::sub(MergeSubcommand),
300     cl::desc("Path to file containing the list of function symbols "
301              "used to populate profile symbol list"));
302 
303 cl::opt<SampleProfileLayout> ProfileLayout(
304     "convert-sample-profile-layout",
305     cl::desc("Convert the generated profile to a profile with a new layout"),
306     cl::sub(MergeSubcommand), cl::init(SPL_None),
307     cl::values(
308         clEnumValN(SPL_Nest, "nest",
309                    "Nested profile, the input should be CS flat profile"),
310         clEnumValN(SPL_Flat, "flat",
311                    "Profile with nested inlinee flatten out")));
312 
313 cl::opt<bool> DropProfileSymbolList(
314     "drop-profile-symbol-list", cl::init(false), cl::Hidden,
315     cl::sub(MergeSubcommand),
316     cl::desc("Drop the profile symbol list when merging AutoFDO profiles "
317              "(only meaningful for -sample)"));
318 
319 cl::opt<bool> KeepVTableSymbols(
320     "keep-vtable-symbols", cl::init(false), cl::Hidden,
321     cl::sub(MergeSubcommand),
322     cl::desc("If true, keep the vtable symbols in indexed profiles"));
323 
324 // Temporary support for writing the previous version of the format, to enable
325 // some forward compatibility.
326 // TODO: Consider enabling this with future version changes as well, to ease
327 // deployment of newer versions of llvm-profdata.
328 cl::opt<bool> DoWritePrevVersion(
329     "write-prev-version", cl::init(false), cl::Hidden,
330     cl::desc("Write the previous version of indexed format, to enable "
331              "some forward compatibility."));
332 
333 cl::opt<memprof::IndexedVersion> MemProfVersionRequested(
334     "memprof-version", cl::Hidden, cl::sub(MergeSubcommand),
335     cl::desc("Specify the version of the memprof format to use"),
336     cl::init(memprof::Version3),
337     cl::values(clEnumValN(memprof::Version2, "2", "version 2"),
338                clEnumValN(memprof::Version3, "3", "version 3")));
339 
340 cl::opt<bool> MemProfFullSchema(
341     "memprof-full-schema", cl::Hidden, cl::sub(MergeSubcommand),
342     cl::desc("Use the full schema for serialization"), cl::init(false));
343 
344 static cl::opt<bool>
345     MemprofGenerateRandomHotness("memprof-random-hotness", cl::init(false),
346                                  cl::Hidden, cl::sub(MergeSubcommand),
347                                  cl::desc("Generate random hotness values"));
348 static cl::opt<unsigned> MemprofGenerateRandomHotnessSeed(
349     "memprof-random-hotness-seed", cl::init(0), cl::Hidden,
350     cl::sub(MergeSubcommand),
351     cl::desc("Random hotness seed to use (0 to generate new seed)"));
352 
353 // Options specific to overlap subcommand.
354 cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
355                                   cl::desc("<base profile file>"),
356                                   cl::sub(OverlapSubcommand));
357 cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
358                                   cl::desc("<test profile file>"),
359                                   cl::sub(OverlapSubcommand));
360 
361 cl::opt<unsigned long long> SimilarityCutoff(
362     "similarity-cutoff", cl::init(0),
363     cl::desc("For sample profiles, list function names (with calling context "
364              "for csspgo) for overlapped functions "
365              "with similarities below the cutoff (percentage times 10000)."),
366     cl::sub(OverlapSubcommand));
367 
368 cl::opt<bool> IsCS(
369     "cs", cl::init(false),
370     cl::desc("For context sensitive PGO counts. Does not work with CSSPGO."),
371     cl::sub(OverlapSubcommand));
372 
373 cl::opt<unsigned long long> OverlapValueCutoff(
374     "value-cutoff", cl::init(-1),
375     cl::desc(
376         "Function level overlap information for every function (with calling "
377         "context for csspgo) in test "
378         "profile with max count value greater than the parameter value"),
379     cl::sub(OverlapSubcommand));
380 
381 // Options specific to show subcommand.
382 cl::opt<bool> ShowCounts("counts", cl::init(false),
383                          cl::desc("Show counter values for shown functions"),
384                          cl::sub(ShowSubcommand));
385 cl::opt<ShowFormat>
386     SFormat("show-format", cl::init(ShowFormat::Text),
387             cl::desc("Emit output in the selected format if supported"),
388             cl::sub(ShowSubcommand),
389             cl::values(clEnumValN(ShowFormat::Text, "text",
390                                   "emit normal text output (default)"),
391                        clEnumValN(ShowFormat::Json, "json", "emit JSON"),
392                        clEnumValN(ShowFormat::Yaml, "yaml", "emit YAML")));
393 // TODO: Consider replacing this with `--show-format=text-encoding`.
394 cl::opt<bool>
395     TextFormat("text", cl::init(false),
396                cl::desc("Show instr profile data in text dump format"),
397                cl::sub(ShowSubcommand));
398 cl::opt<bool>
399     JsonFormat("json",
400                cl::desc("Show sample profile data in the JSON format "
401                         "(deprecated, please use --show-format=json)"),
402                cl::sub(ShowSubcommand));
403 cl::opt<bool> ShowIndirectCallTargets(
404     "ic-targets", cl::init(false),
405     cl::desc("Show indirect call site target values for shown functions"),
406     cl::sub(ShowSubcommand));
407 cl::opt<bool> ShowVTables("show-vtables", cl::init(false),
408                           cl::desc("Show vtable names for shown functions"),
409                           cl::sub(ShowSubcommand));
410 cl::opt<bool> ShowMemOPSizes(
411     "memop-sizes", cl::init(false),
412     cl::desc("Show the profiled sizes of the memory intrinsic calls "
413              "for shown functions"),
414     cl::sub(ShowSubcommand));
415 cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
416                                   cl::desc("Show detailed profile summary"),
417                                   cl::sub(ShowSubcommand));
418 cl::list<uint32_t> DetailedSummaryCutoffs(
419     cl::CommaSeparated, "detailed-summary-cutoffs",
420     cl::desc(
421         "Cutoff percentages (times 10000) for generating detailed summary"),
422     cl::value_desc("800000,901000,999999"), cl::sub(ShowSubcommand));
423 cl::opt<bool>
424     ShowHotFuncList("hot-func-list", cl::init(false),
425                     cl::desc("Show profile summary of a list of hot functions"),
426                     cl::sub(ShowSubcommand));
427 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
428                                cl::desc("Details for each and every function"),
429                                cl::sub(ShowSubcommand));
430 cl::opt<bool> ShowCS("showcs", cl::init(false),
431                      cl::desc("Show context sensitive counts"),
432                      cl::sub(ShowSubcommand));
433 cl::opt<ProfileKinds> ShowProfileKind(
434     cl::desc("Profile kind supported by show:"), cl::sub(ShowSubcommand),
435     cl::init(instr),
436     cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
437                clEnumVal(sample, "Sample profile"),
438                clEnumVal(memory, "MemProf memory access profile")));
439 cl::opt<uint32_t> TopNFunctions(
440     "topn", cl::init(0),
441     cl::desc("Show the list of functions with the largest internal counts"),
442     cl::sub(ShowSubcommand));
443 cl::opt<uint32_t> ShowValueCutoff(
444     "value-cutoff", cl::init(0),
445     cl::desc("Set the count value cutoff. Functions with the maximum count "
446              "less than this value will not be printed out. (Default is 0)"),
447     cl::sub(ShowSubcommand));
448 cl::opt<bool> OnlyListBelow(
449     "list-below-cutoff", cl::init(false),
450     cl::desc("Only output names of functions whose max count values are "
451              "below the cutoff value"),
452     cl::sub(ShowSubcommand));
453 cl::opt<bool> ShowProfileSymbolList(
454     "show-prof-sym-list", cl::init(false),
455     cl::desc("Show profile symbol list if it exists in the profile. "),
456     cl::sub(ShowSubcommand));
457 cl::opt<bool> ShowSectionInfoOnly(
458     "show-sec-info-only", cl::init(false),
459     cl::desc("Show the information of each section in the sample profile. "
460              "The flag is only usable when the sample profile is in "
461              "extbinary format"),
462     cl::sub(ShowSubcommand));
463 cl::opt<bool> ShowBinaryIds("binary-ids", cl::init(false),
464                             cl::desc("Show binary ids in the profile. "),
465                             cl::sub(ShowSubcommand));
466 cl::opt<bool> ShowTemporalProfTraces(
467     "temporal-profile-traces",
468     cl::desc("Show temporal profile traces in the profile."),
469     cl::sub(ShowSubcommand));
470 
471 cl::opt<bool>
472     ShowCovered("covered", cl::init(false),
473                 cl::desc("Show only the functions that have been executed."),
474                 cl::sub(ShowSubcommand));
475 
476 cl::opt<bool> ShowProfileVersion("profile-version", cl::init(false),
477                                  cl::desc("Show profile version. "),
478                                  cl::sub(ShowSubcommand));
479 
480 // Options specific to order subcommand.
481 cl::opt<unsigned>
482     NumTestTraces("num-test-traces", cl::init(0),
483                   cl::desc("Keep aside the last <num-test-traces> traces in "
484                            "the profile when computing the function order and "
485                            "instead use them to evaluate that order"),
486                   cl::sub(OrderSubcommand));
487 
488 // We use this string to indicate that there are
489 // multiple static functions map to the same name.
490 const std::string DuplicateNameStr = "----";
491 
492 static void warn(Twine Message, StringRef Whence = "", StringRef Hint = "") {
493   WithColor::warning();
494   if (!Whence.empty())
495     errs() << Whence << ": ";
496   errs() << Message << "\n";
497   if (!Hint.empty())
498     WithColor::note() << Hint << "\n";
499 }
500 
501 static void warn(Error E, StringRef Whence = "") {
502   if (E.isA<InstrProfError>()) {
503     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
504       warn(IPE.message(), Whence);
505     });
506   }
507 }
508 
509 static void exitWithError(Twine Message, StringRef Whence = "",
510                           StringRef Hint = "") {
511   WithColor::error();
512   if (!Whence.empty())
513     errs() << Whence << ": ";
514   errs() << Message << "\n";
515   if (!Hint.empty())
516     WithColor::note() << Hint << "\n";
517   ::exit(1);
518 }
519 
520 static void exitWithError(Error E, StringRef Whence = "") {
521   if (E.isA<InstrProfError>()) {
522     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
523       instrprof_error instrError = IPE.get();
524       StringRef Hint = "";
525       if (instrError == instrprof_error::unrecognized_format) {
526         // Hint in case user missed specifying the profile type.
527         Hint = "Perhaps you forgot to use the --sample or --memory option?";
528       }
529       exitWithError(IPE.message(), Whence, Hint);
530     });
531     return;
532   }
533 
534   exitWithError(toString(std::move(E)), Whence);
535 }
536 
537 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
538   exitWithError(EC.message(), Whence);
539 }
540 
541 static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
542                                  StringRef Whence = "") {
543   if (FailMode == failIfAnyAreInvalid)
544     exitWithErrorCode(EC, Whence);
545   else
546     warn(EC.message(), Whence);
547 }
548 
549 static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
550                                    StringRef WhenceFunction = "",
551                                    bool ShowHint = true) {
552   if (!WhenceFile.empty())
553     errs() << WhenceFile << ": ";
554   if (!WhenceFunction.empty())
555     errs() << WhenceFunction << ": ";
556 
557   auto IPE = instrprof_error::success;
558   E = handleErrors(std::move(E),
559                    [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
560                      IPE = E->get();
561                      return Error(std::move(E));
562                    });
563   errs() << toString(std::move(E)) << "\n";
564 
565   if (ShowHint) {
566     StringRef Hint = "";
567     if (IPE != instrprof_error::success) {
568       switch (IPE) {
569       case instrprof_error::hash_mismatch:
570       case instrprof_error::count_mismatch:
571       case instrprof_error::value_site_count_mismatch:
572         Hint = "Make sure that all profile data to be merged is generated "
573                "from the same binary.";
574         break;
575       default:
576         break;
577       }
578     }
579 
580     if (!Hint.empty())
581       errs() << Hint << "\n";
582   }
583 }
584 
585 namespace {
586 /// A remapper from original symbol names to new symbol names based on a file
587 /// containing a list of mappings from old name to new name.
588 class SymbolRemapper {
589   std::unique_ptr<MemoryBuffer> File;
590   DenseMap<StringRef, StringRef> RemappingTable;
591 
592 public:
593   /// Build a SymbolRemapper from a file containing a list of old/new symbols.
594   static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
595     auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
596     if (!BufOrError)
597       exitWithErrorCode(BufOrError.getError(), InputFile);
598 
599     auto Remapper = std::make_unique<SymbolRemapper>();
600     Remapper->File = std::move(BufOrError.get());
601 
602     for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
603          !LineIt.is_at_eof(); ++LineIt) {
604       std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
605       if (Parts.first.empty() || Parts.second.empty() ||
606           Parts.second.count(' ')) {
607         exitWithError("unexpected line in remapping file",
608                       (InputFile + ":" + Twine(LineIt.line_number())).str(),
609                       "expected 'old_symbol new_symbol'");
610       }
611       Remapper->RemappingTable.insert(Parts);
612     }
613     return Remapper;
614   }
615 
616   /// Attempt to map the given old symbol into a new symbol.
617   ///
618   /// \return The new symbol, or \p Name if no such symbol was found.
619   StringRef operator()(StringRef Name) {
620     StringRef New = RemappingTable.lookup(Name);
621     return New.empty() ? Name : New;
622   }
623 
624   FunctionId operator()(FunctionId Name) {
625     // MD5 name cannot be remapped.
626     if (!Name.isStringRef())
627       return Name;
628     StringRef New = RemappingTable.lookup(Name.stringRef());
629     return New.empty() ? Name : FunctionId(New);
630   }
631 };
632 }
633 
634 struct WeightedFile {
635   std::string Filename;
636   uint64_t Weight;
637 };
638 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
639 
640 /// Keep track of merged data and reported errors.
641 struct WriterContext {
642   std::mutex Lock;
643   InstrProfWriter Writer;
644   std::vector<std::pair<Error, std::string>> Errors;
645   std::mutex &ErrLock;
646   SmallSet<instrprof_error, 4> &WriterErrorCodes;
647 
648   WriterContext(bool IsSparse, std::mutex &ErrLock,
649                 SmallSet<instrprof_error, 4> &WriterErrorCodes,
650                 uint64_t ReservoirSize = 0, uint64_t MaxTraceLength = 0)
651       : Writer(IsSparse, ReservoirSize, MaxTraceLength, DoWritePrevVersion,
652                MemProfVersionRequested, MemProfFullSchema,
653                MemprofGenerateRandomHotness, MemprofGenerateRandomHotnessSeed),
654         ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {}
655 };
656 
657 /// Computer the overlap b/w profile BaseFilename and TestFileName,
658 /// and store the program level result to Overlap.
659 static void overlapInput(const std::string &BaseFilename,
660                          const std::string &TestFilename, WriterContext *WC,
661                          OverlapStats &Overlap,
662                          const OverlapFuncFilters &FuncFilter,
663                          raw_fd_ostream &OS, bool IsCS) {
664   auto FS = vfs::getRealFileSystem();
665   auto ReaderOrErr = InstrProfReader::create(TestFilename, *FS);
666   if (Error E = ReaderOrErr.takeError()) {
667     // Skip the empty profiles by returning sliently.
668     auto [ErrorCode, Msg] = InstrProfError::take(std::move(E));
669     if (ErrorCode != instrprof_error::empty_raw_profile)
670       WC->Errors.emplace_back(make_error<InstrProfError>(ErrorCode, Msg),
671                               TestFilename);
672     return;
673   }
674 
675   auto Reader = std::move(ReaderOrErr.get());
676   for (auto &I : *Reader) {
677     OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
678     FuncOverlap.setFuncInfo(I.Name, I.Hash);
679 
680     WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
681     FuncOverlap.dump(OS);
682   }
683 }
684 
685 /// Load an input into a writer context.
686 static void
687 loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
688           const InstrProfCorrelator *Correlator, const StringRef ProfiledBinary,
689           WriterContext *WC, const object::BuildIDFetcher *BIDFetcher = nullptr,
690           const ProfCorrelatorKind *BIDFetcherCorrelatorKind = nullptr) {
691   std::unique_lock<std::mutex> CtxGuard{WC->Lock};
692 
693   // Copy the filename, because llvm::ThreadPool copied the input "const
694   // WeightedFile &" by value, making a reference to the filename within it
695   // invalid outside of this packaged task.
696   std::string Filename = Input.Filename;
697 
698   using ::llvm::memprof::RawMemProfReader;
699   if (RawMemProfReader::hasFormat(Input.Filename)) {
700     auto ReaderOrErr = RawMemProfReader::create(Input.Filename, ProfiledBinary);
701     if (!ReaderOrErr) {
702       exitWithError(ReaderOrErr.takeError(), Input.Filename);
703     }
704     std::unique_ptr<RawMemProfReader> Reader = std::move(ReaderOrErr.get());
705     // Check if the profile types can be merged, e.g. clang frontend profiles
706     // should not be merged with memprof profiles.
707     if (Error E = WC->Writer.mergeProfileKind(Reader->getProfileKind())) {
708       consumeError(std::move(E));
709       WC->Errors.emplace_back(
710           make_error<StringError>(
711               "Cannot merge MemProf profile with Clang generated profile.",
712               std::error_code()),
713           Filename);
714       return;
715     }
716 
717     auto MemProfError = [&](Error E) {
718       auto [ErrorCode, Msg] = InstrProfError::take(std::move(E));
719       WC->Errors.emplace_back(make_error<InstrProfError>(ErrorCode, Msg),
720                               Filename);
721     };
722 
723     WC->Writer.addMemProfData(Reader->takeMemProfData(), MemProfError);
724     return;
725   }
726 
727   using ::llvm::memprof::YAMLMemProfReader;
728   if (YAMLMemProfReader::hasFormat(Input.Filename)) {
729     auto ReaderOrErr = YAMLMemProfReader::create(Input.Filename);
730     if (!ReaderOrErr)
731       exitWithError(ReaderOrErr.takeError(), Input.Filename);
732     std::unique_ptr<YAMLMemProfReader> Reader = std::move(ReaderOrErr.get());
733     // Check if the profile types can be merged, e.g. clang frontend profiles
734     // should not be merged with memprof profiles.
735     if (Error E = WC->Writer.mergeProfileKind(Reader->getProfileKind())) {
736       consumeError(std::move(E));
737       WC->Errors.emplace_back(
738           make_error<StringError>(
739               "Cannot merge MemProf profile with incompatible profile.",
740               std::error_code()),
741           Filename);
742       return;
743     }
744 
745     auto MemProfError = [&](Error E) {
746       auto [ErrorCode, Msg] = InstrProfError::take(std::move(E));
747       WC->Errors.emplace_back(make_error<InstrProfError>(ErrorCode, Msg),
748                               Filename);
749     };
750 
751     auto MemProfData = Reader->takeMemProfData();
752 
753     // Check for the empty input in case the YAML file is invalid.
754     if (MemProfData.Records.empty()) {
755       WC->Errors.emplace_back(
756           make_error<StringError>("The profile is empty.", std::error_code()),
757           Filename);
758     }
759 
760     WC->Writer.addMemProfData(std::move(MemProfData), MemProfError);
761     return;
762   }
763 
764   auto FS = vfs::getRealFileSystem();
765   // TODO: This only saves the first non-fatal error from InstrProfReader, and
766   // then added to WriterContext::Errors. However, this is not extensible, if
767   // we have more non-fatal errors from InstrProfReader in the future. How
768   // should this interact with different -failure-mode?
769   std::optional<std::pair<Error, std::string>> ReaderWarning;
770   auto Warn = [&](Error E) {
771     if (ReaderWarning) {
772       consumeError(std::move(E));
773       return;
774     }
775     // Only show the first time an error occurs in this file.
776     auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
777     ReaderWarning = {make_error<InstrProfError>(ErrCode, Msg), Filename};
778   };
779 
780   const ProfCorrelatorKind CorrelatorKind = BIDFetcherCorrelatorKind
781                                                 ? *BIDFetcherCorrelatorKind
782                                                 : ProfCorrelatorKind::NONE;
783   auto ReaderOrErr = InstrProfReader::create(Input.Filename, *FS, Correlator,
784                                              BIDFetcher, CorrelatorKind, Warn);
785   if (Error E = ReaderOrErr.takeError()) {
786     // Skip the empty profiles by returning silently.
787     auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
788     if (ErrCode != instrprof_error::empty_raw_profile)
789       WC->Errors.emplace_back(make_error<InstrProfError>(ErrCode, Msg),
790                               Filename);
791     return;
792   }
793 
794   auto Reader = std::move(ReaderOrErr.get());
795   if (Error E = WC->Writer.mergeProfileKind(Reader->getProfileKind())) {
796     consumeError(std::move(E));
797     WC->Errors.emplace_back(
798         make_error<StringError>(
799             "Merge IR generated profile with Clang generated profile.",
800             std::error_code()),
801         Filename);
802     return;
803   }
804 
805   for (auto &I : *Reader) {
806     if (Remapper)
807       I.Name = (*Remapper)(I.Name);
808     const StringRef FuncName = I.Name;
809     bool Reported = false;
810     WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
811       if (Reported) {
812         consumeError(std::move(E));
813         return;
814       }
815       Reported = true;
816       // Only show hint the first time an error occurs.
817       auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
818       std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
819       bool firstTime = WC->WriterErrorCodes.insert(ErrCode).second;
820       handleMergeWriterError(make_error<InstrProfError>(ErrCode, Msg),
821                              Input.Filename, FuncName, firstTime);
822     });
823   }
824 
825   if (KeepVTableSymbols) {
826     const InstrProfSymtab &symtab = Reader->getSymtab();
827     const auto &VTableNames = symtab.getVTableNames();
828 
829     for (const auto &kv : VTableNames)
830       WC->Writer.addVTableName(kv.getKey());
831   }
832 
833   if (Reader->hasTemporalProfile()) {
834     auto &Traces = Reader->getTemporalProfTraces(Input.Weight);
835     if (!Traces.empty())
836       WC->Writer.addTemporalProfileTraces(
837           Traces, Reader->getTemporalProfTraceStreamSize());
838   }
839   if (Reader->hasError()) {
840     if (Error E = Reader->getError()) {
841       WC->Errors.emplace_back(std::move(E), Filename);
842       return;
843     }
844   }
845 
846   std::vector<llvm::object::BuildID> BinaryIds;
847   if (Error E = Reader->readBinaryIds(BinaryIds)) {
848     WC->Errors.emplace_back(std::move(E), Filename);
849     return;
850   }
851   WC->Writer.addBinaryIds(BinaryIds);
852 
853   if (ReaderWarning) {
854     WC->Errors.emplace_back(std::move(ReaderWarning->first),
855                             ReaderWarning->second);
856   }
857 }
858 
859 /// Merge the \p Src writer context into \p Dst.
860 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
861   for (auto &ErrorPair : Src->Errors)
862     Dst->Errors.push_back(std::move(ErrorPair));
863   Src->Errors.clear();
864 
865   if (Error E = Dst->Writer.mergeProfileKind(Src->Writer.getProfileKind()))
866     exitWithError(std::move(E));
867 
868   Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
869     auto [ErrorCode, Msg] = InstrProfError::take(std::move(E));
870     std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
871     bool firstTime = Dst->WriterErrorCodes.insert(ErrorCode).second;
872     if (firstTime)
873       warn(toString(make_error<InstrProfError>(ErrorCode, Msg)));
874   });
875 }
876 
877 static StringRef
878 getFuncName(const StringMap<InstrProfWriter::ProfilingData>::value_type &Val) {
879   return Val.first();
880 }
881 
882 static std::string
883 getFuncName(const SampleProfileMap::value_type &Val) {
884   return Val.second.getContext().toString();
885 }
886 
887 template <typename T>
888 static void filterFunctions(T &ProfileMap) {
889   bool hasFilter = !FuncNameFilter.empty();
890   bool hasNegativeFilter = !FuncNameNegativeFilter.empty();
891   if (!hasFilter && !hasNegativeFilter)
892     return;
893 
894   // If filter starts with '?' it is MSVC mangled name, not a regex.
895   llvm::Regex ProbablyMSVCMangledName("[?@$_0-9A-Za-z]+");
896   if (hasFilter && FuncNameFilter[0] == '?' &&
897       ProbablyMSVCMangledName.match(FuncNameFilter))
898     FuncNameFilter = llvm::Regex::escape(FuncNameFilter);
899   if (hasNegativeFilter && FuncNameNegativeFilter[0] == '?' &&
900       ProbablyMSVCMangledName.match(FuncNameNegativeFilter))
901     FuncNameNegativeFilter = llvm::Regex::escape(FuncNameNegativeFilter);
902 
903   size_t Count = ProfileMap.size();
904   llvm::Regex Pattern(FuncNameFilter);
905   llvm::Regex NegativePattern(FuncNameNegativeFilter);
906   std::string Error;
907   if (hasFilter && !Pattern.isValid(Error))
908     exitWithError(Error);
909   if (hasNegativeFilter && !NegativePattern.isValid(Error))
910     exitWithError(Error);
911 
912   // Handle MD5 profile, so it is still able to match using the original name.
913   std::string MD5Name = std::to_string(llvm::MD5Hash(FuncNameFilter));
914   std::string NegativeMD5Name =
915       std::to_string(llvm::MD5Hash(FuncNameNegativeFilter));
916 
917   for (auto I = ProfileMap.begin(); I != ProfileMap.end();) {
918     auto Tmp = I++;
919     const auto &FuncName = getFuncName(*Tmp);
920     // Negative filter has higher precedence than positive filter.
921     if ((hasNegativeFilter &&
922          (NegativePattern.match(FuncName) ||
923           (FunctionSamples::UseMD5 && NegativeMD5Name == FuncName))) ||
924         (hasFilter && !(Pattern.match(FuncName) ||
925                         (FunctionSamples::UseMD5 && MD5Name == FuncName))))
926       ProfileMap.erase(Tmp);
927   }
928 
929   llvm::dbgs() << Count - ProfileMap.size() << " of " << Count << " functions "
930                << "in the original profile are filtered.\n";
931 }
932 
933 static void writeInstrProfile(StringRef OutputFilename,
934                               ProfileFormat OutputFormat,
935                               InstrProfWriter &Writer) {
936   std::error_code EC;
937   raw_fd_ostream Output(OutputFilename.data(), EC,
938                         OutputFormat == PF_Text ? sys::fs::OF_TextWithCRLF
939                                                 : sys::fs::OF_None);
940   if (EC)
941     exitWithErrorCode(EC, OutputFilename);
942 
943   if (OutputFormat == PF_Text) {
944     if (Error E = Writer.writeText(Output))
945       warn(std::move(E));
946   } else {
947     if (Output.is_displayed())
948       exitWithError("cannot write a non-text format profile to the terminal");
949     if (Error E = Writer.write(Output))
950       warn(std::move(E));
951   }
952 }
953 
954 static void mergeInstrProfile(const WeightedFileVector &Inputs,
955                               SymbolRemapper *Remapper,
956                               int MaxDbgCorrelationWarnings,
957                               const StringRef ProfiledBinary) {
958   const uint64_t TraceReservoirSize = TemporalProfTraceReservoirSize.getValue();
959   const uint64_t MaxTraceLength = TemporalProfMaxTraceLength.getValue();
960   if (OutputFormat == PF_Compact_Binary)
961     exitWithError("Compact Binary is deprecated");
962   if (OutputFormat != PF_Binary && OutputFormat != PF_Ext_Binary &&
963       OutputFormat != PF_Text)
964     exitWithError("unknown format is specified");
965 
966   // TODO: Maybe we should support correlation with mixture of different
967   // correlation modes(w/wo debug-info/object correlation).
968   if (DebugInfoFilename.empty()) {
969     if (!BinaryFilename.empty() && (DebugInfod || !DebugFileDirectory.empty()))
970       exitWithError("Expected only one of -binary-file, -debuginfod or "
971                     "-debug-file-directory");
972   } else if (!BinaryFilename.empty() || DebugInfod ||
973              !DebugFileDirectory.empty()) {
974     exitWithError("Expected only one of -debug-info, -binary-file, -debuginfod "
975                   "or -debug-file-directory");
976   }
977   std::string CorrelateFilename;
978   ProfCorrelatorKind CorrelateKind = ProfCorrelatorKind::NONE;
979   if (!DebugInfoFilename.empty()) {
980     CorrelateFilename = DebugInfoFilename;
981     CorrelateKind = ProfCorrelatorKind::DEBUG_INFO;
982   } else if (!BinaryFilename.empty()) {
983     CorrelateFilename = BinaryFilename;
984     CorrelateKind = ProfCorrelatorKind::BINARY;
985   }
986 
987   std::unique_ptr<InstrProfCorrelator> Correlator;
988   if (CorrelateKind != InstrProfCorrelator::NONE) {
989     if (auto Err = InstrProfCorrelator::get(CorrelateFilename, CorrelateKind)
990                        .moveInto(Correlator))
991       exitWithError(std::move(Err), CorrelateFilename);
992     if (auto Err = Correlator->correlateProfileData(MaxDbgCorrelationWarnings))
993       exitWithError(std::move(Err), CorrelateFilename);
994   }
995 
996   ProfCorrelatorKind BIDFetcherCorrelateKind = ProfCorrelatorKind::NONE;
997   std::unique_ptr<object::BuildIDFetcher> BIDFetcher;
998   if (DebugInfod) {
999     llvm::HTTPClient::initialize();
1000     BIDFetcher = std::make_unique<DebuginfodFetcher>(DebugFileDirectory);
1001     if (!BIDFetcherProfileCorrelate)
1002       exitWithError("Expected --correlate when --debuginfod is provided");
1003     BIDFetcherCorrelateKind = BIDFetcherProfileCorrelate;
1004   } else if (!DebugFileDirectory.empty()) {
1005     BIDFetcher = std::make_unique<object::BuildIDFetcher>(DebugFileDirectory);
1006     if (!BIDFetcherProfileCorrelate)
1007       exitWithError("Expected --correlate when --debug-file-directory "
1008                     "is provided");
1009     BIDFetcherCorrelateKind = BIDFetcherProfileCorrelate;
1010   } else if (BIDFetcherProfileCorrelate) {
1011     exitWithError("Expected --debuginfod or --debug-file-directory when "
1012                   "--correlate is provided");
1013   }
1014 
1015   std::mutex ErrorLock;
1016   SmallSet<instrprof_error, 4> WriterErrorCodes;
1017 
1018   // If NumThreads is not specified, auto-detect a good default.
1019   if (NumThreads == 0)
1020     NumThreads = std::min(hardware_concurrency().compute_thread_count(),
1021                           unsigned((Inputs.size() + 1) / 2));
1022 
1023   // Initialize the writer contexts.
1024   SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
1025   for (unsigned I = 0; I < NumThreads; ++I)
1026     Contexts.emplace_back(std::make_unique<WriterContext>(
1027         OutputSparse, ErrorLock, WriterErrorCodes, TraceReservoirSize,
1028         MaxTraceLength));
1029 
1030   if (NumThreads == 1) {
1031     for (const auto &Input : Inputs)
1032       loadInput(Input, Remapper, Correlator.get(), ProfiledBinary,
1033                 Contexts[0].get(), BIDFetcher.get(), &BIDFetcherCorrelateKind);
1034   } else {
1035     DefaultThreadPool Pool(hardware_concurrency(NumThreads));
1036 
1037     // Load the inputs in parallel (N/NumThreads serial steps).
1038     unsigned Ctx = 0;
1039     for (const auto &Input : Inputs) {
1040       Pool.async(loadInput, Input, Remapper, Correlator.get(), ProfiledBinary,
1041                  Contexts[Ctx].get(), BIDFetcher.get(),
1042                  &BIDFetcherCorrelateKind);
1043       Ctx = (Ctx + 1) % NumThreads;
1044     }
1045     Pool.wait();
1046 
1047     // Merge the writer contexts together (~ lg(NumThreads) serial steps).
1048     unsigned Mid = Contexts.size() / 2;
1049     unsigned End = Contexts.size();
1050     assert(Mid > 0 && "Expected more than one context");
1051     do {
1052       for (unsigned I = 0; I < Mid; ++I)
1053         Pool.async(mergeWriterContexts, Contexts[I].get(),
1054                    Contexts[I + Mid].get());
1055       Pool.wait();
1056       if (End & 1) {
1057         Pool.async(mergeWriterContexts, Contexts[0].get(),
1058                    Contexts[End - 1].get());
1059         Pool.wait();
1060       }
1061       End = Mid;
1062       Mid /= 2;
1063     } while (Mid > 0);
1064   }
1065 
1066   // Handle deferred errors encountered during merging. If the number of errors
1067   // is equal to the number of inputs the merge failed.
1068   unsigned NumErrors = 0;
1069   for (std::unique_ptr<WriterContext> &WC : Contexts) {
1070     for (auto &ErrorPair : WC->Errors) {
1071       ++NumErrors;
1072       warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
1073     }
1074   }
1075   if ((NumErrors == Inputs.size() && FailMode == failIfAllAreInvalid) ||
1076       (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
1077     exitWithError("no profile can be merged");
1078 
1079   filterFunctions(Contexts[0]->Writer.getProfileData());
1080 
1081   writeInstrProfile(OutputFilename, OutputFormat, Contexts[0]->Writer);
1082 }
1083 
1084 /// The profile entry for a function in instrumentation profile.
1085 struct InstrProfileEntry {
1086   uint64_t MaxCount = 0;
1087   uint64_t NumEdgeCounters = 0;
1088   float ZeroCounterRatio = 0.0;
1089   InstrProfRecord *ProfRecord;
1090   InstrProfileEntry(InstrProfRecord *Record);
1091   InstrProfileEntry() = default;
1092 };
1093 
1094 InstrProfileEntry::InstrProfileEntry(InstrProfRecord *Record) {
1095   ProfRecord = Record;
1096   uint64_t CntNum = Record->Counts.size();
1097   uint64_t ZeroCntNum = 0;
1098   for (size_t I = 0; I < CntNum; ++I) {
1099     MaxCount = std::max(MaxCount, Record->Counts[I]);
1100     ZeroCntNum += !Record->Counts[I];
1101   }
1102   ZeroCounterRatio = (float)ZeroCntNum / CntNum;
1103   NumEdgeCounters = CntNum;
1104 }
1105 
1106 /// Either set all the counters in the instr profile entry \p IFE to
1107 /// -1 / -2 /in order to drop the profile or scale up the
1108 /// counters in \p IFP to be above hot / cold threshold. We use
1109 /// the ratio of zero counters in the profile of a function to
1110 /// decide the profile is helpful or harmful for performance,
1111 /// and to choose whether to scale up or drop it.
1112 static void updateInstrProfileEntry(InstrProfileEntry &IFE, bool SetToHot,
1113                                     uint64_t HotInstrThreshold,
1114                                     uint64_t ColdInstrThreshold,
1115                                     float ZeroCounterThreshold) {
1116   InstrProfRecord *ProfRecord = IFE.ProfRecord;
1117   if (!IFE.MaxCount || IFE.ZeroCounterRatio > ZeroCounterThreshold) {
1118     // If all or most of the counters of the function are zero, the
1119     // profile is unaccountable and should be dropped. Reset all the
1120     // counters to be -1 / -2 and PGO profile-use will drop the profile.
1121     // All counters being -1 also implies that the function is hot so
1122     // PGO profile-use will also set the entry count metadata to be
1123     // above hot threshold.
1124     // All counters being -2 implies that the function is warm so
1125     // PGO profile-use will also set the entry count metadata to be
1126     // above cold threshold.
1127     auto Kind =
1128         (SetToHot ? InstrProfRecord::PseudoHot : InstrProfRecord::PseudoWarm);
1129     ProfRecord->setPseudoCount(Kind);
1130     return;
1131   }
1132 
1133   // Scale up the MaxCount to be multiple times above hot / cold threshold.
1134   const unsigned MultiplyFactor = 3;
1135   uint64_t Threshold = (SetToHot ? HotInstrThreshold : ColdInstrThreshold);
1136   uint64_t Numerator = Threshold * MultiplyFactor;
1137 
1138   // Make sure Threshold for warm counters is below the HotInstrThreshold.
1139   if (!SetToHot && Threshold >= HotInstrThreshold) {
1140     Threshold = (HotInstrThreshold + ColdInstrThreshold) / 2;
1141   }
1142 
1143   uint64_t Denominator = IFE.MaxCount;
1144   if (Numerator <= Denominator)
1145     return;
1146   ProfRecord->scale(Numerator, Denominator, [&](instrprof_error E) {
1147     warn(toString(make_error<InstrProfError>(E)));
1148   });
1149 }
1150 
1151 const uint64_t ColdPercentileIdx = 15;
1152 const uint64_t HotPercentileIdx = 11;
1153 
1154 using sampleprof::FSDiscriminatorPass;
1155 
1156 // Internal options to set FSDiscriminatorPass. Used in merge and show
1157 // commands.
1158 static cl::opt<FSDiscriminatorPass> FSDiscriminatorPassOption(
1159     "fs-discriminator-pass", cl::init(PassLast), cl::Hidden,
1160     cl::desc("Zero out the discriminator bits for the FS discrimiantor "
1161              "pass beyond this value. The enum values are defined in "
1162              "Support/Discriminator.h"),
1163     cl::values(clEnumVal(Base, "Use base discriminators only"),
1164                clEnumVal(Pass1, "Use base and pass 1 discriminators"),
1165                clEnumVal(Pass2, "Use base and pass 1-2 discriminators"),
1166                clEnumVal(Pass3, "Use base and pass 1-3 discriminators"),
1167                clEnumVal(PassLast, "Use all discriminator bits (default)")));
1168 
1169 static unsigned getDiscriminatorMask() {
1170   return getN1Bits(getFSPassBitEnd(FSDiscriminatorPassOption.getValue()));
1171 }
1172 
1173 /// Adjust the instr profile in \p WC based on the sample profile in
1174 /// \p Reader.
1175 static void
1176 adjustInstrProfile(std::unique_ptr<WriterContext> &WC,
1177                    std::unique_ptr<sampleprof::SampleProfileReader> &Reader,
1178                    unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
1179                    unsigned InstrProfColdThreshold) {
1180   // Function to its entry in instr profile.
1181   StringMap<InstrProfileEntry> InstrProfileMap;
1182   StringMap<StringRef> StaticFuncMap;
1183   InstrProfSummaryBuilder IPBuilder(ProfileSummaryBuilder::DefaultCutoffs);
1184 
1185   auto checkSampleProfileHasFUnique = [&Reader]() {
1186     for (const auto &PD : Reader->getProfiles()) {
1187       auto &FContext = PD.second.getContext();
1188       if (FContext.toString().find(FunctionSamples::UniqSuffix) !=
1189           std::string::npos) {
1190         return true;
1191       }
1192     }
1193     return false;
1194   };
1195 
1196   bool SampleProfileHasFUnique = checkSampleProfileHasFUnique();
1197 
1198   auto buildStaticFuncMap = [&StaticFuncMap,
1199                              SampleProfileHasFUnique](const StringRef Name) {
1200     std::string FilePrefixes[] = {".cpp", "cc", ".c", ".hpp", ".h"};
1201     size_t PrefixPos = StringRef::npos;
1202     for (auto &FilePrefix : FilePrefixes) {
1203       std::string NamePrefix = FilePrefix + GlobalIdentifierDelimiter;
1204       PrefixPos = Name.find_insensitive(NamePrefix);
1205       if (PrefixPos == StringRef::npos)
1206         continue;
1207       PrefixPos += NamePrefix.size();
1208       break;
1209     }
1210 
1211     if (PrefixPos == StringRef::npos) {
1212       return;
1213     }
1214 
1215     StringRef NewName = Name.drop_front(PrefixPos);
1216     StringRef FName = Name.substr(0, PrefixPos - 1);
1217     if (NewName.size() == 0) {
1218       return;
1219     }
1220 
1221     // This name should have a static linkage.
1222     size_t PostfixPos = NewName.find(FunctionSamples::UniqSuffix);
1223     bool ProfileHasFUnique = (PostfixPos != StringRef::npos);
1224 
1225     // If sample profile and instrumented profile do not agree on symbol
1226     // uniqification.
1227     if (SampleProfileHasFUnique != ProfileHasFUnique) {
1228       // If instrumented profile uses -funique-internal-linkage-symbols,
1229       // we need to trim the name.
1230       if (ProfileHasFUnique) {
1231         NewName = NewName.substr(0, PostfixPos);
1232       } else {
1233         // If sample profile uses -funique-internal-linkage-symbols,
1234         // we build the map.
1235         std::string NStr =
1236             NewName.str() + getUniqueInternalLinkagePostfix(FName);
1237         NewName = StringRef(NStr);
1238         StaticFuncMap[NewName] = Name;
1239         return;
1240       }
1241     }
1242 
1243     auto [It, Inserted] = StaticFuncMap.try_emplace(NewName, Name);
1244     if (!Inserted)
1245       It->second = DuplicateNameStr;
1246   };
1247 
1248   // We need to flatten the SampleFDO profile as the InstrFDO
1249   // profile does not have inlined callsite profiles.
1250   // One caveat is the pre-inlined function -- their samples
1251   // should be collapsed into the caller function.
1252   // Here we do a DFS traversal to get the flatten profile
1253   // info: the sum of entrycount and the max of maxcount.
1254   // Here is the algorithm:
1255   //   recursive (FS, root_name) {
1256   //      name = FS->getName();
1257   //      get samples for FS;
1258   //      if (InstrProf.find(name) {
1259   //        root_name = name;
1260   //      } else {
1261   //        if (name is in static_func map) {
1262   //          root_name = static_name;
1263   //        }
1264   //      }
1265   //      update the Map entry for root_name;
1266   //      for (subfs: FS) {
1267   //        recursive(subfs, root_name);
1268   //      }
1269   //   }
1270   //
1271   // Here is an example.
1272   //
1273   // SampleProfile:
1274   // foo:12345:1000
1275   // 1: 1000
1276   // 2.1: 1000
1277   // 15: 5000
1278   // 4: bar:1000
1279   //  1: 1000
1280   //  2: goo:3000
1281   //   1: 3000
1282   // 8: bar:40000
1283   //  1: 10000
1284   //  2: goo:30000
1285   //   1: 30000
1286   //
1287   // InstrProfile has two entries:
1288   //  foo
1289   //  bar.cc;bar
1290   //
1291   // After BuildMaxSampleMap, we should have the following in FlattenSampleMap:
1292   // {"foo", {1000, 5000}}
1293   // {"bar.cc;bar", {11000, 30000}}
1294   //
1295   // foo's has an entry count of 1000, and max body count of 5000.
1296   // bar.cc;bar has an entry count of 11000 (sum two callsites of 1000 and
1297   // 10000), and max count of 30000 (from the callsite in line 8).
1298   //
1299   // Note that goo's count will remain in bar.cc;bar() as it does not have an
1300   // entry in InstrProfile.
1301   llvm::StringMap<std::pair<uint64_t, uint64_t>> FlattenSampleMap;
1302   auto BuildMaxSampleMap = [&FlattenSampleMap, &StaticFuncMap,
1303                             &InstrProfileMap](const FunctionSamples &FS,
1304                                               const StringRef &RootName) {
1305     auto BuildMaxSampleMapImpl = [&](const FunctionSamples &FS,
1306                                      const StringRef &RootName,
1307                                      auto &BuildImpl) -> void {
1308       std::string NameStr = FS.getFunction().str();
1309       const StringRef Name = NameStr;
1310       const StringRef *NewRootName = &RootName;
1311       uint64_t EntrySample = FS.getHeadSamplesEstimate();
1312       uint64_t MaxBodySample = FS.getMaxCountInside(/* SkipCallSite*/ true);
1313 
1314       auto It = InstrProfileMap.find(Name);
1315       if (It != InstrProfileMap.end()) {
1316         NewRootName = &Name;
1317       } else {
1318         auto NewName = StaticFuncMap.find(Name);
1319         if (NewName != StaticFuncMap.end()) {
1320           It = InstrProfileMap.find(NewName->second);
1321           if (NewName->second != DuplicateNameStr) {
1322             NewRootName = &NewName->second;
1323           }
1324         } else {
1325           // Here the EntrySample is of an inlined function, so we should not
1326           // update the EntrySample in the map.
1327           EntrySample = 0;
1328         }
1329       }
1330       EntrySample += FlattenSampleMap[*NewRootName].first;
1331       MaxBodySample =
1332           std::max(FlattenSampleMap[*NewRootName].second, MaxBodySample);
1333       FlattenSampleMap[*NewRootName] =
1334           std::make_pair(EntrySample, MaxBodySample);
1335 
1336       for (const auto &C : FS.getCallsiteSamples())
1337         for (const auto &F : C.second)
1338           BuildImpl(F.second, *NewRootName, BuildImpl);
1339     };
1340     BuildMaxSampleMapImpl(FS, RootName, BuildMaxSampleMapImpl);
1341   };
1342 
1343   for (auto &PD : WC->Writer.getProfileData()) {
1344     // Populate IPBuilder.
1345     for (const auto &PDV : PD.getValue()) {
1346       InstrProfRecord Record = PDV.second;
1347       IPBuilder.addRecord(Record);
1348     }
1349 
1350     // If a function has multiple entries in instr profile, skip it.
1351     if (PD.getValue().size() != 1)
1352       continue;
1353 
1354     // Initialize InstrProfileMap.
1355     InstrProfRecord *R = &PD.getValue().begin()->second;
1356     StringRef FullName = PD.getKey();
1357     InstrProfileMap[FullName] = InstrProfileEntry(R);
1358     buildStaticFuncMap(FullName);
1359   }
1360 
1361   for (auto &PD : Reader->getProfiles()) {
1362     sampleprof::FunctionSamples &FS = PD.second;
1363     std::string Name = FS.getFunction().str();
1364     BuildMaxSampleMap(FS, Name);
1365   }
1366 
1367   ProfileSummary InstrPS = *IPBuilder.getSummary();
1368   ProfileSummary SamplePS = Reader->getSummary();
1369 
1370   // Compute cold thresholds for instr profile and sample profile.
1371   uint64_t HotSampleThreshold =
1372       ProfileSummaryBuilder::getEntryForPercentile(
1373           SamplePS.getDetailedSummary(),
1374           ProfileSummaryBuilder::DefaultCutoffs[HotPercentileIdx])
1375           .MinCount;
1376   uint64_t ColdSampleThreshold =
1377       ProfileSummaryBuilder::getEntryForPercentile(
1378           SamplePS.getDetailedSummary(),
1379           ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
1380           .MinCount;
1381   uint64_t HotInstrThreshold =
1382       ProfileSummaryBuilder::getEntryForPercentile(
1383           InstrPS.getDetailedSummary(),
1384           ProfileSummaryBuilder::DefaultCutoffs[HotPercentileIdx])
1385           .MinCount;
1386   uint64_t ColdInstrThreshold =
1387       InstrProfColdThreshold
1388           ? InstrProfColdThreshold
1389           : ProfileSummaryBuilder::getEntryForPercentile(
1390                 InstrPS.getDetailedSummary(),
1391                 ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
1392                 .MinCount;
1393 
1394   // Find hot/warm functions in sample profile which is cold in instr profile
1395   // and adjust the profiles of those functions in the instr profile.
1396   for (const auto &E : FlattenSampleMap) {
1397     uint64_t SampleMaxCount = std::max(E.second.first, E.second.second);
1398     if (SampleMaxCount < ColdSampleThreshold)
1399       continue;
1400     StringRef Name = E.first();
1401     auto It = InstrProfileMap.find(Name);
1402     if (It == InstrProfileMap.end()) {
1403       auto NewName = StaticFuncMap.find(Name);
1404       if (NewName != StaticFuncMap.end()) {
1405         It = InstrProfileMap.find(NewName->second);
1406         if (NewName->second == DuplicateNameStr) {
1407           WithColor::warning()
1408               << "Static function " << Name
1409               << " has multiple promoted names, cannot adjust profile.\n";
1410         }
1411       }
1412     }
1413     if (It == InstrProfileMap.end() ||
1414         It->second.MaxCount > ColdInstrThreshold ||
1415         It->second.NumEdgeCounters < SupplMinSizeThreshold)
1416       continue;
1417     bool SetToHot = SampleMaxCount >= HotSampleThreshold;
1418     updateInstrProfileEntry(It->second, SetToHot, HotInstrThreshold,
1419                             ColdInstrThreshold, ZeroCounterThreshold);
1420   }
1421 }
1422 
1423 /// The main function to supplement instr profile with sample profile.
1424 /// \Inputs contains the instr profile. \p SampleFilename specifies the
1425 /// sample profile. \p OutputFilename specifies the output profile name.
1426 /// \p OutputFormat specifies the output profile format. \p OutputSparse
1427 /// specifies whether to generate sparse profile. \p SupplMinSizeThreshold
1428 /// specifies the minimal size for the functions whose profile will be
1429 /// adjusted. \p ZeroCounterThreshold is the threshold to check whether
1430 /// a function contains too many zero counters and whether its profile
1431 /// should be dropped. \p InstrProfColdThreshold is the user specified
1432 /// cold threshold which will override the cold threshold got from the
1433 /// instr profile summary.
1434 static void supplementInstrProfile(const WeightedFileVector &Inputs,
1435                                    StringRef SampleFilename, bool OutputSparse,
1436                                    unsigned SupplMinSizeThreshold,
1437                                    float ZeroCounterThreshold,
1438                                    unsigned InstrProfColdThreshold) {
1439   if (OutputFilename == "-")
1440     exitWithError("cannot write indexed profdata format to stdout");
1441   if (Inputs.size() != 1)
1442     exitWithError("expect one input to be an instr profile");
1443   if (Inputs[0].Weight != 1)
1444     exitWithError("expect instr profile doesn't have weight");
1445 
1446   StringRef InstrFilename = Inputs[0].Filename;
1447 
1448   // Read sample profile.
1449   LLVMContext Context;
1450   auto FS = vfs::getRealFileSystem();
1451   auto ReaderOrErr = sampleprof::SampleProfileReader::create(
1452       SampleFilename.str(), Context, *FS, FSDiscriminatorPassOption);
1453   if (std::error_code EC = ReaderOrErr.getError())
1454     exitWithErrorCode(EC, SampleFilename);
1455   auto Reader = std::move(ReaderOrErr.get());
1456   if (std::error_code EC = Reader->read())
1457     exitWithErrorCode(EC, SampleFilename);
1458 
1459   // Read instr profile.
1460   std::mutex ErrorLock;
1461   SmallSet<instrprof_error, 4> WriterErrorCodes;
1462   auto WC = std::make_unique<WriterContext>(OutputSparse, ErrorLock,
1463                                             WriterErrorCodes);
1464   loadInput(Inputs[0], nullptr, nullptr, /*ProfiledBinary=*/"", WC.get());
1465   if (WC->Errors.size() > 0)
1466     exitWithError(std::move(WC->Errors[0].first), InstrFilename);
1467 
1468   adjustInstrProfile(WC, Reader, SupplMinSizeThreshold, ZeroCounterThreshold,
1469                      InstrProfColdThreshold);
1470   writeInstrProfile(OutputFilename, OutputFormat, WC->Writer);
1471 }
1472 
1473 /// Make a copy of the given function samples with all symbol names remapped
1474 /// by the provided symbol remapper.
1475 static sampleprof::FunctionSamples
1476 remapSamples(const sampleprof::FunctionSamples &Samples,
1477              SymbolRemapper &Remapper, sampleprof_error &Error) {
1478   sampleprof::FunctionSamples Result;
1479   Result.setFunction(Remapper(Samples.getFunction()));
1480   Result.addTotalSamples(Samples.getTotalSamples());
1481   Result.addHeadSamples(Samples.getHeadSamples());
1482   for (const auto &BodySample : Samples.getBodySamples()) {
1483     uint32_t MaskedDiscriminator =
1484         BodySample.first.Discriminator & getDiscriminatorMask();
1485     Result.addBodySamples(BodySample.first.LineOffset, MaskedDiscriminator,
1486                           BodySample.second.getSamples());
1487     for (const auto &Target : BodySample.second.getCallTargets()) {
1488       Result.addCalledTargetSamples(BodySample.first.LineOffset,
1489                                     MaskedDiscriminator,
1490                                     Remapper(Target.first), Target.second);
1491     }
1492   }
1493   for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
1494     sampleprof::FunctionSamplesMap &Target =
1495         Result.functionSamplesAt(CallsiteSamples.first);
1496     for (const auto &Callsite : CallsiteSamples.second) {
1497       sampleprof::FunctionSamples Remapped =
1498           remapSamples(Callsite.second, Remapper, Error);
1499       mergeSampleProfErrors(Error,
1500                             Target[Remapped.getFunction()].merge(Remapped));
1501     }
1502   }
1503   return Result;
1504 }
1505 
1506 static sampleprof::SampleProfileFormat FormatMap[] = {
1507     sampleprof::SPF_None,
1508     sampleprof::SPF_Text,
1509     sampleprof::SPF_None,
1510     sampleprof::SPF_Ext_Binary,
1511     sampleprof::SPF_GCC,
1512     sampleprof::SPF_Binary};
1513 
1514 static std::unique_ptr<MemoryBuffer>
1515 getInputFileBuf(const StringRef &InputFile) {
1516   if (InputFile == "")
1517     return {};
1518 
1519   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
1520   if (!BufOrError)
1521     exitWithErrorCode(BufOrError.getError(), InputFile);
1522 
1523   return std::move(*BufOrError);
1524 }
1525 
1526 static void populateProfileSymbolList(MemoryBuffer *Buffer,
1527                                       sampleprof::ProfileSymbolList &PSL) {
1528   if (!Buffer)
1529     return;
1530 
1531   SmallVector<StringRef, 32> SymbolVec;
1532   StringRef Data = Buffer->getBuffer();
1533   Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
1534 
1535   for (StringRef SymbolStr : SymbolVec)
1536     PSL.add(SymbolStr.trim());
1537 }
1538 
1539 static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer,
1540                                   ProfileFormat OutputFormat,
1541                                   MemoryBuffer *Buffer,
1542                                   sampleprof::ProfileSymbolList &WriterList,
1543                                   bool CompressAllSections, bool UseMD5,
1544                                   bool GenPartialProfile) {
1545   if (SplitLayout) {
1546     if (OutputFormat == PF_Binary)
1547       warn("-split-layout is ignored. Specify -extbinary to enable it");
1548     else
1549       Writer.setUseCtxSplitLayout();
1550   }
1551 
1552   populateProfileSymbolList(Buffer, WriterList);
1553   if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
1554     warn("Profile Symbol list is not empty but the output format is not "
1555          "ExtBinary format. The list will be lost in the output. ");
1556 
1557   Writer.setProfileSymbolList(&WriterList);
1558 
1559   if (CompressAllSections) {
1560     if (OutputFormat != PF_Ext_Binary)
1561       warn("-compress-all-section is ignored. Specify -extbinary to enable it");
1562     else
1563       Writer.setToCompressAllSections();
1564   }
1565   if (UseMD5) {
1566     if (OutputFormat != PF_Ext_Binary)
1567       warn("-use-md5 is ignored. Specify -extbinary to enable it");
1568     else
1569       Writer.setUseMD5();
1570   }
1571   if (GenPartialProfile) {
1572     if (OutputFormat != PF_Ext_Binary)
1573       warn("-gen-partial-profile is ignored. Specify -extbinary to enable it");
1574     else
1575       Writer.setPartialProfile();
1576   }
1577 }
1578 
1579 static void mergeSampleProfile(const WeightedFileVector &Inputs,
1580                                SymbolRemapper *Remapper,
1581                                StringRef ProfileSymbolListFile,
1582                                size_t OutputSizeLimit) {
1583   using namespace sampleprof;
1584   SampleProfileMap ProfileMap;
1585   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
1586   LLVMContext Context;
1587   sampleprof::ProfileSymbolList WriterList;
1588   std::optional<bool> ProfileIsProbeBased;
1589   std::optional<bool> ProfileIsCS;
1590   for (const auto &Input : Inputs) {
1591     auto FS = vfs::getRealFileSystem();
1592     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context, *FS,
1593                                                    FSDiscriminatorPassOption);
1594     if (std::error_code EC = ReaderOrErr.getError()) {
1595       warnOrExitGivenError(FailMode, EC, Input.Filename);
1596       continue;
1597     }
1598 
1599     // We need to keep the readers around until after all the files are
1600     // read so that we do not lose the function names stored in each
1601     // reader's memory. The function names are needed to write out the
1602     // merged profile map.
1603     Readers.push_back(std::move(ReaderOrErr.get()));
1604     const auto Reader = Readers.back().get();
1605     if (std::error_code EC = Reader->read()) {
1606       warnOrExitGivenError(FailMode, EC, Input.Filename);
1607       Readers.pop_back();
1608       continue;
1609     }
1610 
1611     SampleProfileMap &Profiles = Reader->getProfiles();
1612     if (ProfileIsProbeBased &&
1613         ProfileIsProbeBased != FunctionSamples::ProfileIsProbeBased)
1614       exitWithError(
1615           "cannot merge probe-based profile with non-probe-based profile");
1616     ProfileIsProbeBased = FunctionSamples::ProfileIsProbeBased;
1617     if (ProfileIsCS && ProfileIsCS != FunctionSamples::ProfileIsCS)
1618       exitWithError("cannot merge CS profile with non-CS profile");
1619     ProfileIsCS = FunctionSamples::ProfileIsCS;
1620     for (SampleProfileMap::iterator I = Profiles.begin(), E = Profiles.end();
1621          I != E; ++I) {
1622       sampleprof_error Result = sampleprof_error::success;
1623       FunctionSamples Remapped =
1624           Remapper ? remapSamples(I->second, *Remapper, Result)
1625                    : FunctionSamples();
1626       FunctionSamples &Samples = Remapper ? Remapped : I->second;
1627       SampleContext FContext = Samples.getContext();
1628       mergeSampleProfErrors(Result,
1629                             ProfileMap[FContext].merge(Samples, Input.Weight));
1630       if (Result != sampleprof_error::success) {
1631         std::error_code EC = make_error_code(Result);
1632         handleMergeWriterError(errorCodeToError(EC), Input.Filename,
1633                                FContext.toString());
1634       }
1635     }
1636 
1637     if (!DropProfileSymbolList) {
1638       std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
1639           Reader->getProfileSymbolList();
1640       if (ReaderList)
1641         WriterList.merge(*ReaderList);
1642     }
1643   }
1644 
1645   if (ProfileIsCS && (SampleMergeColdContext || SampleTrimColdContext)) {
1646     // Use threshold calculated from profile summary unless specified.
1647     SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1648     auto Summary = Builder.computeSummaryForProfiles(ProfileMap);
1649     uint64_t SampleProfColdThreshold =
1650         ProfileSummaryBuilder::getColdCountThreshold(
1651             (Summary->getDetailedSummary()));
1652 
1653     // Trim and merge cold context profile using cold threshold above;
1654     SampleContextTrimmer(ProfileMap)
1655         .trimAndMergeColdContextProfiles(
1656             SampleProfColdThreshold, SampleTrimColdContext,
1657             SampleMergeColdContext, SampleColdContextFrameDepth, false);
1658   }
1659 
1660   if (ProfileLayout == llvm::sampleprof::SPL_Flat) {
1661     ProfileConverter::flattenProfile(ProfileMap, FunctionSamples::ProfileIsCS);
1662     ProfileIsCS = FunctionSamples::ProfileIsCS = false;
1663   } else if (ProfileIsCS && ProfileLayout == llvm::sampleprof::SPL_Nest) {
1664     ProfileConverter CSConverter(ProfileMap);
1665     CSConverter.convertCSProfiles();
1666     ProfileIsCS = FunctionSamples::ProfileIsCS = false;
1667   }
1668 
1669   filterFunctions(ProfileMap);
1670 
1671   auto WriterOrErr =
1672       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
1673   if (std::error_code EC = WriterOrErr.getError())
1674     exitWithErrorCode(EC, OutputFilename);
1675 
1676   auto Writer = std::move(WriterOrErr.get());
1677   // WriterList will have StringRef refering to string in Buffer.
1678   // Make sure Buffer lives as long as WriterList.
1679   auto Buffer = getInputFileBuf(ProfileSymbolListFile);
1680   handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList,
1681                         CompressAllSections, UseMD5, GenPartialProfile);
1682 
1683   // If OutputSizeLimit is 0 (default), it is the same as write().
1684   if (std::error_code EC =
1685           Writer->writeWithSizeLimit(ProfileMap, OutputSizeLimit))
1686     exitWithErrorCode(EC);
1687 }
1688 
1689 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
1690   StringRef WeightStr, FileName;
1691   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
1692 
1693   uint64_t Weight;
1694   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
1695     exitWithError("input weight must be a positive integer");
1696 
1697   return {std::string(FileName), Weight};
1698 }
1699 
1700 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
1701   StringRef Filename = WF.Filename;
1702   uint64_t Weight = WF.Weight;
1703 
1704   // If it's STDIN just pass it on.
1705   if (Filename == "-") {
1706     WNI.push_back({std::string(Filename), Weight});
1707     return;
1708   }
1709 
1710   llvm::sys::fs::file_status Status;
1711   llvm::sys::fs::status(Filename, Status);
1712   if (!llvm::sys::fs::exists(Status))
1713     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
1714                       Filename);
1715   // If it's a source file, collect it.
1716   if (llvm::sys::fs::is_regular_file(Status)) {
1717     WNI.push_back({std::string(Filename), Weight});
1718     return;
1719   }
1720 
1721   if (llvm::sys::fs::is_directory(Status)) {
1722     std::error_code EC;
1723     for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
1724          F != E && !EC; F.increment(EC)) {
1725       if (llvm::sys::fs::is_regular_file(F->path())) {
1726         addWeightedInput(WNI, {F->path(), Weight});
1727       }
1728     }
1729     if (EC)
1730       exitWithErrorCode(EC, Filename);
1731   }
1732 }
1733 
1734 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
1735                                     WeightedFileVector &WFV) {
1736   if (!Buffer)
1737     return;
1738 
1739   SmallVector<StringRef, 8> Entries;
1740   StringRef Data = Buffer->getBuffer();
1741   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
1742   for (const StringRef &FileWeightEntry : Entries) {
1743     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
1744     // Skip comments.
1745     if (SanitizedEntry.starts_with("#"))
1746       continue;
1747     // If there's no comma, it's an unweighted profile.
1748     else if (!SanitizedEntry.contains(','))
1749       addWeightedInput(WFV, {std::string(SanitizedEntry), 1});
1750     else
1751       addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
1752   }
1753 }
1754 
1755 static int merge_main(StringRef ProgName) {
1756   WeightedFileVector WeightedInputs;
1757   for (StringRef Filename : InputFilenames)
1758     addWeightedInput(WeightedInputs, {std::string(Filename), 1});
1759   for (StringRef WeightedFilename : WeightedInputFilenames)
1760     addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
1761 
1762   // Make sure that the file buffer stays alive for the duration of the
1763   // weighted input vector's lifetime.
1764   auto Buffer = getInputFileBuf(InputFilenamesFile);
1765   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
1766 
1767   if (WeightedInputs.empty())
1768     exitWithError("no input files specified. See " + ProgName + " merge -help");
1769 
1770   if (DumpInputFileList) {
1771     for (auto &WF : WeightedInputs)
1772       outs() << WF.Weight << "," << WF.Filename << "\n";
1773     return 0;
1774   }
1775 
1776   std::unique_ptr<SymbolRemapper> Remapper;
1777   if (!RemappingFile.empty())
1778     Remapper = SymbolRemapper::create(RemappingFile);
1779 
1780   if (!SupplInstrWithSample.empty()) {
1781     if (ProfileKind != instr)
1782       exitWithError(
1783           "-supplement-instr-with-sample can only work with -instr. ");
1784 
1785     supplementInstrProfile(WeightedInputs, SupplInstrWithSample, OutputSparse,
1786                            SupplMinSizeThreshold, ZeroCounterThreshold,
1787                            InstrProfColdThreshold);
1788     return 0;
1789   }
1790 
1791   if (ProfileKind == instr)
1792     mergeInstrProfile(WeightedInputs, Remapper.get(), MaxDbgCorrelationWarnings,
1793                       ProfiledBinary);
1794   else
1795     mergeSampleProfile(WeightedInputs, Remapper.get(), ProfileSymbolListFile,
1796                        OutputSizeLimit);
1797   return 0;
1798 }
1799 
1800 /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
1801 static void overlapInstrProfile(const std::string &BaseFilename,
1802                                 const std::string &TestFilename,
1803                                 const OverlapFuncFilters &FuncFilter,
1804                                 raw_fd_ostream &OS, bool IsCS) {
1805   std::mutex ErrorLock;
1806   SmallSet<instrprof_error, 4> WriterErrorCodes;
1807   WriterContext Context(false, ErrorLock, WriterErrorCodes);
1808   WeightedFile WeightedInput{BaseFilename, 1};
1809   OverlapStats Overlap;
1810   Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS);
1811   if (E)
1812     exitWithError(std::move(E), "error in getting profile count sums");
1813   if (Overlap.Base.CountSum < 1.0f) {
1814     OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
1815     exit(0);
1816   }
1817   if (Overlap.Test.CountSum < 1.0f) {
1818     OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
1819     exit(0);
1820   }
1821   loadInput(WeightedInput, nullptr, nullptr, /*ProfiledBinary=*/"", &Context);
1822   overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
1823                IsCS);
1824   Overlap.dump(OS);
1825 }
1826 
1827 namespace {
1828 struct SampleOverlapStats {
1829   SampleContext BaseName;
1830   SampleContext TestName;
1831   // Number of overlap units
1832   uint64_t OverlapCount = 0;
1833   // Total samples of overlap units
1834   uint64_t OverlapSample = 0;
1835   // Number of and total samples of units that only present in base or test
1836   // profile
1837   uint64_t BaseUniqueCount = 0;
1838   uint64_t BaseUniqueSample = 0;
1839   uint64_t TestUniqueCount = 0;
1840   uint64_t TestUniqueSample = 0;
1841   // Number of units and total samples in base or test profile
1842   uint64_t BaseCount = 0;
1843   uint64_t BaseSample = 0;
1844   uint64_t TestCount = 0;
1845   uint64_t TestSample = 0;
1846   // Number of and total samples of units that present in at least one profile
1847   uint64_t UnionCount = 0;
1848   uint64_t UnionSample = 0;
1849   // Weighted similarity
1850   double Similarity = 0.0;
1851   // For SampleOverlapStats instances representing functions, weights of the
1852   // function in base and test profiles
1853   double BaseWeight = 0.0;
1854   double TestWeight = 0.0;
1855 
1856   SampleOverlapStats() = default;
1857 };
1858 } // end anonymous namespace
1859 
1860 namespace {
1861 struct FuncSampleStats {
1862   uint64_t SampleSum = 0;
1863   uint64_t MaxSample = 0;
1864   uint64_t HotBlockCount = 0;
1865   FuncSampleStats() = default;
1866   FuncSampleStats(uint64_t SampleSum, uint64_t MaxSample,
1867                   uint64_t HotBlockCount)
1868       : SampleSum(SampleSum), MaxSample(MaxSample),
1869         HotBlockCount(HotBlockCount) {}
1870 };
1871 } // end anonymous namespace
1872 
1873 namespace {
1874 enum MatchStatus { MS_Match, MS_FirstUnique, MS_SecondUnique, MS_None };
1875 
1876 // Class for updating merging steps for two sorted maps. The class should be
1877 // instantiated with a map iterator type.
1878 template <class T> class MatchStep {
1879 public:
1880   MatchStep() = delete;
1881 
1882   MatchStep(T FirstIter, T FirstEnd, T SecondIter, T SecondEnd)
1883       : FirstIter(FirstIter), FirstEnd(FirstEnd), SecondIter(SecondIter),
1884         SecondEnd(SecondEnd), Status(MS_None) {}
1885 
1886   bool areBothFinished() const {
1887     return (FirstIter == FirstEnd && SecondIter == SecondEnd);
1888   }
1889 
1890   bool isFirstFinished() const { return FirstIter == FirstEnd; }
1891 
1892   bool isSecondFinished() const { return SecondIter == SecondEnd; }
1893 
1894   /// Advance one step based on the previous match status unless the previous
1895   /// status is MS_None. Then update Status based on the comparison between two
1896   /// container iterators at the current step. If the previous status is
1897   /// MS_None, it means two iterators are at the beginning and no comparison has
1898   /// been made, so we simply update Status without advancing the iterators.
1899   void updateOneStep();
1900 
1901   T getFirstIter() const { return FirstIter; }
1902 
1903   T getSecondIter() const { return SecondIter; }
1904 
1905   MatchStatus getMatchStatus() const { return Status; }
1906 
1907 private:
1908   // Current iterator and end iterator of the first container.
1909   T FirstIter;
1910   T FirstEnd;
1911   // Current iterator and end iterator of the second container.
1912   T SecondIter;
1913   T SecondEnd;
1914   // Match status of the current step.
1915   MatchStatus Status;
1916 };
1917 } // end anonymous namespace
1918 
1919 template <class T> void MatchStep<T>::updateOneStep() {
1920   switch (Status) {
1921   case MS_Match:
1922     ++FirstIter;
1923     ++SecondIter;
1924     break;
1925   case MS_FirstUnique:
1926     ++FirstIter;
1927     break;
1928   case MS_SecondUnique:
1929     ++SecondIter;
1930     break;
1931   case MS_None:
1932     break;
1933   }
1934 
1935   // Update Status according to iterators at the current step.
1936   if (areBothFinished())
1937     return;
1938   if (FirstIter != FirstEnd &&
1939       (SecondIter == SecondEnd || FirstIter->first < SecondIter->first))
1940     Status = MS_FirstUnique;
1941   else if (SecondIter != SecondEnd &&
1942            (FirstIter == FirstEnd || SecondIter->first < FirstIter->first))
1943     Status = MS_SecondUnique;
1944   else
1945     Status = MS_Match;
1946 }
1947 
1948 // Return the sum of line/block samples, the max line/block sample, and the
1949 // number of line/block samples above the given threshold in a function
1950 // including its inlinees.
1951 static void getFuncSampleStats(const sampleprof::FunctionSamples &Func,
1952                                FuncSampleStats &FuncStats,
1953                                uint64_t HotThreshold) {
1954   for (const auto &L : Func.getBodySamples()) {
1955     uint64_t Sample = L.second.getSamples();
1956     FuncStats.SampleSum += Sample;
1957     FuncStats.MaxSample = std::max(FuncStats.MaxSample, Sample);
1958     if (Sample >= HotThreshold)
1959       ++FuncStats.HotBlockCount;
1960   }
1961 
1962   for (const auto &C : Func.getCallsiteSamples()) {
1963     for (const auto &F : C.second)
1964       getFuncSampleStats(F.second, FuncStats, HotThreshold);
1965   }
1966 }
1967 
1968 /// Predicate that determines if a function is hot with a given threshold. We
1969 /// keep it separate from its callsites for possible extension in the future.
1970 static bool isFunctionHot(const FuncSampleStats &FuncStats,
1971                           uint64_t HotThreshold) {
1972   // We intentionally compare the maximum sample count in a function with the
1973   // HotThreshold to get an approximate determination on hot functions.
1974   return (FuncStats.MaxSample >= HotThreshold);
1975 }
1976 
1977 namespace {
1978 class SampleOverlapAggregator {
1979 public:
1980   SampleOverlapAggregator(const std::string &BaseFilename,
1981                           const std::string &TestFilename,
1982                           double LowSimilarityThreshold, double Epsilon,
1983                           const OverlapFuncFilters &FuncFilter)
1984       : BaseFilename(BaseFilename), TestFilename(TestFilename),
1985         LowSimilarityThreshold(LowSimilarityThreshold), Epsilon(Epsilon),
1986         FuncFilter(FuncFilter) {}
1987 
1988   /// Detect 0-sample input profile and report to output stream. This interface
1989   /// should be called after loadProfiles().
1990   bool detectZeroSampleProfile(raw_fd_ostream &OS) const;
1991 
1992   /// Write out function-level similarity statistics for functions specified by
1993   /// options --function, --value-cutoff, and --similarity-cutoff.
1994   void dumpFuncSimilarity(raw_fd_ostream &OS) const;
1995 
1996   /// Write out program-level similarity and overlap statistics.
1997   void dumpProgramSummary(raw_fd_ostream &OS) const;
1998 
1999   /// Write out hot-function and hot-block statistics for base_profile,
2000   /// test_profile, and their overlap. For both cases, the overlap HO is
2001   /// calculated as follows:
2002   ///    Given the number of functions (or blocks) that are hot in both profiles
2003   ///    HCommon and the number of functions (or blocks) that are hot in at
2004   ///    least one profile HUnion, HO = HCommon / HUnion.
2005   void dumpHotFuncAndBlockOverlap(raw_fd_ostream &OS) const;
2006 
2007   /// This function tries matching functions in base and test profiles. For each
2008   /// pair of matched functions, it aggregates the function-level
2009   /// similarity into a profile-level similarity. It also dump function-level
2010   /// similarity information of functions specified by --function,
2011   /// --value-cutoff, and --similarity-cutoff options. The program-level
2012   /// similarity PS is computed as follows:
2013   ///     Given function-level similarity FS(A) for all function A, the
2014   ///     weight of function A in base profile WB(A), and the weight of function
2015   ///     A in test profile WT(A), compute PS(base_profile, test_profile) =
2016   ///     sum_A(FS(A) * avg(WB(A), WT(A))) ranging in [0.0f to 1.0f] with 0.0
2017   ///     meaning no-overlap.
2018   void computeSampleProfileOverlap(raw_fd_ostream &OS);
2019 
2020   /// Initialize ProfOverlap with the sum of samples in base and test
2021   /// profiles. This function also computes and keeps the sum of samples and
2022   /// max sample counts of each function in BaseStats and TestStats for later
2023   /// use to avoid re-computations.
2024   void initializeSampleProfileOverlap();
2025 
2026   /// Load profiles specified by BaseFilename and TestFilename.
2027   std::error_code loadProfiles();
2028 
2029   using FuncSampleStatsMap =
2030       std::unordered_map<SampleContext, FuncSampleStats, SampleContext::Hash>;
2031 
2032 private:
2033   SampleOverlapStats ProfOverlap;
2034   SampleOverlapStats HotFuncOverlap;
2035   SampleOverlapStats HotBlockOverlap;
2036   std::string BaseFilename;
2037   std::string TestFilename;
2038   std::unique_ptr<sampleprof::SampleProfileReader> BaseReader;
2039   std::unique_ptr<sampleprof::SampleProfileReader> TestReader;
2040   // BaseStats and TestStats hold FuncSampleStats for each function, with
2041   // function name as the key.
2042   FuncSampleStatsMap BaseStats;
2043   FuncSampleStatsMap TestStats;
2044   // Low similarity threshold in floating point number
2045   double LowSimilarityThreshold;
2046   // Block samples above BaseHotThreshold or TestHotThreshold are considered hot
2047   // for tracking hot blocks.
2048   uint64_t BaseHotThreshold;
2049   uint64_t TestHotThreshold;
2050   // A small threshold used to round the results of floating point accumulations
2051   // to resolve imprecision.
2052   const double Epsilon;
2053   std::multimap<double, SampleOverlapStats, std::greater<double>>
2054       FuncSimilarityDump;
2055   // FuncFilter carries specifications in options --value-cutoff and
2056   // --function.
2057   OverlapFuncFilters FuncFilter;
2058   // Column offsets for printing the function-level details table.
2059   static const unsigned int TestWeightCol = 15;
2060   static const unsigned int SimilarityCol = 30;
2061   static const unsigned int OverlapCol = 43;
2062   static const unsigned int BaseUniqueCol = 53;
2063   static const unsigned int TestUniqueCol = 67;
2064   static const unsigned int BaseSampleCol = 81;
2065   static const unsigned int TestSampleCol = 96;
2066   static const unsigned int FuncNameCol = 111;
2067 
2068   /// Return a similarity of two line/block sample counters in the same
2069   /// function in base and test profiles. The line/block-similarity BS(i) is
2070   /// computed as follows:
2071   ///    For an offsets i, given the sample count at i in base profile BB(i),
2072   ///    the sample count at i in test profile BT(i), the sum of sample counts
2073   ///    in this function in base profile SB, and the sum of sample counts in
2074   ///    this function in test profile ST, compute BS(i) = 1.0 - fabs(BB(i)/SB -
2075   ///    BT(i)/ST), ranging in [0.0f to 1.0f] with 0.0 meaning no-overlap.
2076   double computeBlockSimilarity(uint64_t BaseSample, uint64_t TestSample,
2077                                 const SampleOverlapStats &FuncOverlap) const;
2078 
2079   void updateHotBlockOverlap(uint64_t BaseSample, uint64_t TestSample,
2080                              uint64_t HotBlockCount);
2081 
2082   void getHotFunctions(const FuncSampleStatsMap &ProfStats,
2083                        FuncSampleStatsMap &HotFunc,
2084                        uint64_t HotThreshold) const;
2085 
2086   void computeHotFuncOverlap();
2087 
2088   /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
2089   /// Difference for two sample units in a matched function according to the
2090   /// given match status.
2091   void updateOverlapStatsForFunction(uint64_t BaseSample, uint64_t TestSample,
2092                                      uint64_t HotBlockCount,
2093                                      SampleOverlapStats &FuncOverlap,
2094                                      double &Difference, MatchStatus Status);
2095 
2096   /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
2097   /// Difference for unmatched callees that only present in one profile in a
2098   /// matched caller function.
2099   void updateForUnmatchedCallee(const sampleprof::FunctionSamples &Func,
2100                                 SampleOverlapStats &FuncOverlap,
2101                                 double &Difference, MatchStatus Status);
2102 
2103   /// This function updates sample overlap statistics of an overlap function in
2104   /// base and test profile. It also calculates a function-internal similarity
2105   /// FIS as follows:
2106   ///    For offsets i that have samples in at least one profile in this
2107   ///    function A, given BS(i) returned by computeBlockSimilarity(), compute
2108   ///    FIS(A) = (2.0 - sum_i(1.0 - BS(i))) / 2, ranging in [0.0f to 1.0f] with
2109   ///    0.0 meaning no overlap.
2110   double computeSampleFunctionInternalOverlap(
2111       const sampleprof::FunctionSamples &BaseFunc,
2112       const sampleprof::FunctionSamples &TestFunc,
2113       SampleOverlapStats &FuncOverlap);
2114 
2115   /// Function-level similarity (FS) is a weighted value over function internal
2116   /// similarity (FIS). This function computes a function's FS from its FIS by
2117   /// applying the weight.
2118   double weightForFuncSimilarity(double FuncSimilarity, uint64_t BaseFuncSample,
2119                                  uint64_t TestFuncSample) const;
2120 
2121   /// The function-level similarity FS(A) for a function A is computed as
2122   /// follows:
2123   ///     Compute a function-internal similarity FIS(A) by
2124   ///     computeSampleFunctionInternalOverlap(). Then, with the weight of
2125   ///     function A in base profile WB(A), and the weight of function A in test
2126   ///     profile WT(A), compute FS(A) = FIS(A) * (1.0 - fabs(WB(A) - WT(A)))
2127   ///     ranging in [0.0f to 1.0f] with 0.0 meaning no overlap.
2128   double
2129   computeSampleFunctionOverlap(const sampleprof::FunctionSamples *BaseFunc,
2130                                const sampleprof::FunctionSamples *TestFunc,
2131                                SampleOverlapStats *FuncOverlap,
2132                                uint64_t BaseFuncSample,
2133                                uint64_t TestFuncSample);
2134 
2135   /// Profile-level similarity (PS) is a weighted aggregate over function-level
2136   /// similarities (FS). This method weights the FS value by the function
2137   /// weights in the base and test profiles for the aggregation.
2138   double weightByImportance(double FuncSimilarity, uint64_t BaseFuncSample,
2139                             uint64_t TestFuncSample) const;
2140 };
2141 } // end anonymous namespace
2142 
2143 bool SampleOverlapAggregator::detectZeroSampleProfile(
2144     raw_fd_ostream &OS) const {
2145   bool HaveZeroSample = false;
2146   if (ProfOverlap.BaseSample == 0) {
2147     OS << "Sum of sample counts for profile " << BaseFilename << " is 0.\n";
2148     HaveZeroSample = true;
2149   }
2150   if (ProfOverlap.TestSample == 0) {
2151     OS << "Sum of sample counts for profile " << TestFilename << " is 0.\n";
2152     HaveZeroSample = true;
2153   }
2154   return HaveZeroSample;
2155 }
2156 
2157 double SampleOverlapAggregator::computeBlockSimilarity(
2158     uint64_t BaseSample, uint64_t TestSample,
2159     const SampleOverlapStats &FuncOverlap) const {
2160   double BaseFrac = 0.0;
2161   double TestFrac = 0.0;
2162   if (FuncOverlap.BaseSample > 0)
2163     BaseFrac = static_cast<double>(BaseSample) / FuncOverlap.BaseSample;
2164   if (FuncOverlap.TestSample > 0)
2165     TestFrac = static_cast<double>(TestSample) / FuncOverlap.TestSample;
2166   return 1.0 - std::fabs(BaseFrac - TestFrac);
2167 }
2168 
2169 void SampleOverlapAggregator::updateHotBlockOverlap(uint64_t BaseSample,
2170                                                     uint64_t TestSample,
2171                                                     uint64_t HotBlockCount) {
2172   bool IsBaseHot = (BaseSample >= BaseHotThreshold);
2173   bool IsTestHot = (TestSample >= TestHotThreshold);
2174   if (!IsBaseHot && !IsTestHot)
2175     return;
2176 
2177   HotBlockOverlap.UnionCount += HotBlockCount;
2178   if (IsBaseHot)
2179     HotBlockOverlap.BaseCount += HotBlockCount;
2180   if (IsTestHot)
2181     HotBlockOverlap.TestCount += HotBlockCount;
2182   if (IsBaseHot && IsTestHot)
2183     HotBlockOverlap.OverlapCount += HotBlockCount;
2184 }
2185 
2186 void SampleOverlapAggregator::getHotFunctions(
2187     const FuncSampleStatsMap &ProfStats, FuncSampleStatsMap &HotFunc,
2188     uint64_t HotThreshold) const {
2189   for (const auto &F : ProfStats) {
2190     if (isFunctionHot(F.second, HotThreshold))
2191       HotFunc.emplace(F.first, F.second);
2192   }
2193 }
2194 
2195 void SampleOverlapAggregator::computeHotFuncOverlap() {
2196   FuncSampleStatsMap BaseHotFunc;
2197   getHotFunctions(BaseStats, BaseHotFunc, BaseHotThreshold);
2198   HotFuncOverlap.BaseCount = BaseHotFunc.size();
2199 
2200   FuncSampleStatsMap TestHotFunc;
2201   getHotFunctions(TestStats, TestHotFunc, TestHotThreshold);
2202   HotFuncOverlap.TestCount = TestHotFunc.size();
2203   HotFuncOverlap.UnionCount = HotFuncOverlap.TestCount;
2204 
2205   for (const auto &F : BaseHotFunc) {
2206     if (TestHotFunc.count(F.first))
2207       ++HotFuncOverlap.OverlapCount;
2208     else
2209       ++HotFuncOverlap.UnionCount;
2210   }
2211 }
2212 
2213 void SampleOverlapAggregator::updateOverlapStatsForFunction(
2214     uint64_t BaseSample, uint64_t TestSample, uint64_t HotBlockCount,
2215     SampleOverlapStats &FuncOverlap, double &Difference, MatchStatus Status) {
2216   assert(Status != MS_None &&
2217          "Match status should be updated before updating overlap statistics");
2218   if (Status == MS_FirstUnique) {
2219     TestSample = 0;
2220     FuncOverlap.BaseUniqueSample += BaseSample;
2221   } else if (Status == MS_SecondUnique) {
2222     BaseSample = 0;
2223     FuncOverlap.TestUniqueSample += TestSample;
2224   } else {
2225     ++FuncOverlap.OverlapCount;
2226   }
2227 
2228   FuncOverlap.UnionSample += std::max(BaseSample, TestSample);
2229   FuncOverlap.OverlapSample += std::min(BaseSample, TestSample);
2230   Difference +=
2231       1.0 - computeBlockSimilarity(BaseSample, TestSample, FuncOverlap);
2232   updateHotBlockOverlap(BaseSample, TestSample, HotBlockCount);
2233 }
2234 
2235 void SampleOverlapAggregator::updateForUnmatchedCallee(
2236     const sampleprof::FunctionSamples &Func, SampleOverlapStats &FuncOverlap,
2237     double &Difference, MatchStatus Status) {
2238   assert((Status == MS_FirstUnique || Status == MS_SecondUnique) &&
2239          "Status must be either of the two unmatched cases");
2240   FuncSampleStats FuncStats;
2241   if (Status == MS_FirstUnique) {
2242     getFuncSampleStats(Func, FuncStats, BaseHotThreshold);
2243     updateOverlapStatsForFunction(FuncStats.SampleSum, 0,
2244                                   FuncStats.HotBlockCount, FuncOverlap,
2245                                   Difference, Status);
2246   } else {
2247     getFuncSampleStats(Func, FuncStats, TestHotThreshold);
2248     updateOverlapStatsForFunction(0, FuncStats.SampleSum,
2249                                   FuncStats.HotBlockCount, FuncOverlap,
2250                                   Difference, Status);
2251   }
2252 }
2253 
2254 double SampleOverlapAggregator::computeSampleFunctionInternalOverlap(
2255     const sampleprof::FunctionSamples &BaseFunc,
2256     const sampleprof::FunctionSamples &TestFunc,
2257     SampleOverlapStats &FuncOverlap) {
2258 
2259   using namespace sampleprof;
2260 
2261   double Difference = 0;
2262 
2263   // Accumulate Difference for regular line/block samples in the function.
2264   // We match them through sort-merge join algorithm because
2265   // FunctionSamples::getBodySamples() returns a map of sample counters ordered
2266   // by their offsets.
2267   MatchStep<BodySampleMap::const_iterator> BlockIterStep(
2268       BaseFunc.getBodySamples().cbegin(), BaseFunc.getBodySamples().cend(),
2269       TestFunc.getBodySamples().cbegin(), TestFunc.getBodySamples().cend());
2270   BlockIterStep.updateOneStep();
2271   while (!BlockIterStep.areBothFinished()) {
2272     uint64_t BaseSample =
2273         BlockIterStep.isFirstFinished()
2274             ? 0
2275             : BlockIterStep.getFirstIter()->second.getSamples();
2276     uint64_t TestSample =
2277         BlockIterStep.isSecondFinished()
2278             ? 0
2279             : BlockIterStep.getSecondIter()->second.getSamples();
2280     updateOverlapStatsForFunction(BaseSample, TestSample, 1, FuncOverlap,
2281                                   Difference, BlockIterStep.getMatchStatus());
2282 
2283     BlockIterStep.updateOneStep();
2284   }
2285 
2286   // Accumulate Difference for callsite lines in the function. We match
2287   // them through sort-merge algorithm because
2288   // FunctionSamples::getCallsiteSamples() returns a map of callsite records
2289   // ordered by their offsets.
2290   MatchStep<CallsiteSampleMap::const_iterator> CallsiteIterStep(
2291       BaseFunc.getCallsiteSamples().cbegin(),
2292       BaseFunc.getCallsiteSamples().cend(),
2293       TestFunc.getCallsiteSamples().cbegin(),
2294       TestFunc.getCallsiteSamples().cend());
2295   CallsiteIterStep.updateOneStep();
2296   while (!CallsiteIterStep.areBothFinished()) {
2297     MatchStatus CallsiteStepStatus = CallsiteIterStep.getMatchStatus();
2298     assert(CallsiteStepStatus != MS_None &&
2299            "Match status should be updated before entering loop body");
2300 
2301     if (CallsiteStepStatus != MS_Match) {
2302       auto Callsite = (CallsiteStepStatus == MS_FirstUnique)
2303                           ? CallsiteIterStep.getFirstIter()
2304                           : CallsiteIterStep.getSecondIter();
2305       for (const auto &F : Callsite->second)
2306         updateForUnmatchedCallee(F.second, FuncOverlap, Difference,
2307                                  CallsiteStepStatus);
2308     } else {
2309       // There may be multiple inlinees at the same offset, so we need to try
2310       // matching all of them. This match is implemented through sort-merge
2311       // algorithm because callsite records at the same offset are ordered by
2312       // function names.
2313       MatchStep<FunctionSamplesMap::const_iterator> CalleeIterStep(
2314           CallsiteIterStep.getFirstIter()->second.cbegin(),
2315           CallsiteIterStep.getFirstIter()->second.cend(),
2316           CallsiteIterStep.getSecondIter()->second.cbegin(),
2317           CallsiteIterStep.getSecondIter()->second.cend());
2318       CalleeIterStep.updateOneStep();
2319       while (!CalleeIterStep.areBothFinished()) {
2320         MatchStatus CalleeStepStatus = CalleeIterStep.getMatchStatus();
2321         if (CalleeStepStatus != MS_Match) {
2322           auto Callee = (CalleeStepStatus == MS_FirstUnique)
2323                             ? CalleeIterStep.getFirstIter()
2324                             : CalleeIterStep.getSecondIter();
2325           updateForUnmatchedCallee(Callee->second, FuncOverlap, Difference,
2326                                    CalleeStepStatus);
2327         } else {
2328           // An inlined function can contain other inlinees inside, so compute
2329           // the Difference recursively.
2330           Difference += 2.0 - 2 * computeSampleFunctionInternalOverlap(
2331                                       CalleeIterStep.getFirstIter()->second,
2332                                       CalleeIterStep.getSecondIter()->second,
2333                                       FuncOverlap);
2334         }
2335         CalleeIterStep.updateOneStep();
2336       }
2337     }
2338     CallsiteIterStep.updateOneStep();
2339   }
2340 
2341   // Difference reflects the total differences of line/block samples in this
2342   // function and ranges in [0.0f to 2.0f]. Take (2.0 - Difference) / 2 to
2343   // reflect the similarity between function profiles in [0.0f to 1.0f].
2344   return (2.0 - Difference) / 2;
2345 }
2346 
2347 double SampleOverlapAggregator::weightForFuncSimilarity(
2348     double FuncInternalSimilarity, uint64_t BaseFuncSample,
2349     uint64_t TestFuncSample) const {
2350   // Compute the weight as the distance between the function weights in two
2351   // profiles.
2352   double BaseFrac = 0.0;
2353   double TestFrac = 0.0;
2354   assert(ProfOverlap.BaseSample > 0 &&
2355          "Total samples in base profile should be greater than 0");
2356   BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample;
2357   assert(ProfOverlap.TestSample > 0 &&
2358          "Total samples in test profile should be greater than 0");
2359   TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample;
2360   double WeightDistance = std::fabs(BaseFrac - TestFrac);
2361 
2362   // Take WeightDistance into the similarity.
2363   return FuncInternalSimilarity * (1 - WeightDistance);
2364 }
2365 
2366 double
2367 SampleOverlapAggregator::weightByImportance(double FuncSimilarity,
2368                                             uint64_t BaseFuncSample,
2369                                             uint64_t TestFuncSample) const {
2370 
2371   double BaseFrac = 0.0;
2372   double TestFrac = 0.0;
2373   assert(ProfOverlap.BaseSample > 0 &&
2374          "Total samples in base profile should be greater than 0");
2375   BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample / 2.0;
2376   assert(ProfOverlap.TestSample > 0 &&
2377          "Total samples in test profile should be greater than 0");
2378   TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample / 2.0;
2379   return FuncSimilarity * (BaseFrac + TestFrac);
2380 }
2381 
2382 double SampleOverlapAggregator::computeSampleFunctionOverlap(
2383     const sampleprof::FunctionSamples *BaseFunc,
2384     const sampleprof::FunctionSamples *TestFunc,
2385     SampleOverlapStats *FuncOverlap, uint64_t BaseFuncSample,
2386     uint64_t TestFuncSample) {
2387   // Default function internal similarity before weighted, meaning two functions
2388   // has no overlap.
2389   const double DefaultFuncInternalSimilarity = 0;
2390   double FuncSimilarity;
2391   double FuncInternalSimilarity;
2392 
2393   // If BaseFunc or TestFunc is nullptr, it means the functions do not overlap.
2394   // In this case, we use DefaultFuncInternalSimilarity as the function internal
2395   // similarity.
2396   if (!BaseFunc || !TestFunc) {
2397     FuncInternalSimilarity = DefaultFuncInternalSimilarity;
2398   } else {
2399     assert(FuncOverlap != nullptr &&
2400            "FuncOverlap should be provided in this case");
2401     FuncInternalSimilarity = computeSampleFunctionInternalOverlap(
2402         *BaseFunc, *TestFunc, *FuncOverlap);
2403     // Now, FuncInternalSimilarity may be a little less than 0 due to
2404     // imprecision of floating point accumulations. Make it zero if the
2405     // difference is below Epsilon.
2406     FuncInternalSimilarity = (std::fabs(FuncInternalSimilarity - 0) < Epsilon)
2407                                  ? 0
2408                                  : FuncInternalSimilarity;
2409   }
2410   FuncSimilarity = weightForFuncSimilarity(FuncInternalSimilarity,
2411                                            BaseFuncSample, TestFuncSample);
2412   return FuncSimilarity;
2413 }
2414 
2415 void SampleOverlapAggregator::computeSampleProfileOverlap(raw_fd_ostream &OS) {
2416   using namespace sampleprof;
2417 
2418   std::unordered_map<SampleContext, const FunctionSamples *,
2419                      SampleContext::Hash>
2420       BaseFuncProf;
2421   const auto &BaseProfiles = BaseReader->getProfiles();
2422   for (const auto &BaseFunc : BaseProfiles) {
2423     BaseFuncProf.emplace(BaseFunc.second.getContext(), &(BaseFunc.second));
2424   }
2425   ProfOverlap.UnionCount = BaseFuncProf.size();
2426 
2427   const auto &TestProfiles = TestReader->getProfiles();
2428   for (const auto &TestFunc : TestProfiles) {
2429     SampleOverlapStats FuncOverlap;
2430     FuncOverlap.TestName = TestFunc.second.getContext();
2431     assert(TestStats.count(FuncOverlap.TestName) &&
2432            "TestStats should have records for all functions in test profile "
2433            "except inlinees");
2434     FuncOverlap.TestSample = TestStats[FuncOverlap.TestName].SampleSum;
2435 
2436     bool Matched = false;
2437     const auto Match = BaseFuncProf.find(FuncOverlap.TestName);
2438     if (Match == BaseFuncProf.end()) {
2439       const FuncSampleStats &FuncStats = TestStats[FuncOverlap.TestName];
2440       ++ProfOverlap.TestUniqueCount;
2441       ProfOverlap.TestUniqueSample += FuncStats.SampleSum;
2442       FuncOverlap.TestUniqueSample = FuncStats.SampleSum;
2443 
2444       updateHotBlockOverlap(0, FuncStats.SampleSum, FuncStats.HotBlockCount);
2445 
2446       double FuncSimilarity = computeSampleFunctionOverlap(
2447           nullptr, nullptr, nullptr, 0, FuncStats.SampleSum);
2448       ProfOverlap.Similarity +=
2449           weightByImportance(FuncSimilarity, 0, FuncStats.SampleSum);
2450 
2451       ++ProfOverlap.UnionCount;
2452       ProfOverlap.UnionSample += FuncStats.SampleSum;
2453     } else {
2454       ++ProfOverlap.OverlapCount;
2455 
2456       // Two functions match with each other. Compute function-level overlap and
2457       // aggregate them into profile-level overlap.
2458       FuncOverlap.BaseName = Match->second->getContext();
2459       assert(BaseStats.count(FuncOverlap.BaseName) &&
2460              "BaseStats should have records for all functions in base profile "
2461              "except inlinees");
2462       FuncOverlap.BaseSample = BaseStats[FuncOverlap.BaseName].SampleSum;
2463 
2464       FuncOverlap.Similarity = computeSampleFunctionOverlap(
2465           Match->second, &TestFunc.second, &FuncOverlap, FuncOverlap.BaseSample,
2466           FuncOverlap.TestSample);
2467       ProfOverlap.Similarity +=
2468           weightByImportance(FuncOverlap.Similarity, FuncOverlap.BaseSample,
2469                              FuncOverlap.TestSample);
2470       ProfOverlap.OverlapSample += FuncOverlap.OverlapSample;
2471       ProfOverlap.UnionSample += FuncOverlap.UnionSample;
2472 
2473       // Accumulate the percentage of base unique and test unique samples into
2474       // ProfOverlap.
2475       ProfOverlap.BaseUniqueSample += FuncOverlap.BaseUniqueSample;
2476       ProfOverlap.TestUniqueSample += FuncOverlap.TestUniqueSample;
2477 
2478       // Remove matched base functions for later reporting functions not found
2479       // in test profile.
2480       BaseFuncProf.erase(Match);
2481       Matched = true;
2482     }
2483 
2484     // Print function-level similarity information if specified by options.
2485     assert(TestStats.count(FuncOverlap.TestName) &&
2486            "TestStats should have records for all functions in test profile "
2487            "except inlinees");
2488     if (TestStats[FuncOverlap.TestName].MaxSample >= FuncFilter.ValueCutoff ||
2489         (Matched && FuncOverlap.Similarity < LowSimilarityThreshold) ||
2490         (Matched && !FuncFilter.NameFilter.empty() &&
2491          FuncOverlap.BaseName.toString().find(FuncFilter.NameFilter) !=
2492              std::string::npos)) {
2493       assert(ProfOverlap.BaseSample > 0 &&
2494              "Total samples in base profile should be greater than 0");
2495       FuncOverlap.BaseWeight =
2496           static_cast<double>(FuncOverlap.BaseSample) / ProfOverlap.BaseSample;
2497       assert(ProfOverlap.TestSample > 0 &&
2498              "Total samples in test profile should be greater than 0");
2499       FuncOverlap.TestWeight =
2500           static_cast<double>(FuncOverlap.TestSample) / ProfOverlap.TestSample;
2501       FuncSimilarityDump.emplace(FuncOverlap.BaseWeight, FuncOverlap);
2502     }
2503   }
2504 
2505   // Traverse through functions in base profile but not in test profile.
2506   for (const auto &F : BaseFuncProf) {
2507     assert(BaseStats.count(F.second->getContext()) &&
2508            "BaseStats should have records for all functions in base profile "
2509            "except inlinees");
2510     const FuncSampleStats &FuncStats = BaseStats[F.second->getContext()];
2511     ++ProfOverlap.BaseUniqueCount;
2512     ProfOverlap.BaseUniqueSample += FuncStats.SampleSum;
2513 
2514     updateHotBlockOverlap(FuncStats.SampleSum, 0, FuncStats.HotBlockCount);
2515 
2516     double FuncSimilarity = computeSampleFunctionOverlap(
2517         nullptr, nullptr, nullptr, FuncStats.SampleSum, 0);
2518     ProfOverlap.Similarity +=
2519         weightByImportance(FuncSimilarity, FuncStats.SampleSum, 0);
2520 
2521     ProfOverlap.UnionSample += FuncStats.SampleSum;
2522   }
2523 
2524   // Now, ProfSimilarity may be a little greater than 1 due to imprecision
2525   // of floating point accumulations. Make it 1.0 if the difference is below
2526   // Epsilon.
2527   ProfOverlap.Similarity = (std::fabs(ProfOverlap.Similarity - 1) < Epsilon)
2528                                ? 1
2529                                : ProfOverlap.Similarity;
2530 
2531   computeHotFuncOverlap();
2532 }
2533 
2534 void SampleOverlapAggregator::initializeSampleProfileOverlap() {
2535   const auto &BaseProf = BaseReader->getProfiles();
2536   for (const auto &I : BaseProf) {
2537     ++ProfOverlap.BaseCount;
2538     FuncSampleStats FuncStats;
2539     getFuncSampleStats(I.second, FuncStats, BaseHotThreshold);
2540     ProfOverlap.BaseSample += FuncStats.SampleSum;
2541     BaseStats.emplace(I.second.getContext(), FuncStats);
2542   }
2543 
2544   const auto &TestProf = TestReader->getProfiles();
2545   for (const auto &I : TestProf) {
2546     ++ProfOverlap.TestCount;
2547     FuncSampleStats FuncStats;
2548     getFuncSampleStats(I.second, FuncStats, TestHotThreshold);
2549     ProfOverlap.TestSample += FuncStats.SampleSum;
2550     TestStats.emplace(I.second.getContext(), FuncStats);
2551   }
2552 
2553   ProfOverlap.BaseName = StringRef(BaseFilename);
2554   ProfOverlap.TestName = StringRef(TestFilename);
2555 }
2556 
2557 void SampleOverlapAggregator::dumpFuncSimilarity(raw_fd_ostream &OS) const {
2558   using namespace sampleprof;
2559 
2560   if (FuncSimilarityDump.empty())
2561     return;
2562 
2563   formatted_raw_ostream FOS(OS);
2564   FOS << "Function-level details:\n";
2565   FOS << "Base weight";
2566   FOS.PadToColumn(TestWeightCol);
2567   FOS << "Test weight";
2568   FOS.PadToColumn(SimilarityCol);
2569   FOS << "Similarity";
2570   FOS.PadToColumn(OverlapCol);
2571   FOS << "Overlap";
2572   FOS.PadToColumn(BaseUniqueCol);
2573   FOS << "Base unique";
2574   FOS.PadToColumn(TestUniqueCol);
2575   FOS << "Test unique";
2576   FOS.PadToColumn(BaseSampleCol);
2577   FOS << "Base samples";
2578   FOS.PadToColumn(TestSampleCol);
2579   FOS << "Test samples";
2580   FOS.PadToColumn(FuncNameCol);
2581   FOS << "Function name\n";
2582   for (const auto &F : FuncSimilarityDump) {
2583     double OverlapPercent =
2584         F.second.UnionSample > 0
2585             ? static_cast<double>(F.second.OverlapSample) / F.second.UnionSample
2586             : 0;
2587     double BaseUniquePercent =
2588         F.second.BaseSample > 0
2589             ? static_cast<double>(F.second.BaseUniqueSample) /
2590                   F.second.BaseSample
2591             : 0;
2592     double TestUniquePercent =
2593         F.second.TestSample > 0
2594             ? static_cast<double>(F.second.TestUniqueSample) /
2595                   F.second.TestSample
2596             : 0;
2597 
2598     FOS << format("%.2f%%", F.second.BaseWeight * 100);
2599     FOS.PadToColumn(TestWeightCol);
2600     FOS << format("%.2f%%", F.second.TestWeight * 100);
2601     FOS.PadToColumn(SimilarityCol);
2602     FOS << format("%.2f%%", F.second.Similarity * 100);
2603     FOS.PadToColumn(OverlapCol);
2604     FOS << format("%.2f%%", OverlapPercent * 100);
2605     FOS.PadToColumn(BaseUniqueCol);
2606     FOS << format("%.2f%%", BaseUniquePercent * 100);
2607     FOS.PadToColumn(TestUniqueCol);
2608     FOS << format("%.2f%%", TestUniquePercent * 100);
2609     FOS.PadToColumn(BaseSampleCol);
2610     FOS << F.second.BaseSample;
2611     FOS.PadToColumn(TestSampleCol);
2612     FOS << F.second.TestSample;
2613     FOS.PadToColumn(FuncNameCol);
2614     FOS << F.second.TestName.toString() << "\n";
2615   }
2616 }
2617 
2618 void SampleOverlapAggregator::dumpProgramSummary(raw_fd_ostream &OS) const {
2619   OS << "Profile overlap infomation for base_profile: "
2620      << ProfOverlap.BaseName.toString()
2621      << " and test_profile: " << ProfOverlap.TestName.toString()
2622      << "\nProgram level:\n";
2623 
2624   OS << "  Whole program profile similarity: "
2625      << format("%.3f%%", ProfOverlap.Similarity * 100) << "\n";
2626 
2627   assert(ProfOverlap.UnionSample > 0 &&
2628          "Total samples in two profile should be greater than 0");
2629   double OverlapPercent =
2630       static_cast<double>(ProfOverlap.OverlapSample) / ProfOverlap.UnionSample;
2631   assert(ProfOverlap.BaseSample > 0 &&
2632          "Total samples in base profile should be greater than 0");
2633   double BaseUniquePercent = static_cast<double>(ProfOverlap.BaseUniqueSample) /
2634                              ProfOverlap.BaseSample;
2635   assert(ProfOverlap.TestSample > 0 &&
2636          "Total samples in test profile should be greater than 0");
2637   double TestUniquePercent = static_cast<double>(ProfOverlap.TestUniqueSample) /
2638                              ProfOverlap.TestSample;
2639 
2640   OS << "  Whole program sample overlap: "
2641      << format("%.3f%%", OverlapPercent * 100) << "\n";
2642   OS << "    percentage of samples unique in base profile: "
2643      << format("%.3f%%", BaseUniquePercent * 100) << "\n";
2644   OS << "    percentage of samples unique in test profile: "
2645      << format("%.3f%%", TestUniquePercent * 100) << "\n";
2646   OS << "    total samples in base profile: " << ProfOverlap.BaseSample << "\n"
2647      << "    total samples in test profile: " << ProfOverlap.TestSample << "\n";
2648 
2649   assert(ProfOverlap.UnionCount > 0 &&
2650          "There should be at least one function in two input profiles");
2651   double FuncOverlapPercent =
2652       static_cast<double>(ProfOverlap.OverlapCount) / ProfOverlap.UnionCount;
2653   OS << "  Function overlap: " << format("%.3f%%", FuncOverlapPercent * 100)
2654      << "\n";
2655   OS << "    overlap functions: " << ProfOverlap.OverlapCount << "\n";
2656   OS << "    functions unique in base profile: " << ProfOverlap.BaseUniqueCount
2657      << "\n";
2658   OS << "    functions unique in test profile: " << ProfOverlap.TestUniqueCount
2659      << "\n";
2660 }
2661 
2662 void SampleOverlapAggregator::dumpHotFuncAndBlockOverlap(
2663     raw_fd_ostream &OS) const {
2664   assert(HotFuncOverlap.UnionCount > 0 &&
2665          "There should be at least one hot function in two input profiles");
2666   OS << "  Hot-function overlap: "
2667      << format("%.3f%%", static_cast<double>(HotFuncOverlap.OverlapCount) /
2668                              HotFuncOverlap.UnionCount * 100)
2669      << "\n";
2670   OS << "    overlap hot functions: " << HotFuncOverlap.OverlapCount << "\n";
2671   OS << "    hot functions unique in base profile: "
2672      << HotFuncOverlap.BaseCount - HotFuncOverlap.OverlapCount << "\n";
2673   OS << "    hot functions unique in test profile: "
2674      << HotFuncOverlap.TestCount - HotFuncOverlap.OverlapCount << "\n";
2675 
2676   assert(HotBlockOverlap.UnionCount > 0 &&
2677          "There should be at least one hot block in two input profiles");
2678   OS << "  Hot-block overlap: "
2679      << format("%.3f%%", static_cast<double>(HotBlockOverlap.OverlapCount) /
2680                              HotBlockOverlap.UnionCount * 100)
2681      << "\n";
2682   OS << "    overlap hot blocks: " << HotBlockOverlap.OverlapCount << "\n";
2683   OS << "    hot blocks unique in base profile: "
2684      << HotBlockOverlap.BaseCount - HotBlockOverlap.OverlapCount << "\n";
2685   OS << "    hot blocks unique in test profile: "
2686      << HotBlockOverlap.TestCount - HotBlockOverlap.OverlapCount << "\n";
2687 }
2688 
2689 std::error_code SampleOverlapAggregator::loadProfiles() {
2690   using namespace sampleprof;
2691 
2692   LLVMContext Context;
2693   auto FS = vfs::getRealFileSystem();
2694   auto BaseReaderOrErr = SampleProfileReader::create(BaseFilename, Context, *FS,
2695                                                      FSDiscriminatorPassOption);
2696   if (std::error_code EC = BaseReaderOrErr.getError())
2697     exitWithErrorCode(EC, BaseFilename);
2698 
2699   auto TestReaderOrErr = SampleProfileReader::create(TestFilename, Context, *FS,
2700                                                      FSDiscriminatorPassOption);
2701   if (std::error_code EC = TestReaderOrErr.getError())
2702     exitWithErrorCode(EC, TestFilename);
2703 
2704   BaseReader = std::move(BaseReaderOrErr.get());
2705   TestReader = std::move(TestReaderOrErr.get());
2706 
2707   if (std::error_code EC = BaseReader->read())
2708     exitWithErrorCode(EC, BaseFilename);
2709   if (std::error_code EC = TestReader->read())
2710     exitWithErrorCode(EC, TestFilename);
2711   if (BaseReader->profileIsProbeBased() != TestReader->profileIsProbeBased())
2712     exitWithError(
2713         "cannot compare probe-based profile with non-probe-based profile");
2714   if (BaseReader->profileIsCS() != TestReader->profileIsCS())
2715     exitWithError("cannot compare CS profile with non-CS profile");
2716 
2717   // Load BaseHotThreshold and TestHotThreshold as 99-percentile threshold in
2718   // profile summary.
2719   ProfileSummary &BasePS = BaseReader->getSummary();
2720   ProfileSummary &TestPS = TestReader->getSummary();
2721   BaseHotThreshold =
2722       ProfileSummaryBuilder::getHotCountThreshold(BasePS.getDetailedSummary());
2723   TestHotThreshold =
2724       ProfileSummaryBuilder::getHotCountThreshold(TestPS.getDetailedSummary());
2725 
2726   return std::error_code();
2727 }
2728 
2729 void overlapSampleProfile(const std::string &BaseFilename,
2730                           const std::string &TestFilename,
2731                           const OverlapFuncFilters &FuncFilter,
2732                           uint64_t SimilarityCutoff, raw_fd_ostream &OS) {
2733   using namespace sampleprof;
2734 
2735   // We use 0.000005 to initialize OverlapAggr.Epsilon because the final metrics
2736   // report 2--3 places after decimal point in percentage numbers.
2737   SampleOverlapAggregator OverlapAggr(
2738       BaseFilename, TestFilename,
2739       static_cast<double>(SimilarityCutoff) / 1000000, 0.000005, FuncFilter);
2740   if (std::error_code EC = OverlapAggr.loadProfiles())
2741     exitWithErrorCode(EC);
2742 
2743   OverlapAggr.initializeSampleProfileOverlap();
2744   if (OverlapAggr.detectZeroSampleProfile(OS))
2745     return;
2746 
2747   OverlapAggr.computeSampleProfileOverlap(OS);
2748 
2749   OverlapAggr.dumpProgramSummary(OS);
2750   OverlapAggr.dumpHotFuncAndBlockOverlap(OS);
2751   OverlapAggr.dumpFuncSimilarity(OS);
2752 }
2753 
2754 static int overlap_main() {
2755   std::error_code EC;
2756   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF);
2757   if (EC)
2758     exitWithErrorCode(EC, OutputFilename);
2759 
2760   if (ProfileKind == instr)
2761     overlapInstrProfile(BaseFilename, TestFilename,
2762                         OverlapFuncFilters{OverlapValueCutoff, FuncNameFilter},
2763                         OS, IsCS);
2764   else
2765     overlapSampleProfile(BaseFilename, TestFilename,
2766                          OverlapFuncFilters{OverlapValueCutoff, FuncNameFilter},
2767                          SimilarityCutoff, OS);
2768 
2769   return 0;
2770 }
2771 
2772 namespace {
2773 struct ValueSitesStats {
2774   ValueSitesStats() = default;
2775   uint64_t TotalNumValueSites = 0;
2776   uint64_t TotalNumValueSitesWithValueProfile = 0;
2777   uint64_t TotalNumValues = 0;
2778   std::vector<unsigned> ValueSitesHistogram;
2779 };
2780 } // namespace
2781 
2782 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
2783                                   ValueSitesStats &Stats, raw_fd_ostream &OS,
2784                                   InstrProfSymtab *Symtab) {
2785   uint32_t NS = Func.getNumValueSites(VK);
2786   Stats.TotalNumValueSites += NS;
2787   for (size_t I = 0; I < NS; ++I) {
2788     auto VD = Func.getValueArrayForSite(VK, I);
2789     uint32_t NV = VD.size();
2790     if (NV == 0)
2791       continue;
2792     Stats.TotalNumValues += NV;
2793     Stats.TotalNumValueSitesWithValueProfile++;
2794     if (NV > Stats.ValueSitesHistogram.size())
2795       Stats.ValueSitesHistogram.resize(NV, 0);
2796     Stats.ValueSitesHistogram[NV - 1]++;
2797 
2798     uint64_t SiteSum = 0;
2799     for (const auto &V : VD)
2800       SiteSum += V.Count;
2801     if (SiteSum == 0)
2802       SiteSum = 1;
2803 
2804     for (const auto &V : VD) {
2805       OS << "\t[ " << format("%2u", I) << ", ";
2806       if (Symtab == nullptr)
2807         OS << format("%4" PRIu64, V.Value);
2808       else
2809         OS << Symtab->getFuncOrVarName(V.Value);
2810       OS << ", " << format("%10" PRId64, V.Count) << " ] ("
2811          << format("%.2f%%", (V.Count * 100.0 / SiteSum)) << ")\n";
2812     }
2813   }
2814 }
2815 
2816 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
2817                                 ValueSitesStats &Stats) {
2818   OS << "  Total number of sites: " << Stats.TotalNumValueSites << "\n";
2819   OS << "  Total number of sites with values: "
2820      << Stats.TotalNumValueSitesWithValueProfile << "\n";
2821   OS << "  Total number of profiled values: " << Stats.TotalNumValues << "\n";
2822 
2823   OS << "  Value sites histogram:\n\tNumTargets, SiteCount\n";
2824   for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
2825     if (Stats.ValueSitesHistogram[I] > 0)
2826       OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
2827   }
2828 }
2829 
2830 static int showInstrProfile(ShowFormat SFormat, raw_fd_ostream &OS) {
2831   if (SFormat == ShowFormat::Json)
2832     exitWithError("JSON output is not supported for instr profiles");
2833   if (SFormat == ShowFormat::Yaml)
2834     exitWithError("YAML output is not supported for instr profiles");
2835   auto FS = vfs::getRealFileSystem();
2836   auto ReaderOrErr = InstrProfReader::create(Filename, *FS);
2837   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
2838   if (ShowDetailedSummary && Cutoffs.empty()) {
2839     Cutoffs = ProfileSummaryBuilder::DefaultCutoffs;
2840   }
2841   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
2842   if (Error E = ReaderOrErr.takeError())
2843     exitWithError(std::move(E), Filename);
2844 
2845   auto Reader = std::move(ReaderOrErr.get());
2846   bool IsIRInstr = Reader->isIRLevelProfile();
2847   size_t ShownFunctions = 0;
2848   size_t BelowCutoffFunctions = 0;
2849   int NumVPKind = IPVK_Last - IPVK_First + 1;
2850   std::vector<ValueSitesStats> VPStats(NumVPKind);
2851 
2852   auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
2853                    const std::pair<std::string, uint64_t> &v2) {
2854     return v1.second > v2.second;
2855   };
2856 
2857   std::priority_queue<std::pair<std::string, uint64_t>,
2858                       std::vector<std::pair<std::string, uint64_t>>,
2859                       decltype(MinCmp)>
2860       HottestFuncs(MinCmp);
2861 
2862   if (!TextFormat && OnlyListBelow) {
2863     OS << "The list of functions with the maximum counter less than "
2864        << ShowValueCutoff << ":\n";
2865   }
2866 
2867   // Add marker so that IR-level instrumentation round-trips properly.
2868   if (TextFormat && IsIRInstr)
2869     OS << ":ir\n";
2870 
2871   for (const auto &Func : *Reader) {
2872     if (Reader->isIRLevelProfile()) {
2873       bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
2874       if (FuncIsCS != ShowCS)
2875         continue;
2876     }
2877     bool Show = ShowAllFunctions ||
2878                 (!FuncNameFilter.empty() && Func.Name.contains(FuncNameFilter));
2879 
2880     bool doTextFormatDump = (Show && TextFormat);
2881 
2882     if (doTextFormatDump) {
2883       InstrProfSymtab &Symtab = Reader->getSymtab();
2884       InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
2885                                          OS);
2886       continue;
2887     }
2888 
2889     assert(Func.Counts.size() > 0 && "function missing entry counter");
2890     Builder.addRecord(Func);
2891 
2892     if (ShowCovered) {
2893       if (llvm::any_of(Func.Counts, [](uint64_t C) { return C; }))
2894         OS << Func.Name << "\n";
2895       continue;
2896     }
2897 
2898     uint64_t FuncMax = 0;
2899     uint64_t FuncSum = 0;
2900 
2901     auto PseudoKind = Func.getCountPseudoKind();
2902     if (PseudoKind != InstrProfRecord::NotPseudo) {
2903       if (Show) {
2904         if (!ShownFunctions)
2905           OS << "Counters:\n";
2906         ++ShownFunctions;
2907         OS << "  " << Func.Name << ":\n"
2908            << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
2909            << "    Counters: " << Func.Counts.size();
2910         if (PseudoKind == InstrProfRecord::PseudoHot)
2911           OS << "    <PseudoHot>\n";
2912         else if (PseudoKind == InstrProfRecord::PseudoWarm)
2913           OS << "    <PseudoWarm>\n";
2914         else
2915           llvm_unreachable("Unknown PseudoKind");
2916       }
2917       continue;
2918     }
2919 
2920     for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
2921       FuncMax = std::max(FuncMax, Func.Counts[I]);
2922       FuncSum += Func.Counts[I];
2923     }
2924 
2925     if (FuncMax < ShowValueCutoff) {
2926       ++BelowCutoffFunctions;
2927       if (OnlyListBelow) {
2928         OS << "  " << Func.Name << ": (Max = " << FuncMax
2929            << " Sum = " << FuncSum << ")\n";
2930       }
2931       continue;
2932     } else if (OnlyListBelow)
2933       continue;
2934 
2935     if (TopNFunctions) {
2936       if (HottestFuncs.size() == TopNFunctions) {
2937         if (HottestFuncs.top().second < FuncMax) {
2938           HottestFuncs.pop();
2939           HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
2940         }
2941       } else
2942         HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
2943     }
2944 
2945     if (Show) {
2946       if (!ShownFunctions)
2947         OS << "Counters:\n";
2948 
2949       ++ShownFunctions;
2950 
2951       OS << "  " << Func.Name << ":\n"
2952          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
2953          << "    Counters: " << Func.Counts.size() << "\n";
2954       if (!IsIRInstr)
2955         OS << "    Function count: " << Func.Counts[0] << "\n";
2956 
2957       if (ShowIndirectCallTargets)
2958         OS << "    Indirect Call Site Count: "
2959            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
2960 
2961       if (ShowVTables)
2962         OS << "    Number of instrumented vtables: "
2963            << Func.getNumValueSites(IPVK_VTableTarget) << "\n";
2964 
2965       uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
2966       if (ShowMemOPSizes && NumMemOPCalls > 0)
2967         OS << "    Number of Memory Intrinsics Calls: " << NumMemOPCalls
2968            << "\n";
2969 
2970       if (ShowCounts) {
2971         OS << "    Block counts: [";
2972         size_t Start = (IsIRInstr ? 0 : 1);
2973         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
2974           OS << (I == Start ? "" : ", ") << Func.Counts[I];
2975         }
2976         OS << "]\n";
2977       }
2978 
2979       if (ShowIndirectCallTargets) {
2980         OS << "    Indirect Target Results:\n";
2981         traverseAllValueSites(Func, IPVK_IndirectCallTarget,
2982                               VPStats[IPVK_IndirectCallTarget], OS,
2983                               &(Reader->getSymtab()));
2984       }
2985 
2986       if (ShowVTables) {
2987         OS << "    VTable Results:\n";
2988         traverseAllValueSites(Func, IPVK_VTableTarget,
2989                               VPStats[IPVK_VTableTarget], OS,
2990                               &(Reader->getSymtab()));
2991       }
2992 
2993       if (ShowMemOPSizes && NumMemOPCalls > 0) {
2994         OS << "    Memory Intrinsic Size Results:\n";
2995         traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
2996                               nullptr);
2997       }
2998     }
2999   }
3000   if (Reader->hasError())
3001     exitWithError(Reader->getError(), Filename);
3002 
3003   if (TextFormat || ShowCovered)
3004     return 0;
3005   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
3006   bool IsIR = Reader->isIRLevelProfile();
3007   OS << "Instrumentation level: " << (IsIR ? "IR" : "Front-end");
3008   if (IsIR) {
3009     OS << "  entry_first = " << Reader->instrEntryBBEnabled();
3010     OS << "  instrument_loop_entries = " << Reader->instrLoopEntriesEnabled();
3011   }
3012   OS << "\n";
3013   if (ShowAllFunctions || !FuncNameFilter.empty())
3014     OS << "Functions shown: " << ShownFunctions << "\n";
3015   PS->printSummary(OS);
3016   if (ShowValueCutoff > 0) {
3017     OS << "Number of functions with maximum count (< " << ShowValueCutoff
3018        << "): " << BelowCutoffFunctions << "\n";
3019     OS << "Number of functions with maximum count (>= " << ShowValueCutoff
3020        << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
3021   }
3022 
3023   if (TopNFunctions) {
3024     std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
3025     while (!HottestFuncs.empty()) {
3026       SortedHottestFuncs.emplace_back(HottestFuncs.top());
3027       HottestFuncs.pop();
3028     }
3029     OS << "Top " << TopNFunctions
3030        << " functions with the largest internal block counts: \n";
3031     for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
3032       OS << "  " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
3033   }
3034 
3035   if (ShownFunctions && ShowIndirectCallTargets) {
3036     OS << "Statistics for indirect call sites profile:\n";
3037     showValueSitesStats(OS, IPVK_IndirectCallTarget,
3038                         VPStats[IPVK_IndirectCallTarget]);
3039   }
3040 
3041   if (ShownFunctions && ShowVTables) {
3042     OS << "Statistics for vtable profile:\n";
3043     showValueSitesStats(OS, IPVK_VTableTarget, VPStats[IPVK_VTableTarget]);
3044   }
3045 
3046   if (ShownFunctions && ShowMemOPSizes) {
3047     OS << "Statistics for memory intrinsic calls sizes profile:\n";
3048     showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
3049   }
3050 
3051   if (ShowDetailedSummary)
3052     PS->printDetailedSummary(OS);
3053 
3054   if (ShowBinaryIds)
3055     if (Error E = Reader->printBinaryIds(OS))
3056       exitWithError(std::move(E), Filename);
3057 
3058   if (ShowProfileVersion)
3059     OS << "Profile version: " << Reader->getVersion() << "\n";
3060 
3061   if (ShowTemporalProfTraces) {
3062     auto &Traces = Reader->getTemporalProfTraces();
3063     OS << "Temporal Profile Traces (samples=" << Traces.size()
3064        << " seen=" << Reader->getTemporalProfTraceStreamSize() << "):\n";
3065     for (unsigned i = 0; i < Traces.size(); i++) {
3066       OS << "  Temporal Profile Trace " << i << " (weight=" << Traces[i].Weight
3067          << " count=" << Traces[i].FunctionNameRefs.size() << "):\n";
3068       for (auto &NameRef : Traces[i].FunctionNameRefs)
3069         OS << "    " << Reader->getSymtab().getFuncOrVarName(NameRef) << "\n";
3070     }
3071   }
3072 
3073   return 0;
3074 }
3075 
3076 static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
3077                             raw_fd_ostream &OS) {
3078   if (!Reader->dumpSectionInfo(OS)) {
3079     WithColor::warning() << "-show-sec-info-only is only supported for "
3080                          << "sample profile in extbinary format and is "
3081                          << "ignored for other formats.\n";
3082     return;
3083   }
3084 }
3085 
3086 namespace {
3087 struct HotFuncInfo {
3088   std::string FuncName;
3089   uint64_t TotalCount = 0;
3090   double TotalCountPercent = 0.0f;
3091   uint64_t MaxCount = 0;
3092   uint64_t EntryCount = 0;
3093 
3094   HotFuncInfo() = default;
3095 
3096   HotFuncInfo(StringRef FN, uint64_t TS, double TSP, uint64_t MS, uint64_t ES)
3097       : FuncName(FN.begin(), FN.end()), TotalCount(TS), TotalCountPercent(TSP),
3098         MaxCount(MS), EntryCount(ES) {}
3099 };
3100 } // namespace
3101 
3102 // Print out detailed information about hot functions in PrintValues vector.
3103 // Users specify titles and offset of every columns through ColumnTitle and
3104 // ColumnOffset. The size of ColumnTitle and ColumnOffset need to be the same
3105 // and at least 4. Besides, users can optionally give a HotFuncMetric string to
3106 // print out or let it be an empty string.
3107 static void dumpHotFunctionList(const std::vector<std::string> &ColumnTitle,
3108                                 const std::vector<int> &ColumnOffset,
3109                                 const std::vector<HotFuncInfo> &PrintValues,
3110                                 uint64_t HotFuncCount, uint64_t TotalFuncCount,
3111                                 uint64_t HotProfCount, uint64_t TotalProfCount,
3112                                 const std::string &HotFuncMetric,
3113                                 uint32_t TopNFunctions, raw_fd_ostream &OS) {
3114   assert(ColumnOffset.size() == ColumnTitle.size() &&
3115          "ColumnOffset and ColumnTitle should have the same size");
3116   assert(ColumnTitle.size() >= 4 &&
3117          "ColumnTitle should have at least 4 elements");
3118   assert(TotalFuncCount > 0 &&
3119          "There should be at least one function in the profile");
3120   double TotalProfPercent = 0;
3121   if (TotalProfCount > 0)
3122     TotalProfPercent = static_cast<double>(HotProfCount) / TotalProfCount * 100;
3123 
3124   formatted_raw_ostream FOS(OS);
3125   FOS << HotFuncCount << " out of " << TotalFuncCount
3126       << " functions with profile ("
3127       << format("%.2f%%",
3128                 (static_cast<double>(HotFuncCount) / TotalFuncCount * 100))
3129       << ") are considered hot functions";
3130   if (!HotFuncMetric.empty())
3131     FOS << " (" << HotFuncMetric << ")";
3132   FOS << ".\n";
3133   FOS << HotProfCount << " out of " << TotalProfCount << " profile counts ("
3134       << format("%.2f%%", TotalProfPercent) << ") are from hot functions.\n";
3135 
3136   for (size_t I = 0; I < ColumnTitle.size(); ++I) {
3137     FOS.PadToColumn(ColumnOffset[I]);
3138     FOS << ColumnTitle[I];
3139   }
3140   FOS << "\n";
3141 
3142   uint32_t Count = 0;
3143   for (const auto &R : PrintValues) {
3144     if (TopNFunctions && (Count++ == TopNFunctions))
3145       break;
3146     FOS.PadToColumn(ColumnOffset[0]);
3147     FOS << R.TotalCount << " (" << format("%.2f%%", R.TotalCountPercent) << ")";
3148     FOS.PadToColumn(ColumnOffset[1]);
3149     FOS << R.MaxCount;
3150     FOS.PadToColumn(ColumnOffset[2]);
3151     FOS << R.EntryCount;
3152     FOS.PadToColumn(ColumnOffset[3]);
3153     FOS << R.FuncName << "\n";
3154   }
3155 }
3156 
3157 static int showHotFunctionList(const sampleprof::SampleProfileMap &Profiles,
3158                                ProfileSummary &PS, uint32_t TopN,
3159                                raw_fd_ostream &OS) {
3160   using namespace sampleprof;
3161 
3162   const uint32_t HotFuncCutoff = 990000;
3163   auto &SummaryVector = PS.getDetailedSummary();
3164   uint64_t MinCountThreshold = 0;
3165   for (const ProfileSummaryEntry &SummaryEntry : SummaryVector) {
3166     if (SummaryEntry.Cutoff == HotFuncCutoff) {
3167       MinCountThreshold = SummaryEntry.MinCount;
3168       break;
3169     }
3170   }
3171 
3172   // Traverse all functions in the profile and keep only hot functions.
3173   // The following loop also calculates the sum of total samples of all
3174   // functions.
3175   std::multimap<uint64_t, std::pair<const FunctionSamples *, const uint64_t>,
3176                 std::greater<uint64_t>>
3177       HotFunc;
3178   uint64_t ProfileTotalSample = 0;
3179   uint64_t HotFuncSample = 0;
3180   uint64_t HotFuncCount = 0;
3181 
3182   for (const auto &I : Profiles) {
3183     FuncSampleStats FuncStats;
3184     const FunctionSamples &FuncProf = I.second;
3185     ProfileTotalSample += FuncProf.getTotalSamples();
3186     getFuncSampleStats(FuncProf, FuncStats, MinCountThreshold);
3187 
3188     if (isFunctionHot(FuncStats, MinCountThreshold)) {
3189       HotFunc.emplace(FuncProf.getTotalSamples(),
3190                       std::make_pair(&(I.second), FuncStats.MaxSample));
3191       HotFuncSample += FuncProf.getTotalSamples();
3192       ++HotFuncCount;
3193     }
3194   }
3195 
3196   std::vector<std::string> ColumnTitle{"Total sample (%)", "Max sample",
3197                                        "Entry sample", "Function name"};
3198   std::vector<int> ColumnOffset{0, 24, 42, 58};
3199   std::string Metric =
3200       std::string("max sample >= ") + std::to_string(MinCountThreshold);
3201   std::vector<HotFuncInfo> PrintValues;
3202   for (const auto &FuncPair : HotFunc) {
3203     const FunctionSamples &Func = *FuncPair.second.first;
3204     double TotalSamplePercent =
3205         (ProfileTotalSample > 0)
3206             ? (Func.getTotalSamples() * 100.0) / ProfileTotalSample
3207             : 0;
3208     PrintValues.emplace_back(
3209         HotFuncInfo(Func.getContext().toString(), Func.getTotalSamples(),
3210                     TotalSamplePercent, FuncPair.second.second,
3211                     Func.getHeadSamplesEstimate()));
3212   }
3213   dumpHotFunctionList(ColumnTitle, ColumnOffset, PrintValues, HotFuncCount,
3214                       Profiles.size(), HotFuncSample, ProfileTotalSample,
3215                       Metric, TopN, OS);
3216 
3217   return 0;
3218 }
3219 
3220 static int showSampleProfile(ShowFormat SFormat, raw_fd_ostream &OS) {
3221   if (SFormat == ShowFormat::Yaml)
3222     exitWithError("YAML output is not supported for sample profiles");
3223   using namespace sampleprof;
3224   LLVMContext Context;
3225   auto FS = vfs::getRealFileSystem();
3226   auto ReaderOrErr = SampleProfileReader::create(Filename, Context, *FS,
3227                                                  FSDiscriminatorPassOption);
3228   if (std::error_code EC = ReaderOrErr.getError())
3229     exitWithErrorCode(EC, Filename);
3230 
3231   auto Reader = std::move(ReaderOrErr.get());
3232   if (ShowSectionInfoOnly) {
3233     showSectionInfo(Reader.get(), OS);
3234     return 0;
3235   }
3236 
3237   if (std::error_code EC = Reader->read())
3238     exitWithErrorCode(EC, Filename);
3239 
3240   if (ShowAllFunctions || FuncNameFilter.empty()) {
3241     if (SFormat == ShowFormat::Json)
3242       Reader->dumpJson(OS);
3243     else
3244       Reader->dump(OS);
3245   } else {
3246     if (SFormat == ShowFormat::Json)
3247       exitWithError(
3248           "the JSON format is supported only when all functions are to "
3249           "be printed");
3250 
3251     // TODO: parse context string to support filtering by contexts.
3252     FunctionSamples *FS = Reader->getSamplesFor(StringRef(FuncNameFilter));
3253     Reader->dumpFunctionProfile(FS ? *FS : FunctionSamples(), OS);
3254   }
3255 
3256   if (ShowProfileSymbolList) {
3257     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
3258         Reader->getProfileSymbolList();
3259     ReaderList->dump(OS);
3260   }
3261 
3262   if (ShowDetailedSummary) {
3263     auto &PS = Reader->getSummary();
3264     PS.printSummary(OS);
3265     PS.printDetailedSummary(OS);
3266   }
3267 
3268   if (ShowHotFuncList || TopNFunctions)
3269     showHotFunctionList(Reader->getProfiles(), Reader->getSummary(),
3270                         TopNFunctions, OS);
3271 
3272   return 0;
3273 }
3274 
3275 static int showMemProfProfile(ShowFormat SFormat, raw_fd_ostream &OS) {
3276   if (SFormat == ShowFormat::Json)
3277     exitWithError("JSON output is not supported for MemProf");
3278 
3279   // Show the raw profile in YAML.
3280   if (memprof::RawMemProfReader::hasFormat(Filename)) {
3281     auto ReaderOr = llvm::memprof::RawMemProfReader::create(
3282         Filename, ProfiledBinary, /*KeepNames=*/true);
3283     if (Error E = ReaderOr.takeError()) {
3284       // Since the error can be related to the profile or the binary we do not
3285       // pass whence. Instead additional context is provided where necessary in
3286       // the error message.
3287       exitWithError(std::move(E), /*Whence*/ "");
3288     }
3289 
3290     std::unique_ptr<llvm::memprof::RawMemProfReader> Reader(
3291         ReaderOr.get().release());
3292 
3293     Reader->printYAML(OS);
3294     return 0;
3295   }
3296 
3297   // Show the indexed MemProf profile in YAML.
3298   auto FS = vfs::getRealFileSystem();
3299   auto ReaderOrErr = IndexedInstrProfReader::create(Filename, *FS);
3300   if (Error E = ReaderOrErr.takeError())
3301     exitWithError(std::move(E), Filename);
3302 
3303   auto Reader = std::move(ReaderOrErr.get());
3304   memprof::AllMemProfData Data = Reader->getAllMemProfData();
3305   // Construct yaml::Output with the maximum column width of 80 so that each
3306   // Frame fits in one line.
3307   yaml::Output Yout(OS, nullptr, 80);
3308   Yout << Data;
3309 
3310   return 0;
3311 }
3312 
3313 static int showDebugInfoCorrelation(const std::string &Filename,
3314                                     ShowFormat SFormat, raw_fd_ostream &OS) {
3315   if (SFormat == ShowFormat::Json)
3316     exitWithError("JSON output is not supported for debug info correlation");
3317   std::unique_ptr<InstrProfCorrelator> Correlator;
3318   if (auto Err =
3319           InstrProfCorrelator::get(Filename, InstrProfCorrelator::DEBUG_INFO)
3320               .moveInto(Correlator))
3321     exitWithError(std::move(Err), Filename);
3322   if (SFormat == ShowFormat::Yaml) {
3323     if (auto Err = Correlator->dumpYaml(MaxDbgCorrelationWarnings, OS))
3324       exitWithError(std::move(Err), Filename);
3325     return 0;
3326   }
3327 
3328   if (auto Err = Correlator->correlateProfileData(MaxDbgCorrelationWarnings))
3329     exitWithError(std::move(Err), Filename);
3330 
3331   InstrProfSymtab Symtab;
3332   if (auto Err = Symtab.create(
3333           StringRef(Correlator->getNamesPointer(), Correlator->getNamesSize())))
3334     exitWithError(std::move(Err), Filename);
3335 
3336   if (ShowProfileSymbolList)
3337     Symtab.dumpNames(OS);
3338   // TODO: Read "Profile Data Type" from debug info to compute and show how many
3339   // counters the section holds.
3340   if (ShowDetailedSummary)
3341     OS << "Counters section size: 0x"
3342        << Twine::utohexstr(Correlator->getCountersSectionSize()) << " bytes\n";
3343   OS << "Found " << Correlator->getDataSize() << " functions\n";
3344 
3345   return 0;
3346 }
3347 
3348 static int show_main(StringRef ProgName) {
3349   if (Filename.empty() && DebugInfoFilename.empty())
3350     exitWithError(
3351         "the positional argument '<profdata-file>' is required unless '--" +
3352         DebugInfoFilename.ArgStr + "' is provided");
3353 
3354   if (Filename == OutputFilename) {
3355     errs() << ProgName
3356            << " show: Input file name cannot be the same as the output file "
3357               "name!\n";
3358     return 1;
3359   }
3360   if (JsonFormat)
3361     SFormat = ShowFormat::Json;
3362 
3363   std::error_code EC;
3364   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF);
3365   if (EC)
3366     exitWithErrorCode(EC, OutputFilename);
3367 
3368   if (ShowAllFunctions && !FuncNameFilter.empty())
3369     WithColor::warning() << "-function argument ignored: showing all functions\n";
3370 
3371   if (!DebugInfoFilename.empty())
3372     return showDebugInfoCorrelation(DebugInfoFilename, SFormat, OS);
3373 
3374   if (ShowProfileKind == instr)
3375     return showInstrProfile(SFormat, OS);
3376   if (ShowProfileKind == sample)
3377     return showSampleProfile(SFormat, OS);
3378   return showMemProfProfile(SFormat, OS);
3379 }
3380 
3381 static int order_main() {
3382   std::error_code EC;
3383   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF);
3384   if (EC)
3385     exitWithErrorCode(EC, OutputFilename);
3386   auto FS = vfs::getRealFileSystem();
3387   auto ReaderOrErr = InstrProfReader::create(Filename, *FS);
3388   if (Error E = ReaderOrErr.takeError())
3389     exitWithError(std::move(E), Filename);
3390 
3391   auto Reader = std::move(ReaderOrErr.get());
3392   for (auto &I : *Reader) {
3393     // Read all entries
3394     (void)I;
3395   }
3396   ArrayRef Traces = Reader->getTemporalProfTraces();
3397   if (NumTestTraces && NumTestTraces >= Traces.size())
3398     exitWithError(
3399         "--" + NumTestTraces.ArgStr +
3400         " must be smaller than the total number of traces: expected: < " +
3401         Twine(Traces.size()) + ", actual: " + Twine(NumTestTraces));
3402   ArrayRef TestTraces = Traces.take_back(NumTestTraces);
3403   Traces = Traces.drop_back(NumTestTraces);
3404 
3405   std::vector<BPFunctionNode> Nodes;
3406   TemporalProfTraceTy::createBPFunctionNodes(Traces, Nodes);
3407   BalancedPartitioningConfig Config;
3408   BalancedPartitioning BP(Config);
3409   BP.run(Nodes);
3410 
3411   OS << "# Ordered " << Nodes.size() << " functions\n";
3412   if (!TestTraces.empty()) {
3413     // Since we don't know the symbol sizes, we assume 32 functions per page.
3414     DenseMap<BPFunctionNode::IDT, unsigned> IdToPageNumber;
3415     for (auto &Node : Nodes)
3416       IdToPageNumber[Node.Id] = IdToPageNumber.size() / 32;
3417 
3418     SmallSet<unsigned, 0> TouchedPages;
3419     unsigned Area = 0;
3420     for (auto &Trace : TestTraces) {
3421       for (auto Id : Trace.FunctionNameRefs) {
3422         auto It = IdToPageNumber.find(Id);
3423         if (It == IdToPageNumber.end())
3424           continue;
3425         TouchedPages.insert(It->getSecond());
3426         Area += TouchedPages.size();
3427       }
3428       TouchedPages.clear();
3429     }
3430     OS << "# Total area under the page fault curve: " << (float)Area << "\n";
3431   }
3432   OS << "# Warning: Mach-O may prefix symbols with \"_\" depending on the "
3433         "linkage and this output does not take that into account. Some "
3434         "post-processing may be required before passing to the linker via "
3435         "-order_file.\n";
3436   for (auto &N : Nodes) {
3437     auto [Filename, ParsedFuncName] =
3438         getParsedIRPGOName(Reader->getSymtab().getFuncOrVarName(N.Id));
3439     if (!Filename.empty())
3440       OS << "# " << Filename << "\n";
3441     OS << ParsedFuncName << "\n";
3442   }
3443   return 0;
3444 }
3445 
3446 int llvm_profdata_main(int argc, char **argvNonConst,
3447                        const llvm::ToolContext &) {
3448   const char **argv = const_cast<const char **>(argvNonConst);
3449 
3450   StringRef ProgName(sys::path::filename(argv[0]));
3451 
3452   if (argc < 2) {
3453     errs()
3454         << ProgName
3455         << ": No subcommand specified! Run llvm-profdata --help for usage.\n";
3456     return 1;
3457   }
3458 
3459   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data\n");
3460 
3461   if (ShowSubcommand)
3462     return show_main(ProgName);
3463 
3464   if (OrderSubcommand)
3465     return order_main();
3466 
3467   if (OverlapSubcommand)
3468     return overlap_main();
3469 
3470   if (MergeSubcommand)
3471     return merge_main(ProgName);
3472 
3473   errs() << ProgName
3474          << ": Unknown command. Run llvm-profdata --help for usage.\n";
3475   return 1;
3476 }
3477