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