1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // llvm-profdata merges .profdata files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/SmallSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/ProfileData/InstrProfReader.h"
19 #include "llvm/ProfileData/InstrProfWriter.h"
20 #include "llvm/ProfileData/ProfileCommon.h"
21 #include "llvm/ProfileData/SampleProfReader.h"
22 #include "llvm/ProfileData/SampleProfWriter.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Errc.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/Signals.h"
32 #include "llvm/Support/ThreadPool.h"
33 #include "llvm/Support/raw_ostream.h"
38 enum ProfileFormat { PF_None = 0, PF_Text, PF_Binary, PF_GCC };
40 static void exitWithError(const Twine &Message, StringRef Whence = "",
41 StringRef Hint = "") {
44 errs() << Whence << ": ";
45 errs() << Message << "\n";
47 errs() << Hint << "\n";
51 static void exitWithError(Error E, StringRef Whence = "") {
52 if (E.isA<InstrProfError>()) {
53 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
54 instrprof_error instrError = IPE.get();
56 if (instrError == instrprof_error::unrecognized_format) {
57 // Hint for common error of forgetting -sample for sample profiles.
58 Hint = "Perhaps you forgot to use the -sample option?";
60 exitWithError(IPE.message(), Whence, Hint);
64 exitWithError(toString(std::move(E)), Whence);
67 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
68 exitWithError(EC.message(), Whence);
72 enum ProfileKinds { instr, sample };
75 static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
76 StringRef WhenceFunction = "",
77 bool ShowHint = true) {
78 if (!WhenceFile.empty())
79 errs() << WhenceFile << ": ";
80 if (!WhenceFunction.empty())
81 errs() << WhenceFunction << ": ";
83 auto IPE = instrprof_error::success;
84 E = handleErrors(std::move(E),
85 [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
87 return Error(std::move(E));
89 errs() << toString(std::move(E)) << "\n";
93 if (IPE != instrprof_error::success) {
95 case instrprof_error::hash_mismatch:
96 case instrprof_error::count_mismatch:
97 case instrprof_error::value_site_count_mismatch:
98 Hint = "Make sure that all profile data to be merged is generated "
99 "from the same binary.";
107 errs() << Hint << "\n";
111 struct WeightedFile {
112 std::string Filename;
115 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
117 /// Keep track of merged data and reported errors.
118 struct WriterContext {
120 InstrProfWriter Writer;
124 SmallSet<instrprof_error, 4> &WriterErrorCodes;
126 WriterContext(bool IsSparse, std::mutex &ErrLock,
127 SmallSet<instrprof_error, 4> &WriterErrorCodes)
128 : Lock(), Writer(IsSparse), Err(Error::success()), ErrWhence(""),
129 ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {}
132 /// Load an input into a writer context.
133 static void loadInput(const WeightedFile &Input, WriterContext *WC) {
134 std::unique_lock<std::mutex> CtxGuard{WC->Lock};
136 // If there's a pending hard error, don't do more work.
140 WC->ErrWhence = Input.Filename;
142 auto ReaderOrErr = InstrProfReader::create(Input.Filename);
143 if (Error E = ReaderOrErr.takeError()) {
144 // Skip the empty profiles by returning sliently.
145 instrprof_error IPE = InstrProfError::take(std::move(E));
146 if (IPE != instrprof_error::empty_raw_profile)
147 WC->Err = make_error<InstrProfError>(IPE);
151 auto Reader = std::move(ReaderOrErr.get());
152 bool IsIRProfile = Reader->isIRLevelProfile();
153 if (WC->Writer.setIsIRLevelProfile(IsIRProfile)) {
154 WC->Err = make_error<StringError>(
155 "Merge IR generated profile with Clang generated profile.",
160 for (auto &I : *Reader) {
161 const StringRef FuncName = I.Name;
162 bool Reported = false;
163 WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
165 consumeError(std::move(E));
169 // Only show hint the first time an error occurs.
170 instrprof_error IPE = InstrProfError::take(std::move(E));
171 std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
172 bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
173 handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
174 FuncName, firstTime);
177 if (Reader->hasError())
178 WC->Err = Reader->getError();
181 /// Merge the \p Src writer context into \p Dst.
182 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
183 bool Reported = false;
184 Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
186 consumeError(std::move(E));
190 Dst->Err = std::move(E);
194 static void mergeInstrProfile(const WeightedFileVector &Inputs,
195 StringRef OutputFilename,
196 ProfileFormat OutputFormat, bool OutputSparse,
197 unsigned NumThreads) {
198 if (OutputFilename.compare("-") == 0)
199 exitWithError("Cannot write indexed profdata format to stdout.");
201 if (OutputFormat != PF_Binary && OutputFormat != PF_Text)
202 exitWithError("Unknown format is specified.");
205 raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
207 exitWithErrorCode(EC, OutputFilename);
209 std::mutex ErrorLock;
210 SmallSet<instrprof_error, 4> WriterErrorCodes;
212 // If NumThreads is not specified, auto-detect a good default.
214 NumThreads = std::max(1U, std::min(std::thread::hardware_concurrency(),
215 unsigned(Inputs.size() / 2)));
217 // Initialize the writer contexts.
218 SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
219 for (unsigned I = 0; I < NumThreads; ++I)
220 Contexts.emplace_back(llvm::make_unique<WriterContext>(
221 OutputSparse, ErrorLock, WriterErrorCodes));
223 if (NumThreads == 1) {
224 for (const auto &Input : Inputs)
225 loadInput(Input, Contexts[0].get());
227 ThreadPool Pool(NumThreads);
229 // Load the inputs in parallel (N/NumThreads serial steps).
231 for (const auto &Input : Inputs) {
232 Pool.async(loadInput, Input, Contexts[Ctx].get());
233 Ctx = (Ctx + 1) % NumThreads;
237 // Merge the writer contexts together (~ lg(NumThreads) serial steps).
238 unsigned Mid = Contexts.size() / 2;
239 unsigned End = Contexts.size();
240 assert(Mid > 0 && "Expected more than one context");
242 for (unsigned I = 0; I < Mid; ++I)
243 Pool.async(mergeWriterContexts, Contexts[I].get(),
244 Contexts[I + Mid].get());
247 Pool.async(mergeWriterContexts, Contexts[0].get(),
248 Contexts[End - 1].get());
256 // Handle deferred hard errors encountered during merging.
257 for (std::unique_ptr<WriterContext> &WC : Contexts)
259 exitWithError(std::move(WC->Err), WC->ErrWhence);
261 InstrProfWriter &Writer = Contexts[0]->Writer;
262 if (OutputFormat == PF_Text) {
263 if (Error E = Writer.writeText(Output))
264 exitWithError(std::move(E));
266 Writer.write(Output);
270 static sampleprof::SampleProfileFormat FormatMap[] = {
271 sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Binary,
272 sampleprof::SPF_GCC};
274 static void mergeSampleProfile(const WeightedFileVector &Inputs,
275 StringRef OutputFilename,
276 ProfileFormat OutputFormat) {
277 using namespace sampleprof;
279 SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
280 if (std::error_code EC = WriterOrErr.getError())
281 exitWithErrorCode(EC, OutputFilename);
283 auto Writer = std::move(WriterOrErr.get());
284 StringMap<FunctionSamples> ProfileMap;
285 SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
287 for (const auto &Input : Inputs) {
288 auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
289 if (std::error_code EC = ReaderOrErr.getError())
290 exitWithErrorCode(EC, Input.Filename);
292 // We need to keep the readers around until after all the files are
293 // read so that we do not lose the function names stored in each
294 // reader's memory. The function names are needed to write out the
295 // merged profile map.
296 Readers.push_back(std::move(ReaderOrErr.get()));
297 const auto Reader = Readers.back().get();
298 if (std::error_code EC = Reader->read())
299 exitWithErrorCode(EC, Input.Filename);
301 StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
302 for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
305 StringRef FName = I->first();
306 FunctionSamples &Samples = I->second;
307 sampleprof_error Result = ProfileMap[FName].merge(Samples, Input.Weight);
308 if (Result != sampleprof_error::success) {
309 std::error_code EC = make_error_code(Result);
310 handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
314 Writer->write(ProfileMap);
317 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
318 StringRef WeightStr, FileName;
319 std::tie(WeightStr, FileName) = WeightedFilename.split(',');
322 if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
323 exitWithError("Input weight must be a positive integer.");
325 return {FileName, Weight};
328 static std::unique_ptr<MemoryBuffer>
329 getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) {
330 if (InputFilenamesFile == "")
333 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile);
335 exitWithErrorCode(BufOrError.getError(), InputFilenamesFile);
337 return std::move(*BufOrError);
340 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
341 StringRef Filename = WF.Filename;
342 uint64_t Weight = WF.Weight;
344 // If it's STDIN just pass it on.
345 if (Filename == "-") {
346 WNI.push_back({Filename, Weight});
350 llvm::sys::fs::file_status Status;
351 llvm::sys::fs::status(Filename, Status);
352 if (!llvm::sys::fs::exists(Status))
353 exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
355 // If it's a source file, collect it.
356 if (llvm::sys::fs::is_regular_file(Status)) {
357 WNI.push_back({Filename, Weight});
361 if (llvm::sys::fs::is_directory(Status)) {
363 for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
364 F != E && !EC; F.increment(EC)) {
365 if (llvm::sys::fs::is_regular_file(F->path())) {
366 addWeightedInput(WNI, {F->path(), Weight});
370 exitWithErrorCode(EC, Filename);
374 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
375 WeightedFileVector &WFV) {
379 SmallVector<StringRef, 8> Entries;
380 StringRef Data = Buffer->getBuffer();
381 Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
382 for (const StringRef &FileWeightEntry : Entries) {
383 StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
385 if (SanitizedEntry.startswith("#"))
387 // If there's no comma, it's an unweighted profile.
388 else if (SanitizedEntry.find(',') == StringRef::npos)
389 addWeightedInput(WFV, {SanitizedEntry, 1});
391 addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
395 static int merge_main(int argc, const char *argv[]) {
396 cl::list<std::string> InputFilenames(cl::Positional,
397 cl::desc("<filename...>"));
398 cl::list<std::string> WeightedInputFilenames("weighted-input",
399 cl::desc("<weight>,<filename>"));
400 cl::opt<std::string> InputFilenamesFile(
401 "input-files", cl::init(""),
402 cl::desc("Path to file containing newline-separated "
403 "[<weight>,]<filename> entries"));
404 cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
405 cl::aliasopt(InputFilenamesFile));
406 cl::opt<bool> DumpInputFileList(
407 "dump-input-file-list", cl::init(false), cl::Hidden,
408 cl::desc("Dump the list of input files and their weights, then exit"));
409 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
410 cl::init("-"), cl::Required,
411 cl::desc("Output file"));
412 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
413 cl::aliasopt(OutputFilename));
414 cl::opt<ProfileKinds> ProfileKind(
415 cl::desc("Profile kind:"), cl::init(instr),
416 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
417 clEnumVal(sample, "Sample profile")));
418 cl::opt<ProfileFormat> OutputFormat(
419 cl::desc("Format of output profile"), cl::init(PF_Binary),
420 cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
421 clEnumValN(PF_Text, "text", "Text encoding"),
422 clEnumValN(PF_GCC, "gcc",
423 "GCC encoding (only meaningful for -sample)")));
424 cl::opt<bool> OutputSparse("sparse", cl::init(false),
425 cl::desc("Generate a sparse profile (only meaningful for -instr)"));
426 cl::opt<unsigned> NumThreads(
427 "num-threads", cl::init(0),
428 cl::desc("Number of merge threads to use (default: autodetect)"));
429 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
430 cl::aliasopt(NumThreads));
432 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
434 WeightedFileVector WeightedInputs;
435 for (StringRef Filename : InputFilenames)
436 addWeightedInput(WeightedInputs, {Filename, 1});
437 for (StringRef WeightedFilename : WeightedInputFilenames)
438 addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
440 // Make sure that the file buffer stays alive for the duration of the
441 // weighted input vector's lifetime.
442 auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile);
443 parseInputFilenamesFile(Buffer.get(), WeightedInputs);
445 if (WeightedInputs.empty())
446 exitWithError("No input files specified. See " +
447 sys::path::filename(argv[0]) + " -help");
449 if (DumpInputFileList) {
450 for (auto &WF : WeightedInputs)
451 outs() << WF.Weight << "," << WF.Filename << "\n";
455 if (ProfileKind == instr)
456 mergeInstrProfile(WeightedInputs, OutputFilename, OutputFormat,
457 OutputSparse, NumThreads);
459 mergeSampleProfile(WeightedInputs, OutputFilename, OutputFormat);
464 typedef struct ValueSitesStats {
466 : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
468 uint64_t TotalNumValueSites;
469 uint64_t TotalNumValueSitesWithValueProfile;
470 uint64_t TotalNumValues;
471 std::vector<unsigned> ValueSitesHistogram;
474 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
475 ValueSitesStats &Stats, raw_fd_ostream &OS,
476 InstrProfSymtab *Symtab) {
477 uint32_t NS = Func.getNumValueSites(VK);
478 Stats.TotalNumValueSites += NS;
479 for (size_t I = 0; I < NS; ++I) {
480 uint32_t NV = Func.getNumValueDataForSite(VK, I);
481 std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
482 Stats.TotalNumValues += NV;
484 Stats.TotalNumValueSitesWithValueProfile++;
485 if (NV > Stats.ValueSitesHistogram.size())
486 Stats.ValueSitesHistogram.resize(NV, 0);
487 Stats.ValueSitesHistogram[NV - 1]++;
489 for (uint32_t V = 0; V < NV; V++) {
490 OS << "\t[ " << I << ", ";
491 if (Symtab == nullptr)
494 OS << Symtab->getFuncName(VD[V].Value);
495 OS << ", " << VD[V].Count << " ]\n";
500 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
501 ValueSitesStats &Stats) {
502 OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n";
503 OS << " Total number of sites with values: "
504 << Stats.TotalNumValueSitesWithValueProfile << "\n";
505 OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n";
507 OS << " Value sites histogram:\n\tNumTargets, SiteCount\n";
508 for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
509 if (Stats.ValueSitesHistogram[I] > 0)
510 OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
514 static int showInstrProfile(const std::string &Filename, bool ShowCounts,
515 uint32_t TopN, bool ShowIndirectCallTargets,
516 bool ShowMemOPSizes, bool ShowDetailedSummary,
517 std::vector<uint32_t> DetailedSummaryCutoffs,
518 bool ShowAllFunctions,
519 const std::string &ShowFunction, bool TextFormat,
520 raw_fd_ostream &OS) {
521 auto ReaderOrErr = InstrProfReader::create(Filename);
522 std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
523 if (ShowDetailedSummary && Cutoffs.empty()) {
524 Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
526 InstrProfSummaryBuilder Builder(std::move(Cutoffs));
527 if (Error E = ReaderOrErr.takeError())
528 exitWithError(std::move(E), Filename);
530 auto Reader = std::move(ReaderOrErr.get());
531 bool IsIRInstr = Reader->isIRLevelProfile();
532 size_t ShownFunctions = 0;
533 int NumVPKind = IPVK_Last - IPVK_First + 1;
534 std::vector<ValueSitesStats> VPStats(NumVPKind);
536 auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
537 const std::pair<std::string, uint64_t> &v2) {
538 return v1.second > v2.second;
541 std::priority_queue<std::pair<std::string, uint64_t>,
542 std::vector<std::pair<std::string, uint64_t>>,
544 HottestFuncs(MinCmp);
546 for (const auto &Func : *Reader) {
548 ShowAllFunctions || (!ShowFunction.empty() &&
549 Func.Name.find(ShowFunction) != Func.Name.npos);
551 bool doTextFormatDump = (Show && ShowCounts && TextFormat);
553 if (doTextFormatDump) {
554 InstrProfSymtab &Symtab = Reader->getSymtab();
555 InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
560 assert(Func.Counts.size() > 0 && "function missing entry counter");
561 Builder.addRecord(Func);
564 uint64_t FuncMax = 0;
565 for (size_t I = 0, E = Func.Counts.size(); I < E; ++I)
566 FuncMax = std::max(FuncMax, Func.Counts[I]);
568 if (HottestFuncs.size() == TopN) {
569 if (HottestFuncs.top().second < FuncMax) {
571 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
574 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
584 OS << " " << Func.Name << ":\n"
585 << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
586 << " Counters: " << Func.Counts.size() << "\n";
588 OS << " Function count: " << Func.Counts[0] << "\n";
590 if (ShowIndirectCallTargets)
591 OS << " Indirect Call Site Count: "
592 << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
594 uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
595 if (ShowMemOPSizes && NumMemOPCalls > 0)
596 OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls
600 OS << " Block counts: [";
601 size_t Start = (IsIRInstr ? 0 : 1);
602 for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
603 OS << (I == Start ? "" : ", ") << Func.Counts[I];
608 if (ShowIndirectCallTargets) {
609 OS << " Indirect Target Results:\n";
610 traverseAllValueSites(Func, IPVK_IndirectCallTarget,
611 VPStats[IPVK_IndirectCallTarget], OS,
612 &(Reader->getSymtab()));
615 if (ShowMemOPSizes && NumMemOPCalls > 0) {
616 OS << " Memory Intrinsic Size Results:\n";
617 traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
622 if (Reader->hasError())
623 exitWithError(Reader->getError(), Filename);
625 if (ShowCounts && TextFormat)
627 std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
628 if (ShowAllFunctions || !ShowFunction.empty())
629 OS << "Functions shown: " << ShownFunctions << "\n";
630 OS << "Total functions: " << PS->getNumFunctions() << "\n";
631 OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
632 OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
635 std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
636 while (!HottestFuncs.empty()) {
637 SortedHottestFuncs.emplace_back(HottestFuncs.top());
641 << " functions with the largest internal block counts: \n";
642 for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
643 OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
646 if (ShownFunctions && ShowIndirectCallTargets) {
647 OS << "Statistics for indirect call sites profile:\n";
648 showValueSitesStats(OS, IPVK_IndirectCallTarget,
649 VPStats[IPVK_IndirectCallTarget]);
652 if (ShownFunctions && ShowMemOPSizes) {
653 OS << "Statistics for memory intrinsic calls sizes profile:\n";
654 showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
657 if (ShowDetailedSummary) {
658 OS << "Detailed summary:\n";
659 OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
660 OS << "Total count: " << PS->getTotalCount() << "\n";
661 for (auto Entry : PS->getDetailedSummary()) {
662 OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
664 << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
665 << " percentage of the total counts.\n";
671 static int showSampleProfile(const std::string &Filename, bool ShowCounts,
672 bool ShowAllFunctions,
673 const std::string &ShowFunction,
674 raw_fd_ostream &OS) {
675 using namespace sampleprof;
677 auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
678 if (std::error_code EC = ReaderOrErr.getError())
679 exitWithErrorCode(EC, Filename);
681 auto Reader = std::move(ReaderOrErr.get());
682 if (std::error_code EC = Reader->read())
683 exitWithErrorCode(EC, Filename);
685 if (ShowAllFunctions || ShowFunction.empty())
688 Reader->dumpFunctionProfile(ShowFunction, OS);
693 static int show_main(int argc, const char *argv[]) {
694 cl::opt<std::string> Filename(cl::Positional, cl::Required,
695 cl::desc("<profdata-file>"));
697 cl::opt<bool> ShowCounts("counts", cl::init(false),
698 cl::desc("Show counter values for shown functions"));
699 cl::opt<bool> TextFormat(
700 "text", cl::init(false),
701 cl::desc("Show instr profile data in text dump format"));
702 cl::opt<bool> ShowIndirectCallTargets(
703 "ic-targets", cl::init(false),
704 cl::desc("Show indirect call site target values for shown functions"));
705 cl::opt<bool> ShowMemOPSizes(
706 "memop-sizes", cl::init(false),
707 cl::desc("Show the profiled sizes of the memory intrinsic calls "
708 "for shown functions"));
709 cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
710 cl::desc("Show detailed profile summary"));
711 cl::list<uint32_t> DetailedSummaryCutoffs(
712 cl::CommaSeparated, "detailed-summary-cutoffs",
714 "Cutoff percentages (times 10000) for generating detailed summary"),
715 cl::value_desc("800000,901000,999999"));
716 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
717 cl::desc("Details for every function"));
718 cl::opt<std::string> ShowFunction("function",
719 cl::desc("Details for matching functions"));
721 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
722 cl::init("-"), cl::desc("Output file"));
723 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
724 cl::aliasopt(OutputFilename));
725 cl::opt<ProfileKinds> ProfileKind(
726 cl::desc("Profile kind:"), cl::init(instr),
727 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
728 clEnumVal(sample, "Sample profile")));
729 cl::opt<uint32_t> TopNFunctions(
731 cl::desc("Show the list of functions with the largest internal counts"));
733 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
735 if (OutputFilename.empty())
736 OutputFilename = "-";
739 raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
741 exitWithErrorCode(EC, OutputFilename);
743 if (ShowAllFunctions && !ShowFunction.empty())
744 errs() << "warning: -function argument ignored: showing all functions\n";
746 std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs.begin(),
747 DetailedSummaryCutoffs.end());
748 if (ProfileKind == instr)
749 return showInstrProfile(Filename, ShowCounts, TopNFunctions,
750 ShowIndirectCallTargets, ShowMemOPSizes,
751 ShowDetailedSummary, DetailedSummaryCutoffs,
752 ShowAllFunctions, ShowFunction, TextFormat, OS);
754 return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
758 int main(int argc, const char *argv[]) {
759 // Print a stack trace if we signal out.
760 sys::PrintStackTraceOnErrorSignal(argv[0]);
761 PrettyStackTraceProgram X(argc, argv);
762 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
764 StringRef ProgName(sys::path::filename(argv[0]));
766 int (*func)(int, const char *[]) = nullptr;
768 if (strcmp(argv[1], "merge") == 0)
770 else if (strcmp(argv[1], "show") == 0)
774 std::string Invocation(ProgName.str() + " " + argv[1]);
775 argv[1] = Invocation.c_str();
776 return func(argc - 1, argv + 1);
779 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
780 strcmp(argv[1], "--help") == 0) {
782 errs() << "OVERVIEW: LLVM profile data tools\n\n"
783 << "USAGE: " << ProgName << " <command> [args...]\n"
784 << "USAGE: " << ProgName << " <command> -help\n\n"
785 << "See each individual command --help for more details.\n"
786 << "Available commands: merge, show\n";
792 errs() << ProgName << ": No command specified!\n";
794 errs() << ProgName << ": Unknown command!\n";
796 errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";