1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // llvm-profdata merges .profdata files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/SmallSet.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/ProfileData/InstrProfReader.h"
18 #include "llvm/ProfileData/InstrProfWriter.h"
19 #include "llvm/ProfileData/ProfileCommon.h"
20 #include "llvm/ProfileData/SampleProfReader.h"
21 #include "llvm/ProfileData/SampleProfWriter.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/InitLLVM.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/Threading.h"
30 #include "llvm/Support/ThreadPool.h"
31 #include "llvm/Support/WithColor.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 
35 using namespace llvm;
36 
37 enum ProfileFormat {
38   PF_None = 0,
39   PF_Text,
40   PF_Compact_Binary,
41   PF_Ext_Binary,
42   PF_GCC,
43   PF_Binary
44 };
45 
46 static void warn(Twine Message, std::string Whence = "",
47                  std::string Hint = "") {
48   WithColor::warning();
49   if (!Whence.empty())
50     errs() << Whence << ": ";
51   errs() << Message << "\n";
52   if (!Hint.empty())
53     WithColor::note() << Hint << "\n";
54 }
55 
56 static void exitWithError(Twine Message, std::string Whence = "",
57                           std::string Hint = "") {
58   WithColor::error();
59   if (!Whence.empty())
60     errs() << Whence << ": ";
61   errs() << Message << "\n";
62   if (!Hint.empty())
63     WithColor::note() << Hint << "\n";
64   ::exit(1);
65 }
66 
67 static void exitWithError(Error E, StringRef Whence = "") {
68   if (E.isA<InstrProfError>()) {
69     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
70       instrprof_error instrError = IPE.get();
71       StringRef Hint = "";
72       if (instrError == instrprof_error::unrecognized_format) {
73         // Hint for common error of forgetting --sample for sample profiles.
74         Hint = "Perhaps you forgot to use the --sample option?";
75       }
76       exitWithError(IPE.message(), std::string(Whence), std::string(Hint));
77     });
78   }
79 
80   exitWithError(toString(std::move(E)), std::string(Whence));
81 }
82 
83 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
84   exitWithError(EC.message(), std::string(Whence));
85 }
86 
87 namespace {
88 enum ProfileKinds { instr, sample };
89 enum FailureMode { failIfAnyAreInvalid, failIfAllAreInvalid };
90 }
91 
92 static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
93                                  StringRef Whence = "") {
94   if (FailMode == failIfAnyAreInvalid)
95     exitWithErrorCode(EC, Whence);
96   else
97     warn(EC.message(), std::string(Whence));
98 }
99 
100 static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
101                                    StringRef WhenceFunction = "",
102                                    bool ShowHint = true) {
103   if (!WhenceFile.empty())
104     errs() << WhenceFile << ": ";
105   if (!WhenceFunction.empty())
106     errs() << WhenceFunction << ": ";
107 
108   auto IPE = instrprof_error::success;
109   E = handleErrors(std::move(E),
110                    [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
111                      IPE = E->get();
112                      return Error(std::move(E));
113                    });
114   errs() << toString(std::move(E)) << "\n";
115 
116   if (ShowHint) {
117     StringRef Hint = "";
118     if (IPE != instrprof_error::success) {
119       switch (IPE) {
120       case instrprof_error::hash_mismatch:
121       case instrprof_error::count_mismatch:
122       case instrprof_error::value_site_count_mismatch:
123         Hint = "Make sure that all profile data to be merged is generated "
124                "from the same binary.";
125         break;
126       default:
127         break;
128       }
129     }
130 
131     if (!Hint.empty())
132       errs() << Hint << "\n";
133   }
134 }
135 
136 namespace {
137 /// A remapper from original symbol names to new symbol names based on a file
138 /// containing a list of mappings from old name to new name.
139 class SymbolRemapper {
140   std::unique_ptr<MemoryBuffer> File;
141   DenseMap<StringRef, StringRef> RemappingTable;
142 
143 public:
144   /// Build a SymbolRemapper from a file containing a list of old/new symbols.
145   static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
146     auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
147     if (!BufOrError)
148       exitWithErrorCode(BufOrError.getError(), InputFile);
149 
150     auto Remapper = std::make_unique<SymbolRemapper>();
151     Remapper->File = std::move(BufOrError.get());
152 
153     for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
154          !LineIt.is_at_eof(); ++LineIt) {
155       std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
156       if (Parts.first.empty() || Parts.second.empty() ||
157           Parts.second.count(' ')) {
158         exitWithError("unexpected line in remapping file",
159                       (InputFile + ":" + Twine(LineIt.line_number())).str(),
160                       "expected 'old_symbol new_symbol'");
161       }
162       Remapper->RemappingTable.insert(Parts);
163     }
164     return Remapper;
165   }
166 
167   /// Attempt to map the given old symbol into a new symbol.
168   ///
169   /// \return The new symbol, or \p Name if no such symbol was found.
170   StringRef operator()(StringRef Name) {
171     StringRef New = RemappingTable.lookup(Name);
172     return New.empty() ? Name : New;
173   }
174 };
175 }
176 
177 struct WeightedFile {
178   std::string Filename;
179   uint64_t Weight;
180 };
181 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
182 
183 /// Keep track of merged data and reported errors.
184 struct WriterContext {
185   std::mutex Lock;
186   InstrProfWriter Writer;
187   std::vector<std::pair<Error, std::string>> Errors;
188   std::mutex &ErrLock;
189   SmallSet<instrprof_error, 4> &WriterErrorCodes;
190 
191   WriterContext(bool IsSparse, std::mutex &ErrLock,
192                 SmallSet<instrprof_error, 4> &WriterErrorCodes)
193       : Lock(), Writer(IsSparse), Errors(), ErrLock(ErrLock),
194         WriterErrorCodes(WriterErrorCodes) {}
195 };
196 
197 /// Computer the overlap b/w profile BaseFilename and TestFileName,
198 /// and store the program level result to Overlap.
199 static void overlapInput(const std::string &BaseFilename,
200                          const std::string &TestFilename, WriterContext *WC,
201                          OverlapStats &Overlap,
202                          const OverlapFuncFilters &FuncFilter,
203                          raw_fd_ostream &OS, bool IsCS) {
204   auto ReaderOrErr = InstrProfReader::create(TestFilename);
205   if (Error E = ReaderOrErr.takeError()) {
206     // Skip the empty profiles by returning sliently.
207     instrprof_error IPE = InstrProfError::take(std::move(E));
208     if (IPE != instrprof_error::empty_raw_profile)
209       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), TestFilename);
210     return;
211   }
212 
213   auto Reader = std::move(ReaderOrErr.get());
214   for (auto &I : *Reader) {
215     OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
216     FuncOverlap.setFuncInfo(I.Name, I.Hash);
217 
218     WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
219     FuncOverlap.dump(OS);
220   }
221 }
222 
223 /// Load an input into a writer context.
224 static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
225                       WriterContext *WC) {
226   std::unique_lock<std::mutex> CtxGuard{WC->Lock};
227 
228   // Copy the filename, because llvm::ThreadPool copied the input "const
229   // WeightedFile &" by value, making a reference to the filename within it
230   // invalid outside of this packaged task.
231   std::string Filename = Input.Filename;
232 
233   auto ReaderOrErr = InstrProfReader::create(Input.Filename);
234   if (Error E = ReaderOrErr.takeError()) {
235     // Skip the empty profiles by returning sliently.
236     instrprof_error IPE = InstrProfError::take(std::move(E));
237     if (IPE != instrprof_error::empty_raw_profile)
238       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename);
239     return;
240   }
241 
242   auto Reader = std::move(ReaderOrErr.get());
243   bool IsIRProfile = Reader->isIRLevelProfile();
244   bool HasCSIRProfile = Reader->hasCSIRLevelProfile();
245   if (WC->Writer.setIsIRLevelProfile(IsIRProfile, HasCSIRProfile)) {
246     WC->Errors.emplace_back(
247         make_error<StringError>(
248             "Merge IR generated profile with Clang generated profile.",
249             std::error_code()),
250         Filename);
251     return;
252   }
253 
254   for (auto &I : *Reader) {
255     if (Remapper)
256       I.Name = (*Remapper)(I.Name);
257     const StringRef FuncName = I.Name;
258     bool Reported = false;
259     WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
260       if (Reported) {
261         consumeError(std::move(E));
262         return;
263       }
264       Reported = true;
265       // Only show hint the first time an error occurs.
266       instrprof_error IPE = InstrProfError::take(std::move(E));
267       std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
268       bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
269       handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
270                              FuncName, firstTime);
271     });
272   }
273   if (Reader->hasError())
274     if (Error E = Reader->getError())
275       WC->Errors.emplace_back(std::move(E), Filename);
276 }
277 
278 /// Merge the \p Src writer context into \p Dst.
279 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
280   for (auto &ErrorPair : Src->Errors)
281     Dst->Errors.push_back(std::move(ErrorPair));
282   Src->Errors.clear();
283 
284   Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
285     instrprof_error IPE = InstrProfError::take(std::move(E));
286     std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
287     bool firstTime = Dst->WriterErrorCodes.insert(IPE).second;
288     if (firstTime)
289       warn(toString(make_error<InstrProfError>(IPE)));
290   });
291 }
292 
293 static void mergeInstrProfile(const WeightedFileVector &Inputs,
294                               SymbolRemapper *Remapper,
295                               StringRef OutputFilename,
296                               ProfileFormat OutputFormat, bool OutputSparse,
297                               unsigned NumThreads, FailureMode FailMode) {
298   if (OutputFilename.compare("-") == 0)
299     exitWithError("Cannot write indexed profdata format to stdout.");
300 
301   if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
302       OutputFormat != PF_Ext_Binary && OutputFormat != PF_Text)
303     exitWithError("Unknown format is specified.");
304 
305   std::mutex ErrorLock;
306   SmallSet<instrprof_error, 4> WriterErrorCodes;
307 
308   // If NumThreads is not specified, auto-detect a good default.
309   if (NumThreads == 0)
310     NumThreads = std::min(hardware_concurrency().compute_thread_count(),
311                           unsigned((Inputs.size() + 1) / 2));
312   // FIXME: There's a bug here, where setting NumThreads = Inputs.size() fails
313   // the merge_empty_profile.test because the InstrProfWriter.ProfileKind isn't
314   // merged, thus the emitted file ends up with a PF_Unknown kind.
315 
316   // Initialize the writer contexts.
317   SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
318   for (unsigned I = 0; I < NumThreads; ++I)
319     Contexts.emplace_back(std::make_unique<WriterContext>(
320         OutputSparse, ErrorLock, WriterErrorCodes));
321 
322   if (NumThreads == 1) {
323     for (const auto &Input : Inputs)
324       loadInput(Input, Remapper, Contexts[0].get());
325   } else {
326     ThreadPool Pool(hardware_concurrency(NumThreads));
327 
328     // Load the inputs in parallel (N/NumThreads serial steps).
329     unsigned Ctx = 0;
330     for (const auto &Input : Inputs) {
331       Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get());
332       Ctx = (Ctx + 1) % NumThreads;
333     }
334     Pool.wait();
335 
336     // Merge the writer contexts together (~ lg(NumThreads) serial steps).
337     unsigned Mid = Contexts.size() / 2;
338     unsigned End = Contexts.size();
339     assert(Mid > 0 && "Expected more than one context");
340     do {
341       for (unsigned I = 0; I < Mid; ++I)
342         Pool.async(mergeWriterContexts, Contexts[I].get(),
343                    Contexts[I + Mid].get());
344       Pool.wait();
345       if (End & 1) {
346         Pool.async(mergeWriterContexts, Contexts[0].get(),
347                    Contexts[End - 1].get());
348         Pool.wait();
349       }
350       End = Mid;
351       Mid /= 2;
352     } while (Mid > 0);
353   }
354 
355   // Handle deferred errors encountered during merging. If the number of errors
356   // is equal to the number of inputs the merge failed.
357   unsigned NumErrors = 0;
358   for (std::unique_ptr<WriterContext> &WC : Contexts) {
359     for (auto &ErrorPair : WC->Errors) {
360       ++NumErrors;
361       warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
362     }
363   }
364   if (NumErrors == Inputs.size() ||
365       (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
366     exitWithError("No profiles could be merged.");
367 
368   std::error_code EC;
369   raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::OF_None);
370   if (EC)
371     exitWithErrorCode(EC, OutputFilename);
372 
373   InstrProfWriter &Writer = Contexts[0]->Writer;
374   if (OutputFormat == PF_Text) {
375     if (Error E = Writer.writeText(Output))
376       exitWithError(std::move(E));
377   } else {
378     Writer.write(Output);
379   }
380 }
381 
382 /// Make a copy of the given function samples with all symbol names remapped
383 /// by the provided symbol remapper.
384 static sampleprof::FunctionSamples
385 remapSamples(const sampleprof::FunctionSamples &Samples,
386              SymbolRemapper &Remapper, sampleprof_error &Error) {
387   sampleprof::FunctionSamples Result;
388   Result.setName(Remapper(Samples.getName()));
389   Result.addTotalSamples(Samples.getTotalSamples());
390   Result.addHeadSamples(Samples.getHeadSamples());
391   for (const auto &BodySample : Samples.getBodySamples()) {
392     Result.addBodySamples(BodySample.first.LineOffset,
393                           BodySample.first.Discriminator,
394                           BodySample.second.getSamples());
395     for (const auto &Target : BodySample.second.getCallTargets()) {
396       Result.addCalledTargetSamples(BodySample.first.LineOffset,
397                                     BodySample.first.Discriminator,
398                                     Remapper(Target.first()), Target.second);
399     }
400   }
401   for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
402     sampleprof::FunctionSamplesMap &Target =
403         Result.functionSamplesAt(CallsiteSamples.first);
404     for (const auto &Callsite : CallsiteSamples.second) {
405       sampleprof::FunctionSamples Remapped =
406           remapSamples(Callsite.second, Remapper, Error);
407       MergeResult(Error,
408                   Target[std::string(Remapped.getName())].merge(Remapped));
409     }
410   }
411   return Result;
412 }
413 
414 static sampleprof::SampleProfileFormat FormatMap[] = {
415     sampleprof::SPF_None,
416     sampleprof::SPF_Text,
417     sampleprof::SPF_Compact_Binary,
418     sampleprof::SPF_Ext_Binary,
419     sampleprof::SPF_GCC,
420     sampleprof::SPF_Binary};
421 
422 static std::unique_ptr<MemoryBuffer>
423 getInputFileBuf(const StringRef &InputFile) {
424   if (InputFile == "")
425     return {};
426 
427   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
428   if (!BufOrError)
429     exitWithErrorCode(BufOrError.getError(), InputFile);
430 
431   return std::move(*BufOrError);
432 }
433 
434 static void populateProfileSymbolList(MemoryBuffer *Buffer,
435                                       sampleprof::ProfileSymbolList &PSL) {
436   if (!Buffer)
437     return;
438 
439   SmallVector<StringRef, 32> SymbolVec;
440   StringRef Data = Buffer->getBuffer();
441   Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
442 
443   for (StringRef symbol : SymbolVec)
444     PSL.add(symbol);
445 }
446 
447 static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer,
448                                   ProfileFormat OutputFormat,
449                                   MemoryBuffer *Buffer,
450                                   sampleprof::ProfileSymbolList &WriterList,
451                                   bool CompressAllSections, bool UseMD5,
452                                   bool PartialProfile) {
453   populateProfileSymbolList(Buffer, WriterList);
454   if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
455     warn("Profile Symbol list is not empty but the output format is not "
456          "ExtBinary format. The list will be lost in the output. ");
457 
458   Writer.setProfileSymbolList(&WriterList);
459 
460   if (CompressAllSections) {
461     if (OutputFormat != PF_Ext_Binary)
462       warn("-compress-all-section is ignored. Specify -extbinary to enable it");
463     else
464       Writer.setToCompressAllSections();
465   }
466   if (UseMD5) {
467     if (OutputFormat != PF_Ext_Binary)
468       warn("-use-md5 is ignored. Specify -extbinary to enable it");
469     else
470       Writer.setUseMD5();
471   }
472   if (PartialProfile) {
473     if (OutputFormat != PF_Ext_Binary)
474       warn("-partial-profile is ignored. Specify -extbinary to enable it");
475     else
476       Writer.setPartialProfile();
477   }
478 }
479 
480 static void
481 mergeSampleProfile(const WeightedFileVector &Inputs, SymbolRemapper *Remapper,
482                    StringRef OutputFilename, ProfileFormat OutputFormat,
483                    StringRef ProfileSymbolListFile, bool CompressAllSections,
484                    bool UseMD5, bool PartialProfile, FailureMode FailMode) {
485   using namespace sampleprof;
486   StringMap<FunctionSamples> ProfileMap;
487   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
488   LLVMContext Context;
489   sampleprof::ProfileSymbolList WriterList;
490   for (const auto &Input : Inputs) {
491     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
492     if (std::error_code EC = ReaderOrErr.getError()) {
493       warnOrExitGivenError(FailMode, EC, Input.Filename);
494       continue;
495     }
496 
497     // We need to keep the readers around until after all the files are
498     // read so that we do not lose the function names stored in each
499     // reader's memory. The function names are needed to write out the
500     // merged profile map.
501     Readers.push_back(std::move(ReaderOrErr.get()));
502     const auto Reader = Readers.back().get();
503     if (std::error_code EC = Reader->read()) {
504       warnOrExitGivenError(FailMode, EC, Input.Filename);
505       Readers.pop_back();
506       continue;
507     }
508 
509     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
510     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
511                                               E = Profiles.end();
512          I != E; ++I) {
513       sampleprof_error Result = sampleprof_error::success;
514       FunctionSamples Remapped =
515           Remapper ? remapSamples(I->second, *Remapper, Result)
516                    : FunctionSamples();
517       FunctionSamples &Samples = Remapper ? Remapped : I->second;
518       StringRef FName = Samples.getName();
519       MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight));
520       if (Result != sampleprof_error::success) {
521         std::error_code EC = make_error_code(Result);
522         handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
523       }
524     }
525 
526     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
527         Reader->getProfileSymbolList();
528     if (ReaderList)
529       WriterList.merge(*ReaderList);
530   }
531   auto WriterOrErr =
532       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
533   if (std::error_code EC = WriterOrErr.getError())
534     exitWithErrorCode(EC, OutputFilename);
535 
536   auto Writer = std::move(WriterOrErr.get());
537   // WriterList will have StringRef refering to string in Buffer.
538   // Make sure Buffer lives as long as WriterList.
539   auto Buffer = getInputFileBuf(ProfileSymbolListFile);
540   handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList,
541                         CompressAllSections, UseMD5, PartialProfile);
542   Writer->write(ProfileMap);
543 }
544 
545 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
546   StringRef WeightStr, FileName;
547   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
548 
549   uint64_t Weight;
550   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
551     exitWithError("Input weight must be a positive integer.");
552 
553   return {std::string(FileName), Weight};
554 }
555 
556 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
557   StringRef Filename = WF.Filename;
558   uint64_t Weight = WF.Weight;
559 
560   // If it's STDIN just pass it on.
561   if (Filename == "-") {
562     WNI.push_back({std::string(Filename), Weight});
563     return;
564   }
565 
566   llvm::sys::fs::file_status Status;
567   llvm::sys::fs::status(Filename, Status);
568   if (!llvm::sys::fs::exists(Status))
569     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
570                       Filename);
571   // If it's a source file, collect it.
572   if (llvm::sys::fs::is_regular_file(Status)) {
573     WNI.push_back({std::string(Filename), Weight});
574     return;
575   }
576 
577   if (llvm::sys::fs::is_directory(Status)) {
578     std::error_code EC;
579     for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
580          F != E && !EC; F.increment(EC)) {
581       if (llvm::sys::fs::is_regular_file(F->path())) {
582         addWeightedInput(WNI, {F->path(), Weight});
583       }
584     }
585     if (EC)
586       exitWithErrorCode(EC, Filename);
587   }
588 }
589 
590 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
591                                     WeightedFileVector &WFV) {
592   if (!Buffer)
593     return;
594 
595   SmallVector<StringRef, 8> Entries;
596   StringRef Data = Buffer->getBuffer();
597   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
598   for (const StringRef &FileWeightEntry : Entries) {
599     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
600     // Skip comments.
601     if (SanitizedEntry.startswith("#"))
602       continue;
603     // If there's no comma, it's an unweighted profile.
604     else if (SanitizedEntry.find(',') == StringRef::npos)
605       addWeightedInput(WFV, {std::string(SanitizedEntry), 1});
606     else
607       addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
608   }
609 }
610 
611 static int merge_main(int argc, const char *argv[]) {
612   cl::list<std::string> InputFilenames(cl::Positional,
613                                        cl::desc("<filename...>"));
614   cl::list<std::string> WeightedInputFilenames("weighted-input",
615                                                cl::desc("<weight>,<filename>"));
616   cl::opt<std::string> InputFilenamesFile(
617       "input-files", cl::init(""),
618       cl::desc("Path to file containing newline-separated "
619                "[<weight>,]<filename> entries"));
620   cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
621                                 cl::aliasopt(InputFilenamesFile));
622   cl::opt<bool> DumpInputFileList(
623       "dump-input-file-list", cl::init(false), cl::Hidden,
624       cl::desc("Dump the list of input files and their weights, then exit"));
625   cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
626                                      cl::desc("Symbol remapping file"));
627   cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
628                            cl::aliasopt(RemappingFile));
629   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
630                                       cl::init("-"), cl::Required,
631                                       cl::desc("Output file"));
632   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
633                             cl::aliasopt(OutputFilename));
634   cl::opt<ProfileKinds> ProfileKind(
635       cl::desc("Profile kind:"), cl::init(instr),
636       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
637                  clEnumVal(sample, "Sample profile")));
638   cl::opt<ProfileFormat> OutputFormat(
639       cl::desc("Format of output profile"), cl::init(PF_Binary),
640       cl::values(
641           clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
642           clEnumValN(PF_Compact_Binary, "compbinary",
643                      "Compact binary encoding"),
644           clEnumValN(PF_Ext_Binary, "extbinary", "Extensible binary encoding"),
645           clEnumValN(PF_Text, "text", "Text encoding"),
646           clEnumValN(PF_GCC, "gcc",
647                      "GCC encoding (only meaningful for -sample)")));
648   cl::opt<FailureMode> FailureMode(
649       "failure-mode", cl::init(failIfAnyAreInvalid), cl::desc("Failure mode:"),
650       cl::values(clEnumValN(failIfAnyAreInvalid, "any",
651                             "Fail if any profile is invalid."),
652                  clEnumValN(failIfAllAreInvalid, "all",
653                             "Fail only if all profiles are invalid.")));
654   cl::opt<bool> OutputSparse("sparse", cl::init(false),
655       cl::desc("Generate a sparse profile (only meaningful for -instr)"));
656   cl::opt<unsigned> NumThreads(
657       "num-threads", cl::init(0),
658       cl::desc("Number of merge threads to use (default: autodetect)"));
659   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
660                         cl::aliasopt(NumThreads));
661   cl::opt<std::string> ProfileSymbolListFile(
662       "prof-sym-list", cl::init(""),
663       cl::desc("Path to file containing the list of function symbols "
664                "used to populate profile symbol list"));
665   cl::opt<bool> CompressAllSections(
666       "compress-all-sections", cl::init(false), cl::Hidden,
667       cl::desc("Compress all sections when writing the profile (only "
668                "meaningful for -extbinary)"));
669   cl::opt<bool> UseMD5(
670       "use-md5", cl::init(false), cl::Hidden,
671       cl::desc("Choose to use MD5 to represent string in name table (only "
672                "meaningful for -extbinary)"));
673   cl::opt<bool> PartialProfile(
674       "partial-profile", cl::init(false), cl::Hidden,
675       cl::desc("Set the profile to be a partial profile (only meaningful "
676                "for -extbinary)"));
677 
678   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
679 
680   WeightedFileVector WeightedInputs;
681   for (StringRef Filename : InputFilenames)
682     addWeightedInput(WeightedInputs, {std::string(Filename), 1});
683   for (StringRef WeightedFilename : WeightedInputFilenames)
684     addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
685 
686   // Make sure that the file buffer stays alive for the duration of the
687   // weighted input vector's lifetime.
688   auto Buffer = getInputFileBuf(InputFilenamesFile);
689   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
690 
691   if (WeightedInputs.empty())
692     exitWithError("No input files specified. See " +
693                   sys::path::filename(argv[0]) + " -help");
694 
695   if (DumpInputFileList) {
696     for (auto &WF : WeightedInputs)
697       outs() << WF.Weight << "," << WF.Filename << "\n";
698     return 0;
699   }
700 
701   std::unique_ptr<SymbolRemapper> Remapper;
702   if (!RemappingFile.empty())
703     Remapper = SymbolRemapper::create(RemappingFile);
704 
705   if (ProfileKind == instr)
706     mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
707                       OutputFormat, OutputSparse, NumThreads, FailureMode);
708   else
709     mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
710                        OutputFormat, ProfileSymbolListFile, CompressAllSections,
711                        UseMD5, PartialProfile, FailureMode);
712 
713   return 0;
714 }
715 
716 /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
717 static void overlapInstrProfile(const std::string &BaseFilename,
718                                 const std::string &TestFilename,
719                                 const OverlapFuncFilters &FuncFilter,
720                                 raw_fd_ostream &OS, bool IsCS) {
721   std::mutex ErrorLock;
722   SmallSet<instrprof_error, 4> WriterErrorCodes;
723   WriterContext Context(false, ErrorLock, WriterErrorCodes);
724   WeightedFile WeightedInput{BaseFilename, 1};
725   OverlapStats Overlap;
726   Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS);
727   if (E)
728     exitWithError(std::move(E), "Error in getting profile count sums");
729   if (Overlap.Base.CountSum < 1.0f) {
730     OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
731     exit(0);
732   }
733   if (Overlap.Test.CountSum < 1.0f) {
734     OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
735     exit(0);
736   }
737   loadInput(WeightedInput, nullptr, &Context);
738   overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
739                IsCS);
740   Overlap.dump(OS);
741 }
742 
743 static int overlap_main(int argc, const char *argv[]) {
744   cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
745                                     cl::desc("<base profile file>"));
746   cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
747                                     cl::desc("<test profile file>"));
748   cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
749                               cl::desc("Output file"));
750   cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
751   cl::opt<bool> IsCS("cs", cl::init(false),
752                      cl::desc("For context sensitive counts"));
753   cl::opt<unsigned long long> ValueCutoff(
754       "value-cutoff", cl::init(-1),
755       cl::desc(
756           "Function level overlap information for every function in test "
757           "profile with max count value greater then the parameter value"));
758   cl::opt<std::string> FuncNameFilter(
759       "function",
760       cl::desc("Function level overlap information for matching functions"));
761   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
762 
763   std::error_code EC;
764   raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_Text);
765   if (EC)
766     exitWithErrorCode(EC, Output);
767 
768   overlapInstrProfile(BaseFilename, TestFilename,
769                       OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
770                       IsCS);
771 
772   return 0;
773 }
774 
775 typedef struct ValueSitesStats {
776   ValueSitesStats()
777       : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
778         TotalNumValues(0) {}
779   uint64_t TotalNumValueSites;
780   uint64_t TotalNumValueSitesWithValueProfile;
781   uint64_t TotalNumValues;
782   std::vector<unsigned> ValueSitesHistogram;
783 } ValueSitesStats;
784 
785 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
786                                   ValueSitesStats &Stats, raw_fd_ostream &OS,
787                                   InstrProfSymtab *Symtab) {
788   uint32_t NS = Func.getNumValueSites(VK);
789   Stats.TotalNumValueSites += NS;
790   for (size_t I = 0; I < NS; ++I) {
791     uint32_t NV = Func.getNumValueDataForSite(VK, I);
792     std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
793     Stats.TotalNumValues += NV;
794     if (NV) {
795       Stats.TotalNumValueSitesWithValueProfile++;
796       if (NV > Stats.ValueSitesHistogram.size())
797         Stats.ValueSitesHistogram.resize(NV, 0);
798       Stats.ValueSitesHistogram[NV - 1]++;
799     }
800 
801     uint64_t SiteSum = 0;
802     for (uint32_t V = 0; V < NV; V++)
803       SiteSum += VD[V].Count;
804     if (SiteSum == 0)
805       SiteSum = 1;
806 
807     for (uint32_t V = 0; V < NV; V++) {
808       OS << "\t[ " << format("%2u", I) << ", ";
809       if (Symtab == nullptr)
810         OS << format("%4" PRIu64, VD[V].Value);
811       else
812         OS << Symtab->getFuncName(VD[V].Value);
813       OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
814          << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
815     }
816   }
817 }
818 
819 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
820                                 ValueSitesStats &Stats) {
821   OS << "  Total number of sites: " << Stats.TotalNumValueSites << "\n";
822   OS << "  Total number of sites with values: "
823      << Stats.TotalNumValueSitesWithValueProfile << "\n";
824   OS << "  Total number of profiled values: " << Stats.TotalNumValues << "\n";
825 
826   OS << "  Value sites histogram:\n\tNumTargets, SiteCount\n";
827   for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
828     if (Stats.ValueSitesHistogram[I] > 0)
829       OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
830   }
831 }
832 
833 static int showInstrProfile(const std::string &Filename, bool ShowCounts,
834                             uint32_t TopN, bool ShowIndirectCallTargets,
835                             bool ShowMemOPSizes, bool ShowDetailedSummary,
836                             std::vector<uint32_t> DetailedSummaryCutoffs,
837                             bool ShowAllFunctions, bool ShowCS,
838                             uint64_t ValueCutoff, bool OnlyListBelow,
839                             const std::string &ShowFunction, bool TextFormat,
840                             raw_fd_ostream &OS) {
841   auto ReaderOrErr = InstrProfReader::create(Filename);
842   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
843   if (ShowDetailedSummary && Cutoffs.empty()) {
844     Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
845   }
846   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
847   if (Error E = ReaderOrErr.takeError())
848     exitWithError(std::move(E), Filename);
849 
850   auto Reader = std::move(ReaderOrErr.get());
851   bool IsIRInstr = Reader->isIRLevelProfile();
852   size_t ShownFunctions = 0;
853   size_t BelowCutoffFunctions = 0;
854   int NumVPKind = IPVK_Last - IPVK_First + 1;
855   std::vector<ValueSitesStats> VPStats(NumVPKind);
856 
857   auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
858                    const std::pair<std::string, uint64_t> &v2) {
859     return v1.second > v2.second;
860   };
861 
862   std::priority_queue<std::pair<std::string, uint64_t>,
863                       std::vector<std::pair<std::string, uint64_t>>,
864                       decltype(MinCmp)>
865       HottestFuncs(MinCmp);
866 
867   if (!TextFormat && OnlyListBelow) {
868     OS << "The list of functions with the maximum counter less than "
869        << ValueCutoff << ":\n";
870   }
871 
872   // Add marker so that IR-level instrumentation round-trips properly.
873   if (TextFormat && IsIRInstr)
874     OS << ":ir\n";
875 
876   for (const auto &Func : *Reader) {
877     if (Reader->isIRLevelProfile()) {
878       bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
879       if (FuncIsCS != ShowCS)
880         continue;
881     }
882     bool Show =
883         ShowAllFunctions || (!ShowFunction.empty() &&
884                              Func.Name.find(ShowFunction) != Func.Name.npos);
885 
886     bool doTextFormatDump = (Show && TextFormat);
887 
888     if (doTextFormatDump) {
889       InstrProfSymtab &Symtab = Reader->getSymtab();
890       InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
891                                          OS);
892       continue;
893     }
894 
895     assert(Func.Counts.size() > 0 && "function missing entry counter");
896     Builder.addRecord(Func);
897 
898     uint64_t FuncMax = 0;
899     uint64_t FuncSum = 0;
900     for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
901       FuncMax = std::max(FuncMax, Func.Counts[I]);
902       FuncSum += Func.Counts[I];
903     }
904 
905     if (FuncMax < ValueCutoff) {
906       ++BelowCutoffFunctions;
907       if (OnlyListBelow) {
908         OS << "  " << Func.Name << ": (Max = " << FuncMax
909            << " Sum = " << FuncSum << ")\n";
910       }
911       continue;
912     } else if (OnlyListBelow)
913       continue;
914 
915     if (TopN) {
916       if (HottestFuncs.size() == TopN) {
917         if (HottestFuncs.top().second < FuncMax) {
918           HottestFuncs.pop();
919           HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
920         }
921       } else
922         HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
923     }
924 
925     if (Show) {
926       if (!ShownFunctions)
927         OS << "Counters:\n";
928 
929       ++ShownFunctions;
930 
931       OS << "  " << Func.Name << ":\n"
932          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
933          << "    Counters: " << Func.Counts.size() << "\n";
934       if (!IsIRInstr)
935         OS << "    Function count: " << Func.Counts[0] << "\n";
936 
937       if (ShowIndirectCallTargets)
938         OS << "    Indirect Call Site Count: "
939            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
940 
941       uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
942       if (ShowMemOPSizes && NumMemOPCalls > 0)
943         OS << "    Number of Memory Intrinsics Calls: " << NumMemOPCalls
944            << "\n";
945 
946       if (ShowCounts) {
947         OS << "    Block counts: [";
948         size_t Start = (IsIRInstr ? 0 : 1);
949         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
950           OS << (I == Start ? "" : ", ") << Func.Counts[I];
951         }
952         OS << "]\n";
953       }
954 
955       if (ShowIndirectCallTargets) {
956         OS << "    Indirect Target Results:\n";
957         traverseAllValueSites(Func, IPVK_IndirectCallTarget,
958                               VPStats[IPVK_IndirectCallTarget], OS,
959                               &(Reader->getSymtab()));
960       }
961 
962       if (ShowMemOPSizes && NumMemOPCalls > 0) {
963         OS << "    Memory Intrinsic Size Results:\n";
964         traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
965                               nullptr);
966       }
967     }
968   }
969   if (Reader->hasError())
970     exitWithError(Reader->getError(), Filename);
971 
972   if (TextFormat)
973     return 0;
974   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
975   OS << "Instrumentation level: "
976      << (Reader->isIRLevelProfile() ? "IR" : "Front-end") << "\n";
977   if (ShowAllFunctions || !ShowFunction.empty())
978     OS << "Functions shown: " << ShownFunctions << "\n";
979   OS << "Total functions: " << PS->getNumFunctions() << "\n";
980   if (ValueCutoff > 0) {
981     OS << "Number of functions with maximum count (< " << ValueCutoff
982        << "): " << BelowCutoffFunctions << "\n";
983     OS << "Number of functions with maximum count (>= " << ValueCutoff
984        << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
985   }
986   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
987   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
988 
989   if (TopN) {
990     std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
991     while (!HottestFuncs.empty()) {
992       SortedHottestFuncs.emplace_back(HottestFuncs.top());
993       HottestFuncs.pop();
994     }
995     OS << "Top " << TopN
996        << " functions with the largest internal block counts: \n";
997     for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
998       OS << "  " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
999   }
1000 
1001   if (ShownFunctions && ShowIndirectCallTargets) {
1002     OS << "Statistics for indirect call sites profile:\n";
1003     showValueSitesStats(OS, IPVK_IndirectCallTarget,
1004                         VPStats[IPVK_IndirectCallTarget]);
1005   }
1006 
1007   if (ShownFunctions && ShowMemOPSizes) {
1008     OS << "Statistics for memory intrinsic calls sizes profile:\n";
1009     showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
1010   }
1011 
1012   if (ShowDetailedSummary) {
1013     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
1014     OS << "Total count: " << PS->getTotalCount() << "\n";
1015     PS->printDetailedSummary(OS);
1016   }
1017   return 0;
1018 }
1019 
1020 static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
1021                             raw_fd_ostream &OS) {
1022   if (!Reader->dumpSectionInfo(OS)) {
1023     WithColor::warning() << "-show-sec-info-only is only supported for "
1024                          << "sample profile in extbinary format and is "
1025                          << "ignored for other formats.\n";
1026     return;
1027   }
1028 }
1029 
1030 static int showSampleProfile(const std::string &Filename, bool ShowCounts,
1031                              bool ShowAllFunctions, bool ShowDetailedSummary,
1032                              const std::string &ShowFunction,
1033                              bool ShowProfileSymbolList,
1034                              bool ShowSectionInfoOnly, raw_fd_ostream &OS) {
1035   using namespace sampleprof;
1036   LLVMContext Context;
1037   auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
1038   if (std::error_code EC = ReaderOrErr.getError())
1039     exitWithErrorCode(EC, Filename);
1040 
1041   auto Reader = std::move(ReaderOrErr.get());
1042 
1043   if (ShowSectionInfoOnly) {
1044     showSectionInfo(Reader.get(), OS);
1045     return 0;
1046   }
1047 
1048   if (std::error_code EC = Reader->read())
1049     exitWithErrorCode(EC, Filename);
1050 
1051   if (ShowAllFunctions || ShowFunction.empty())
1052     Reader->dump(OS);
1053   else
1054     Reader->dumpFunctionProfile(ShowFunction, OS);
1055 
1056   if (ShowProfileSymbolList) {
1057     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
1058         Reader->getProfileSymbolList();
1059     ReaderList->dump(OS);
1060   }
1061 
1062   if (ShowDetailedSummary) {
1063     auto &PS = Reader->getSummary();
1064     PS.printSummary(OS);
1065     PS.printDetailedSummary(OS);
1066   }
1067 
1068   return 0;
1069 }
1070 
1071 static int show_main(int argc, const char *argv[]) {
1072   cl::opt<std::string> Filename(cl::Positional, cl::Required,
1073                                 cl::desc("<profdata-file>"));
1074 
1075   cl::opt<bool> ShowCounts("counts", cl::init(false),
1076                            cl::desc("Show counter values for shown functions"));
1077   cl::opt<bool> TextFormat(
1078       "text", cl::init(false),
1079       cl::desc("Show instr profile data in text dump format"));
1080   cl::opt<bool> ShowIndirectCallTargets(
1081       "ic-targets", cl::init(false),
1082       cl::desc("Show indirect call site target values for shown functions"));
1083   cl::opt<bool> ShowMemOPSizes(
1084       "memop-sizes", cl::init(false),
1085       cl::desc("Show the profiled sizes of the memory intrinsic calls "
1086                "for shown functions"));
1087   cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
1088                                     cl::desc("Show detailed profile summary"));
1089   cl::list<uint32_t> DetailedSummaryCutoffs(
1090       cl::CommaSeparated, "detailed-summary-cutoffs",
1091       cl::desc(
1092           "Cutoff percentages (times 10000) for generating detailed summary"),
1093       cl::value_desc("800000,901000,999999"));
1094   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
1095                                  cl::desc("Details for every function"));
1096   cl::opt<bool> ShowCS("showcs", cl::init(false),
1097                        cl::desc("Show context sensitive counts"));
1098   cl::opt<std::string> ShowFunction("function",
1099                                     cl::desc("Details for matching functions"));
1100 
1101   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
1102                                       cl::init("-"), cl::desc("Output file"));
1103   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
1104                             cl::aliasopt(OutputFilename));
1105   cl::opt<ProfileKinds> ProfileKind(
1106       cl::desc("Profile kind:"), cl::init(instr),
1107       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
1108                  clEnumVal(sample, "Sample profile")));
1109   cl::opt<uint32_t> TopNFunctions(
1110       "topn", cl::init(0),
1111       cl::desc("Show the list of functions with the largest internal counts"));
1112   cl::opt<uint32_t> ValueCutoff(
1113       "value-cutoff", cl::init(0),
1114       cl::desc("Set the count value cutoff. Functions with the maximum count "
1115                "less than this value will not be printed out. (Default is 0)"));
1116   cl::opt<bool> OnlyListBelow(
1117       "list-below-cutoff", cl::init(false),
1118       cl::desc("Only output names of functions whose max count values are "
1119                "below the cutoff value"));
1120   cl::opt<bool> ShowProfileSymbolList(
1121       "show-prof-sym-list", cl::init(false),
1122       cl::desc("Show profile symbol list if it exists in the profile. "));
1123   cl::opt<bool> ShowSectionInfoOnly(
1124       "show-sec-info-only", cl::init(false),
1125       cl::desc("Show the information of each section in the sample profile. "
1126                "The flag is only usable when the sample profile is in "
1127                "extbinary format"));
1128 
1129   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
1130 
1131   if (OutputFilename.empty())
1132     OutputFilename = "-";
1133 
1134   if (!Filename.compare(OutputFilename)) {
1135     errs() << sys::path::filename(argv[0])
1136            << ": Input file name cannot be the same as the output file name!\n";
1137     return 1;
1138   }
1139 
1140   std::error_code EC;
1141   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_Text);
1142   if (EC)
1143     exitWithErrorCode(EC, OutputFilename);
1144 
1145   if (ShowAllFunctions && !ShowFunction.empty())
1146     WithColor::warning() << "-function argument ignored: showing all functions\n";
1147 
1148   if (ProfileKind == instr)
1149     return showInstrProfile(Filename, ShowCounts, TopNFunctions,
1150                             ShowIndirectCallTargets, ShowMemOPSizes,
1151                             ShowDetailedSummary, DetailedSummaryCutoffs,
1152                             ShowAllFunctions, ShowCS, ValueCutoff,
1153                             OnlyListBelow, ShowFunction, TextFormat, OS);
1154   else
1155     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
1156                              ShowDetailedSummary, ShowFunction,
1157                              ShowProfileSymbolList, ShowSectionInfoOnly, OS);
1158 }
1159 
1160 int main(int argc, const char *argv[]) {
1161   InitLLVM X(argc, argv);
1162 
1163   StringRef ProgName(sys::path::filename(argv[0]));
1164   if (argc > 1) {
1165     int (*func)(int, const char *[]) = nullptr;
1166 
1167     if (strcmp(argv[1], "merge") == 0)
1168       func = merge_main;
1169     else if (strcmp(argv[1], "show") == 0)
1170       func = show_main;
1171     else if (strcmp(argv[1], "overlap") == 0)
1172       func = overlap_main;
1173 
1174     if (func) {
1175       std::string Invocation(ProgName.str() + " " + argv[1]);
1176       argv[1] = Invocation.c_str();
1177       return func(argc - 1, argv + 1);
1178     }
1179 
1180     if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
1181         strcmp(argv[1], "--help") == 0) {
1182 
1183       errs() << "OVERVIEW: LLVM profile data tools\n\n"
1184              << "USAGE: " << ProgName << " <command> [args...]\n"
1185              << "USAGE: " << ProgName << " <command> -help\n\n"
1186              << "See each individual command --help for more details.\n"
1187              << "Available commands: merge, show, overlap\n";
1188       return 0;
1189     }
1190   }
1191 
1192   if (argc < 2)
1193     errs() << ProgName << ": No command specified!\n";
1194   else
1195     errs() << ProgName << ": Unknown command!\n";
1196 
1197   errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
1198   return 1;
1199 }
1200