1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // llvm-profdata merges .profdata files.
11 //
12 //===----------------------------------------------------------------------===//
13 
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"
34 #include <algorithm>
35 
36 using namespace llvm;
37 
38 enum ProfileFormat { PF_None = 0, PF_Text, PF_Binary, PF_GCC };
39 
40 static void exitWithError(const Twine &Message, StringRef Whence = "",
41                           StringRef Hint = "") {
42   errs() << "error: ";
43   if (!Whence.empty())
44     errs() << Whence << ": ";
45   errs() << Message << "\n";
46   if (!Hint.empty())
47     errs() << Hint << "\n";
48   ::exit(1);
49 }
50 
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();
55       StringRef Hint = "";
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?";
59       }
60       exitWithError(IPE.message(), Whence, Hint);
61     });
62   }
63 
64   exitWithError(toString(std::move(E)), Whence);
65 }
66 
67 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
68   exitWithError(EC.message(), Whence);
69 }
70 
71 namespace {
72 enum ProfileKinds { instr, sample };
73 }
74 
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 << ": ";
82 
83   auto IPE = instrprof_error::success;
84   E = handleErrors(std::move(E),
85                    [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
86                      IPE = E->get();
87                      return Error(std::move(E));
88                    });
89   errs() << toString(std::move(E)) << "\n";
90 
91   if (ShowHint) {
92     StringRef Hint = "";
93     if (IPE != instrprof_error::success) {
94       switch (IPE) {
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.";
100         break;
101       default:
102         break;
103       }
104     }
105 
106     if (!Hint.empty())
107       errs() << Hint << "\n";
108   }
109 }
110 
111 struct WeightedFile {
112   StringRef Filename;
113   uint64_t Weight;
114 
115   WeightedFile() {}
116 
117   WeightedFile(StringRef F, uint64_t W) : Filename{F}, Weight{W} {}
118 };
119 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
120 
121 /// Keep track of merged data and reported errors.
122 struct WriterContext {
123   std::mutex Lock;
124   InstrProfWriter Writer;
125   Error Err;
126   StringRef ErrWhence;
127   std::mutex &ErrLock;
128   SmallSet<instrprof_error, 4> &WriterErrorCodes;
129 
130   WriterContext(bool IsSparse, std::mutex &ErrLock,
131                 SmallSet<instrprof_error, 4> &WriterErrorCodes)
132       : Lock(), Writer(IsSparse), Err(Error::success()), ErrWhence(""),
133         ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {}
134 };
135 
136 /// Load an input into a writer context.
137 static void loadInput(const WeightedFile &Input, WriterContext *WC) {
138   std::unique_lock<std::mutex> CtxGuard{WC->Lock};
139 
140   // If there's a pending hard error, don't do more work.
141   if (WC->Err)
142     return;
143 
144   WC->ErrWhence = Input.Filename;
145 
146   auto ReaderOrErr = InstrProfReader::create(Input.Filename);
147   if ((WC->Err = ReaderOrErr.takeError()))
148     return;
149 
150   auto Reader = std::move(ReaderOrErr.get());
151   bool IsIRProfile = Reader->isIRLevelProfile();
152   if (WC->Writer.setIsIRLevelProfile(IsIRProfile)) {
153     WC->Err = make_error<StringError>(
154         "Merge IR generated profile with Clang generated profile.",
155         std::error_code());
156     return;
157   }
158 
159   for (auto &I : *Reader) {
160     if (Error E = WC->Writer.addRecord(std::move(I), Input.Weight)) {
161       // Only show hint the first time an error occurs.
162       instrprof_error IPE = InstrProfError::take(std::move(E));
163       std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
164       bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
165       handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
166                              I.Name, firstTime);
167     }
168   }
169   if (Reader->hasError())
170     WC->Err = Reader->getError();
171 }
172 
173 /// Merge the \p Src writer context into \p Dst.
174 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
175   if (Error E = Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer)))
176     Dst->Err = std::move(E);
177 }
178 
179 static void mergeInstrProfile(const WeightedFileVector &Inputs,
180                               StringRef OutputFilename,
181                               ProfileFormat OutputFormat, bool OutputSparse,
182                               unsigned NumThreads) {
183   if (OutputFilename.compare("-") == 0)
184     exitWithError("Cannot write indexed profdata format to stdout.");
185 
186   if (OutputFormat != PF_Binary && OutputFormat != PF_Text)
187     exitWithError("Unknown format is specified.");
188 
189   std::error_code EC;
190   raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
191   if (EC)
192     exitWithErrorCode(EC, OutputFilename);
193 
194   std::mutex ErrorLock;
195   SmallSet<instrprof_error, 4> WriterErrorCodes;
196 
197   // If NumThreads is not specified, auto-detect a good default.
198   if (NumThreads == 0)
199     NumThreads = std::max(1U, std::min(std::thread::hardware_concurrency(),
200                                        unsigned(Inputs.size() / 2)));
201 
202   // Initialize the writer contexts.
203   SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
204   for (unsigned I = 0; I < NumThreads; ++I)
205     Contexts.emplace_back(llvm::make_unique<WriterContext>(
206         OutputSparse, ErrorLock, WriterErrorCodes));
207 
208   if (NumThreads == 1) {
209     for (const auto &Input : Inputs)
210       loadInput(Input, Contexts[0].get());
211   } else {
212     ThreadPool Pool(NumThreads);
213 
214     // Load the inputs in parallel (N/NumThreads serial steps).
215     unsigned Ctx = 0;
216     for (const auto &Input : Inputs) {
217       Pool.async(loadInput, Input, Contexts[Ctx].get());
218       Ctx = (Ctx + 1) % NumThreads;
219     }
220     Pool.wait();
221 
222     // Merge the writer contexts together (~ lg(NumThreads) serial steps).
223     unsigned Mid = Contexts.size() / 2;
224     unsigned End = Contexts.size();
225     assert(Mid > 0 && "Expected more than one context");
226     do {
227       for (unsigned I = 0; I < Mid; ++I)
228         Pool.async(mergeWriterContexts, Contexts[I].get(),
229                    Contexts[I + Mid].get());
230       Pool.wait();
231       if (End & 1) {
232         Pool.async(mergeWriterContexts, Contexts[0].get(),
233                    Contexts[End - 1].get());
234         Pool.wait();
235       }
236       End = Mid;
237       Mid /= 2;
238     } while (Mid > 0);
239   }
240 
241   // Handle deferred hard errors encountered during merging.
242   for (std::unique_ptr<WriterContext> &WC : Contexts)
243     if (WC->Err)
244       exitWithError(std::move(WC->Err), WC->ErrWhence);
245 
246   InstrProfWriter &Writer = Contexts[0]->Writer;
247   if (OutputFormat == PF_Text)
248     Writer.writeText(Output);
249   else
250     Writer.write(Output);
251 }
252 
253 static sampleprof::SampleProfileFormat FormatMap[] = {
254     sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Binary,
255     sampleprof::SPF_GCC};
256 
257 static void mergeSampleProfile(const WeightedFileVector &Inputs,
258                                StringRef OutputFilename,
259                                ProfileFormat OutputFormat) {
260   using namespace sampleprof;
261   auto WriterOrErr =
262       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
263   if (std::error_code EC = WriterOrErr.getError())
264     exitWithErrorCode(EC, OutputFilename);
265 
266   auto Writer = std::move(WriterOrErr.get());
267   StringMap<FunctionSamples> ProfileMap;
268   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
269   LLVMContext Context;
270   for (const auto &Input : Inputs) {
271     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
272     if (std::error_code EC = ReaderOrErr.getError())
273       exitWithErrorCode(EC, Input.Filename);
274 
275     // We need to keep the readers around until after all the files are
276     // read so that we do not lose the function names stored in each
277     // reader's memory. The function names are needed to write out the
278     // merged profile map.
279     Readers.push_back(std::move(ReaderOrErr.get()));
280     const auto Reader = Readers.back().get();
281     if (std::error_code EC = Reader->read())
282       exitWithErrorCode(EC, Input.Filename);
283 
284     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
285     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
286                                               E = Profiles.end();
287          I != E; ++I) {
288       StringRef FName = I->first();
289       FunctionSamples &Samples = I->second;
290       sampleprof_error Result = ProfileMap[FName].merge(Samples, Input.Weight);
291       if (Result != sampleprof_error::success) {
292         std::error_code EC = make_error_code(Result);
293         handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
294       }
295     }
296   }
297   Writer->write(ProfileMap);
298 }
299 
300 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
301   StringRef WeightStr, FileName;
302   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
303 
304   uint64_t Weight;
305   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
306     exitWithError("Input weight must be a positive integer.");
307 
308   if (!sys::fs::exists(FileName))
309     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
310                       FileName);
311 
312   return WeightedFile(FileName, Weight);
313 }
314 
315 static std::unique_ptr<MemoryBuffer>
316 getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) {
317   if (InputFilenamesFile == "")
318     return {};
319 
320   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile);
321   if (!BufOrError)
322     exitWithErrorCode(BufOrError.getError(), InputFilenamesFile);
323 
324   return std::move(*BufOrError);
325 }
326 
327 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
328                                     WeightedFileVector &WFV) {
329   if (!Buffer)
330     return;
331 
332   SmallVector<StringRef, 8> Entries;
333   StringRef Data = Buffer->getBuffer();
334   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
335   for (const StringRef &FileWeightEntry : Entries) {
336     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
337     // Skip comments.
338     if (SanitizedEntry.startswith("#"))
339       continue;
340     // If there's no comma, it's an unweighted profile.
341     else if (SanitizedEntry.find(',') == StringRef::npos)
342       WFV.emplace_back(SanitizedEntry, 1);
343     else
344       WFV.emplace_back(parseWeightedFile(SanitizedEntry));
345   }
346 }
347 
348 static int merge_main(int argc, const char *argv[]) {
349   cl::list<std::string> InputFilenames(cl::Positional,
350                                        cl::desc("<filename...>"));
351   cl::list<std::string> WeightedInputFilenames("weighted-input",
352                                                cl::desc("<weight>,<filename>"));
353   cl::opt<std::string> InputFilenamesFile(
354       "input-files", cl::init(""),
355       cl::desc("Path to file containing newline-separated "
356                "[<weight>,]<filename> entries"));
357   cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
358                                 cl::aliasopt(InputFilenamesFile));
359   cl::opt<bool> DumpInputFileList(
360       "dump-input-file-list", cl::init(false), cl::Hidden,
361       cl::desc("Dump the list of input files and their weights, then exit"));
362   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
363                                       cl::init("-"), cl::Required,
364                                       cl::desc("Output file"));
365   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
366                             cl::aliasopt(OutputFilename));
367   cl::opt<ProfileKinds> ProfileKind(
368       cl::desc("Profile kind:"), cl::init(instr),
369       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
370                  clEnumVal(sample, "Sample profile"), clEnumValEnd));
371   cl::opt<ProfileFormat> OutputFormat(
372       cl::desc("Format of output profile"), cl::init(PF_Binary),
373       cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
374                  clEnumValN(PF_Text, "text", "Text encoding"),
375                  clEnumValN(PF_GCC, "gcc",
376                             "GCC encoding (only meaningful for -sample)"),
377                  clEnumValEnd));
378   cl::opt<bool> OutputSparse("sparse", cl::init(false),
379       cl::desc("Generate a sparse profile (only meaningful for -instr)"));
380   cl::opt<unsigned> NumThreads(
381       "num-threads", cl::init(0),
382       cl::desc("Number of merge threads to use (default: autodetect)"));
383   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
384                         cl::aliasopt(NumThreads));
385 
386   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
387 
388   WeightedFileVector WeightedInputs;
389   for (StringRef Filename : InputFilenames)
390     WeightedInputs.emplace_back(Filename, 1);
391   for (StringRef WeightedFilename : WeightedInputFilenames)
392     WeightedInputs.emplace_back(parseWeightedFile(WeightedFilename));
393 
394   // Make sure that the file buffer stays alive for the duration of the
395   // weighted input vector's lifetime.
396   auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile);
397   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
398 
399   if (WeightedInputs.empty())
400     exitWithError("No input files specified. See " +
401                   sys::path::filename(argv[0]) + " -help");
402 
403   if (DumpInputFileList) {
404     for (auto &WF : WeightedInputs)
405       outs() << WF.Weight << "," << WF.Filename << "\n";
406     return 0;
407   }
408 
409   if (ProfileKind == instr)
410     mergeInstrProfile(WeightedInputs, OutputFilename, OutputFormat,
411                       OutputSparse, NumThreads);
412   else
413     mergeSampleProfile(WeightedInputs, OutputFilename, OutputFormat);
414 
415   return 0;
416 }
417 
418 static int showInstrProfile(const std::string &Filename, bool ShowCounts,
419                             bool ShowIndirectCallTargets,
420                             bool ShowDetailedSummary,
421                             std::vector<uint32_t> DetailedSummaryCutoffs,
422                             bool ShowAllFunctions,
423                             const std::string &ShowFunction, bool TextFormat,
424                             raw_fd_ostream &OS) {
425   auto ReaderOrErr = InstrProfReader::create(Filename);
426   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
427   if (ShowDetailedSummary && Cutoffs.empty()) {
428     Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
429   }
430   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
431   if (Error E = ReaderOrErr.takeError())
432     exitWithError(std::move(E), Filename);
433 
434   auto Reader = std::move(ReaderOrErr.get());
435   bool IsIRInstr = Reader->isIRLevelProfile();
436   size_t ShownFunctions = 0;
437   uint64_t TotalNumValueSites = 0;
438   uint64_t TotalNumValueSitesWithValueProfile = 0;
439   uint64_t TotalNumValues = 0;
440   for (const auto &Func : *Reader) {
441     bool Show =
442         ShowAllFunctions || (!ShowFunction.empty() &&
443                              Func.Name.find(ShowFunction) != Func.Name.npos);
444 
445     bool doTextFormatDump = (Show && ShowCounts && TextFormat);
446 
447     if (doTextFormatDump) {
448       InstrProfSymtab &Symtab = Reader->getSymtab();
449       InstrProfWriter::writeRecordInText(Func, Symtab, OS);
450       continue;
451     }
452 
453     assert(Func.Counts.size() > 0 && "function missing entry counter");
454     Builder.addRecord(Func);
455 
456     if (Show) {
457 
458       if (!ShownFunctions)
459         OS << "Counters:\n";
460 
461       ++ShownFunctions;
462 
463       OS << "  " << Func.Name << ":\n"
464          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
465          << "    Counters: " << Func.Counts.size() << "\n";
466       if (!IsIRInstr)
467         OS << "    Function count: " << Func.Counts[0] << "\n";
468 
469       if (ShowIndirectCallTargets)
470         OS << "    Indirect Call Site Count: "
471            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
472 
473       if (ShowCounts) {
474         OS << "    Block counts: [";
475         size_t Start = (IsIRInstr ? 0 : 1);
476         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
477           OS << (I == Start ? "" : ", ") << Func.Counts[I];
478         }
479         OS << "]\n";
480       }
481 
482       if (ShowIndirectCallTargets) {
483         InstrProfSymtab &Symtab = Reader->getSymtab();
484         uint32_t NS = Func.getNumValueSites(IPVK_IndirectCallTarget);
485         OS << "    Indirect Target Results: \n";
486         TotalNumValueSites += NS;
487         for (size_t I = 0; I < NS; ++I) {
488           uint32_t NV = Func.getNumValueDataForSite(IPVK_IndirectCallTarget, I);
489           std::unique_ptr<InstrProfValueData[]> VD =
490               Func.getValueForSite(IPVK_IndirectCallTarget, I);
491           TotalNumValues += NV;
492           if (NV)
493             TotalNumValueSitesWithValueProfile++;
494           for (uint32_t V = 0; V < NV; V++) {
495             OS << "\t[ " << I << ", ";
496             OS << Symtab.getFuncName(VD[V].Value) << ", " << VD[V].Count
497                << " ]\n";
498           }
499         }
500       }
501     }
502   }
503   if (Reader->hasError())
504     exitWithError(Reader->getError(), Filename);
505 
506   if (ShowCounts && TextFormat)
507     return 0;
508   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
509   if (ShowAllFunctions || !ShowFunction.empty())
510     OS << "Functions shown: " << ShownFunctions << "\n";
511   OS << "Total functions: " << PS->getNumFunctions() << "\n";
512   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
513   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
514   if (ShownFunctions && ShowIndirectCallTargets) {
515     OS << "Total Number of Indirect Call Sites : " << TotalNumValueSites
516        << "\n";
517     OS << "Total Number of Sites With Values : "
518        << TotalNumValueSitesWithValueProfile << "\n";
519     OS << "Total Number of Profiled Values : " << TotalNumValues << "\n";
520   }
521 
522   if (ShowDetailedSummary) {
523     OS << "Detailed summary:\n";
524     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
525     OS << "Total count: " << PS->getTotalCount() << "\n";
526     for (auto Entry : PS->getDetailedSummary()) {
527       OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
528          << " account for "
529          << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
530          << " percentage of the total counts.\n";
531     }
532   }
533   return 0;
534 }
535 
536 static int showSampleProfile(const std::string &Filename, bool ShowCounts,
537                              bool ShowAllFunctions,
538                              const std::string &ShowFunction,
539                              raw_fd_ostream &OS) {
540   using namespace sampleprof;
541   LLVMContext Context;
542   auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
543   if (std::error_code EC = ReaderOrErr.getError())
544     exitWithErrorCode(EC, Filename);
545 
546   auto Reader = std::move(ReaderOrErr.get());
547   if (std::error_code EC = Reader->read())
548     exitWithErrorCode(EC, Filename);
549 
550   if (ShowAllFunctions || ShowFunction.empty())
551     Reader->dump(OS);
552   else
553     Reader->dumpFunctionProfile(ShowFunction, OS);
554 
555   return 0;
556 }
557 
558 static int show_main(int argc, const char *argv[]) {
559   cl::opt<std::string> Filename(cl::Positional, cl::Required,
560                                 cl::desc("<profdata-file>"));
561 
562   cl::opt<bool> ShowCounts("counts", cl::init(false),
563                            cl::desc("Show counter values for shown functions"));
564   cl::opt<bool> TextFormat(
565       "text", cl::init(false),
566       cl::desc("Show instr profile data in text dump format"));
567   cl::opt<bool> ShowIndirectCallTargets(
568       "ic-targets", cl::init(false),
569       cl::desc("Show indirect call site target values for shown functions"));
570   cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
571                                     cl::desc("Show detailed profile summary"));
572   cl::list<uint32_t> DetailedSummaryCutoffs(
573       cl::CommaSeparated, "detailed-summary-cutoffs",
574       cl::desc(
575           "Cutoff percentages (times 10000) for generating detailed summary"),
576       cl::value_desc("800000,901000,999999"));
577   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
578                                  cl::desc("Details for every function"));
579   cl::opt<std::string> ShowFunction("function",
580                                     cl::desc("Details for matching functions"));
581 
582   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
583                                       cl::init("-"), cl::desc("Output file"));
584   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
585                             cl::aliasopt(OutputFilename));
586   cl::opt<ProfileKinds> ProfileKind(
587       cl::desc("Profile kind:"), cl::init(instr),
588       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
589                  clEnumVal(sample, "Sample profile"), clEnumValEnd));
590 
591   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
592 
593   if (OutputFilename.empty())
594     OutputFilename = "-";
595 
596   std::error_code EC;
597   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
598   if (EC)
599     exitWithErrorCode(EC, OutputFilename);
600 
601   if (ShowAllFunctions && !ShowFunction.empty())
602     errs() << "warning: -function argument ignored: showing all functions\n";
603 
604   std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs.begin(),
605                                 DetailedSummaryCutoffs.end());
606   if (ProfileKind == instr)
607     return showInstrProfile(Filename, ShowCounts, ShowIndirectCallTargets,
608                             ShowDetailedSummary, DetailedSummaryCutoffs,
609                             ShowAllFunctions, ShowFunction, TextFormat, OS);
610   else
611     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
612                              ShowFunction, OS);
613 }
614 
615 int main(int argc, const char *argv[]) {
616   // Print a stack trace if we signal out.
617   sys::PrintStackTraceOnErrorSignal(argv[0]);
618   PrettyStackTraceProgram X(argc, argv);
619   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
620 
621   StringRef ProgName(sys::path::filename(argv[0]));
622   if (argc > 1) {
623     int (*func)(int, const char *[]) = nullptr;
624 
625     if (strcmp(argv[1], "merge") == 0)
626       func = merge_main;
627     else if (strcmp(argv[1], "show") == 0)
628       func = show_main;
629 
630     if (func) {
631       std::string Invocation(ProgName.str() + " " + argv[1]);
632       argv[1] = Invocation.c_str();
633       return func(argc - 1, argv + 1);
634     }
635 
636     if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
637         strcmp(argv[1], "--help") == 0) {
638 
639       errs() << "OVERVIEW: LLVM profile data tools\n\n"
640              << "USAGE: " << ProgName << " <command> [args...]\n"
641              << "USAGE: " << ProgName << " <command> -help\n\n"
642              << "Available commands: merge, show\n";
643       return 0;
644     }
645   }
646 
647   if (argc < 2)
648     errs() << ProgName << ": No command specified!\n";
649   else
650     errs() << ProgName << ": Unknown command!\n";
651 
652   errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
653   return 1;
654 }
655