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