xref: /llvm-project/llvm/tools/llvm-cov/CodeCoverage.cpp (revision 50479f60c40106de3fc5a54b572ccc806f79958a)
1 //===- CodeCoverage.cpp - Coverage tool based on profiling instrumentation-===//
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 // The 'CodeCoverageTool' class implements a command line tool to analyze and
11 // report coverage information using the profiling instrumentation and code
12 // coverage mapping.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "CoverageFilters.h"
17 #include "CoverageReport.h"
18 #include "CoverageSummaryInfo.h"
19 #include "CoverageViewOptions.h"
20 #include "RenderingSupport.h"
21 #include "SourceCoverageView.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
26 #include "llvm/ProfileData/InstrProfReader.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/Program.h"
34 #include "llvm/Support/ScopedPrinter.h"
35 #include "llvm/Support/Threading.h"
36 #include "llvm/Support/ThreadPool.h"
37 #include "llvm/Support/ToolOutputFile.h"
38 #include <functional>
39 #include <system_error>
40 
41 using namespace llvm;
42 using namespace coverage;
43 
44 void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping,
45                               const CoverageViewOptions &Options,
46                               raw_ostream &OS);
47 
48 namespace {
49 /// \brief The implementation of the coverage tool.
50 class CodeCoverageTool {
51 public:
52   enum Command {
53     /// \brief The show command.
54     Show,
55     /// \brief The report command.
56     Report,
57     /// \brief The export command.
58     Export
59   };
60 
61   int run(Command Cmd, int argc, const char **argv);
62 
63 private:
64   /// \brief Print the error message to the error output stream.
65   void error(const Twine &Message, StringRef Whence = "");
66 
67   /// \brief Print the warning message to the error output stream.
68   void warning(const Twine &Message, StringRef Whence = "");
69 
70   /// \brief Convert \p Path into an absolute path and append it to the list
71   /// of collected paths.
72   void addCollectedPath(const std::string &Path);
73 
74   /// \brief If \p Path is a regular file, collect the path. If it's a
75   /// directory, recursively collect all of the paths within the directory.
76   void collectPaths(const std::string &Path);
77 
78   /// \brief Return a memory buffer for the given source file.
79   ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
80 
81   /// \brief Create source views for the expansions of the view.
82   void attachExpansionSubViews(SourceCoverageView &View,
83                                ArrayRef<ExpansionRecord> Expansions,
84                                const CoverageMapping &Coverage);
85 
86   /// \brief Create the source view of a particular function.
87   std::unique_ptr<SourceCoverageView>
88   createFunctionView(const FunctionRecord &Function,
89                      const CoverageMapping &Coverage);
90 
91   /// \brief Create the main source view of a particular source file.
92   std::unique_ptr<SourceCoverageView>
93   createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
94 
95   /// \brief Load the coverage mapping data. Return nullptr if an error occurred.
96   std::unique_ptr<CoverageMapping> load();
97 
98   /// \brief Create a mapping from files in the Coverage data to local copies
99   /// (path-equivalence).
100   void remapPathNames(const CoverageMapping &Coverage);
101 
102   /// \brief Remove input source files which aren't mapped by \p Coverage.
103   void removeUnmappedInputs(const CoverageMapping &Coverage);
104 
105   /// \brief If a demangler is available, demangle all symbol names.
106   void demangleSymbols(const CoverageMapping &Coverage);
107 
108   /// \brief Write out a source file view to the filesystem.
109   void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
110                            CoveragePrinter *Printer, bool ShowFilenames);
111 
112   typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
113 
114   int show(int argc, const char **argv,
115            CommandLineParserType commandLineParser);
116 
117   int report(int argc, const char **argv,
118              CommandLineParserType commandLineParser);
119 
120   int export_(int argc, const char **argv,
121               CommandLineParserType commandLineParser);
122 
123   std::vector<StringRef> ObjectFilenames;
124   CoverageViewOptions ViewOpts;
125   CoverageFiltersMatchAll Filters;
126 
127   /// The path to the indexed profile.
128   std::string PGOFilename;
129 
130   /// A list of input source files.
131   std::vector<std::string> SourceFiles;
132 
133   /// In -path-equivalence mode, this maps the absolute paths from the coverage
134   /// mapping data to the input source files.
135   StringMap<std::string> RemappedFilenames;
136 
137   /// The coverage data path to be remapped from, and the source path to be
138   /// remapped to, when using -path-equivalence.
139   Optional<std::pair<std::string, std::string>> PathRemapping;
140 
141   /// The architecture the coverage mapping data targets.
142   std::vector<StringRef> CoverageArches;
143 
144   /// A cache for demangled symbols.
145   DemangleCache DC;
146 
147   /// A lock which guards printing to stderr.
148   std::mutex ErrsLock;
149 
150   /// A container for input source file buffers.
151   std::mutex LoadedSourceFilesLock;
152   std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
153       LoadedSourceFiles;
154 
155   /// Whitelist from -name-whitelist to be used for filtering.
156   std::unique_ptr<SpecialCaseList> NameWhitelist;
157 };
158 }
159 
160 static std::string getErrorString(const Twine &Message, StringRef Whence,
161                                   bool Warning) {
162   std::string Str = (Warning ? "warning" : "error");
163   Str += ": ";
164   if (!Whence.empty())
165     Str += Whence.str() + ": ";
166   Str += Message.str() + "\n";
167   return Str;
168 }
169 
170 void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
171   std::unique_lock<std::mutex> Guard{ErrsLock};
172   ViewOpts.colored_ostream(errs(), raw_ostream::RED)
173       << getErrorString(Message, Whence, false);
174 }
175 
176 void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
177   std::unique_lock<std::mutex> Guard{ErrsLock};
178   ViewOpts.colored_ostream(errs(), raw_ostream::RED)
179       << getErrorString(Message, Whence, true);
180 }
181 
182 void CodeCoverageTool::addCollectedPath(const std::string &Path) {
183   SmallString<128> EffectivePath(Path);
184   if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
185     error(EC.message(), Path);
186     return;
187   }
188   sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true);
189   SourceFiles.emplace_back(EffectivePath.str());
190 }
191 
192 void CodeCoverageTool::collectPaths(const std::string &Path) {
193   llvm::sys::fs::file_status Status;
194   llvm::sys::fs::status(Path, Status);
195   if (!llvm::sys::fs::exists(Status)) {
196     if (PathRemapping)
197       addCollectedPath(Path);
198     else
199       error("Missing source file", Path);
200     return;
201   }
202 
203   if (llvm::sys::fs::is_regular_file(Status)) {
204     addCollectedPath(Path);
205     return;
206   }
207 
208   if (llvm::sys::fs::is_directory(Status)) {
209     std::error_code EC;
210     for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
211          F != E && !EC; F.increment(EC)) {
212       if (llvm::sys::fs::is_regular_file(F->path()))
213         addCollectedPath(F->path());
214     }
215     if (EC)
216       warning(EC.message(), Path);
217   }
218 }
219 
220 ErrorOr<const MemoryBuffer &>
221 CodeCoverageTool::getSourceFile(StringRef SourceFile) {
222   // If we've remapped filenames, look up the real location for this file.
223   std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
224   if (!RemappedFilenames.empty()) {
225     auto Loc = RemappedFilenames.find(SourceFile);
226     if (Loc != RemappedFilenames.end())
227       SourceFile = Loc->second;
228   }
229   for (const auto &Files : LoadedSourceFiles)
230     if (sys::fs::equivalent(SourceFile, Files.first))
231       return *Files.second;
232   auto Buffer = MemoryBuffer::getFile(SourceFile);
233   if (auto EC = Buffer.getError()) {
234     error(EC.message(), SourceFile);
235     return EC;
236   }
237   LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
238   return *LoadedSourceFiles.back().second;
239 }
240 
241 void CodeCoverageTool::attachExpansionSubViews(
242     SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
243     const CoverageMapping &Coverage) {
244   if (!ViewOpts.ShowExpandedRegions)
245     return;
246   for (const auto &Expansion : Expansions) {
247     auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
248     if (ExpansionCoverage.empty())
249       continue;
250     auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
251     if (!SourceBuffer)
252       continue;
253 
254     auto SubViewExpansions = ExpansionCoverage.getExpansions();
255     auto SubView =
256         SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
257                                    ViewOpts, std::move(ExpansionCoverage));
258     attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
259     View.addExpansion(Expansion.Region, std::move(SubView));
260   }
261 }
262 
263 std::unique_ptr<SourceCoverageView>
264 CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
265                                      const CoverageMapping &Coverage) {
266   auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
267   if (FunctionCoverage.empty())
268     return nullptr;
269   auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
270   if (!SourceBuffer)
271     return nullptr;
272 
273   auto Expansions = FunctionCoverage.getExpansions();
274   auto View = SourceCoverageView::create(DC.demangle(Function.Name),
275                                          SourceBuffer.get(), ViewOpts,
276                                          std::move(FunctionCoverage));
277   attachExpansionSubViews(*View, Expansions, Coverage);
278 
279   return View;
280 }
281 
282 std::unique_ptr<SourceCoverageView>
283 CodeCoverageTool::createSourceFileView(StringRef SourceFile,
284                                        const CoverageMapping &Coverage) {
285   auto SourceBuffer = getSourceFile(SourceFile);
286   if (!SourceBuffer)
287     return nullptr;
288   auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
289   if (FileCoverage.empty())
290     return nullptr;
291 
292   auto Expansions = FileCoverage.getExpansions();
293   auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
294                                          ViewOpts, std::move(FileCoverage));
295   attachExpansionSubViews(*View, Expansions, Coverage);
296   if (!ViewOpts.ShowFunctionInstantiations)
297     return View;
298 
299   for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) {
300     // Skip functions which have a single instantiation.
301     if (Group.size() < 2)
302       continue;
303 
304     for (const FunctionRecord *Function : Group.getInstantiations()) {
305       std::unique_ptr<SourceCoverageView> SubView{nullptr};
306 
307       StringRef Funcname = DC.demangle(Function->Name);
308 
309       if (Function->ExecutionCount > 0) {
310         auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
311         auto SubViewExpansions = SubViewCoverage.getExpansions();
312         SubView = SourceCoverageView::create(
313             Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
314         attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
315       }
316 
317       unsigned FileID = Function->CountedRegions.front().FileID;
318       unsigned Line = 0;
319       for (const auto &CR : Function->CountedRegions)
320         if (CR.FileID == FileID)
321           Line = std::max(CR.LineEnd, Line);
322       View->addInstantiation(Funcname, Line, std::move(SubView));
323     }
324   }
325   return View;
326 }
327 
328 static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
329   sys::fs::file_status Status;
330   if (sys::fs::status(LHS, Status))
331     return false;
332   auto LHSTime = Status.getLastModificationTime();
333   if (sys::fs::status(RHS, Status))
334     return false;
335   auto RHSTime = Status.getLastModificationTime();
336   return LHSTime > RHSTime;
337 }
338 
339 std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
340   for (StringRef ObjectFilename : ObjectFilenames)
341     if (modifiedTimeGT(ObjectFilename, PGOFilename))
342       warning("profile data may be out of date - object is newer",
343               ObjectFilename);
344   auto CoverageOrErr =
345       CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches);
346   if (Error E = CoverageOrErr.takeError()) {
347     error("Failed to load coverage: " + toString(std::move(E)),
348           join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "));
349     return nullptr;
350   }
351   auto Coverage = std::move(CoverageOrErr.get());
352   unsigned Mismatched = Coverage->getMismatchedCount();
353   if (Mismatched)
354     warning(utostr(Mismatched) + " functions have mismatched data");
355 
356   remapPathNames(*Coverage);
357 
358   if (!SourceFiles.empty())
359     removeUnmappedInputs(*Coverage);
360 
361   demangleSymbols(*Coverage);
362 
363   return Coverage;
364 }
365 
366 void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
367   if (!PathRemapping)
368     return;
369 
370   // Convert remapping paths to native paths with trailing seperators.
371   auto nativeWithTrailing = [](StringRef Path) -> std::string {
372     if (Path.empty())
373       return "";
374     SmallString<128> NativePath;
375     sys::path::native(Path, NativePath);
376     if (!sys::path::is_separator(NativePath.back()))
377       NativePath += sys::path::get_separator();
378     return NativePath.c_str();
379   };
380   std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
381   std::string RemapTo = nativeWithTrailing(PathRemapping->second);
382 
383   // Create a mapping from coverage data file paths to local paths.
384   for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
385     SmallString<128> NativeFilename;
386     sys::path::native(Filename, NativeFilename);
387     if (NativeFilename.startswith(RemapFrom)) {
388       RemappedFilenames[Filename] =
389           RemapTo + NativeFilename.substr(RemapFrom.size()).str();
390     }
391   }
392 
393   // Convert input files from local paths to coverage data file paths.
394   StringMap<std::string> InvRemappedFilenames;
395   for (const auto &RemappedFilename : RemappedFilenames)
396     InvRemappedFilenames[RemappedFilename.getValue()] = RemappedFilename.getKey();
397 
398   for (std::string &Filename : SourceFiles) {
399     SmallString<128> NativeFilename;
400     sys::path::native(Filename, NativeFilename);
401     auto CovFileName = InvRemappedFilenames.find(NativeFilename);
402     if (CovFileName != InvRemappedFilenames.end())
403       Filename = CovFileName->second;
404   }
405 }
406 
407 void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
408   std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
409 
410   auto UncoveredFilesIt = SourceFiles.end();
411   // The user may have specified source files which aren't in the coverage
412   // mapping. Filter these files away.
413   UncoveredFilesIt = std::remove_if(
414       SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
415         return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
416                                    SF);
417       });
418 
419   SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
420 }
421 
422 void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
423   if (!ViewOpts.hasDemangler())
424     return;
425 
426   // Pass function names to the demangler in a temporary file.
427   int InputFD;
428   SmallString<256> InputPath;
429   std::error_code EC =
430       sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
431   if (EC) {
432     error(InputPath, EC.message());
433     return;
434   }
435   tool_output_file InputTOF{InputPath, InputFD};
436 
437   unsigned NumSymbols = 0;
438   for (const auto &Function : Coverage.getCoveredFunctions()) {
439     InputTOF.os() << Function.Name << '\n';
440     ++NumSymbols;
441   }
442   InputTOF.os().close();
443 
444   // Use another temporary file to store the demangler's output.
445   int OutputFD;
446   SmallString<256> OutputPath;
447   EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
448                                     OutputPath);
449   if (EC) {
450     error(OutputPath, EC.message());
451     return;
452   }
453   tool_output_file OutputTOF{OutputPath, OutputFD};
454   OutputTOF.os().close();
455 
456   // Invoke the demangler.
457   std::vector<const char *> ArgsV;
458   for (const std::string &Arg : ViewOpts.DemanglerOpts)
459     ArgsV.push_back(Arg.c_str());
460   ArgsV.push_back(nullptr);
461   StringRef InputPathRef = InputPath.str();
462   StringRef OutputPathRef = OutputPath.str();
463   StringRef StderrRef;
464   const StringRef *Redirects[] = {&InputPathRef, &OutputPathRef, &StderrRef};
465   std::string ErrMsg;
466   int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
467                                /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
468                                /*memoryLimit=*/0, &ErrMsg);
469   if (RC) {
470     error(ErrMsg, ViewOpts.DemanglerOpts[0]);
471     return;
472   }
473 
474   // Parse the demangler's output.
475   auto BufOrError = MemoryBuffer::getFile(OutputPath);
476   if (!BufOrError) {
477     error(OutputPath, BufOrError.getError().message());
478     return;
479   }
480 
481   std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
482 
483   SmallVector<StringRef, 8> Symbols;
484   StringRef DemanglerData = DemanglerBuf->getBuffer();
485   DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
486                       /*KeepEmpty=*/false);
487   if (Symbols.size() != NumSymbols) {
488     error("Demangler did not provide expected number of symbols");
489     return;
490   }
491 
492   // Cache the demangled names.
493   unsigned I = 0;
494   for (const auto &Function : Coverage.getCoveredFunctions())
495     // On Windows, lines in the demangler's output file end with "\r\n".
496     // Splitting by '\n' keeps '\r's, so cut them now.
497     DC.DemangledNames[Function.Name] = Symbols[I++].rtrim();
498 }
499 
500 void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
501                                            CoverageMapping *Coverage,
502                                            CoveragePrinter *Printer,
503                                            bool ShowFilenames) {
504   auto View = createSourceFileView(SourceFile, *Coverage);
505   if (!View) {
506     warning("The file '" + SourceFile + "' isn't covered.");
507     return;
508   }
509 
510   auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
511   if (Error E = OSOrErr.takeError()) {
512     error("Could not create view file!", toString(std::move(E)));
513     return;
514   }
515   auto OS = std::move(OSOrErr.get());
516 
517   View->print(*OS.get(), /*Wholefile=*/true,
518               /*ShowSourceName=*/ShowFilenames);
519   Printer->closeViewFile(std::move(OS));
520 }
521 
522 int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
523   cl::opt<std::string> CovFilename(
524       cl::Positional, cl::desc("Covered executable or object file."));
525 
526   cl::list<std::string> CovFilenames(
527       "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
528       cl::CommaSeparated);
529 
530   cl::list<std::string> InputSourceFiles(
531       cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
532 
533   cl::opt<bool> DebugDumpCollectedPaths(
534       "dump-collected-paths", cl::Optional, cl::Hidden,
535       cl::desc("Show the collected paths to source files"));
536 
537   cl::opt<std::string, true> PGOFilename(
538       "instr-profile", cl::Required, cl::location(this->PGOFilename),
539       cl::desc(
540           "File with the profile data obtained after an instrumented run"));
541 
542   cl::list<std::string> Arches(
543       "arch", cl::desc("architectures of the coverage mapping binaries"));
544 
545   cl::opt<bool> DebugDump("dump", cl::Optional,
546                           cl::desc("Show internal debug dump"));
547 
548   cl::opt<CoverageViewOptions::OutputFormat> Format(
549       "format", cl::desc("Output format for line-based coverage reports"),
550       cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
551                             "Text output"),
552                  clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
553                             "HTML output")),
554       cl::init(CoverageViewOptions::OutputFormat::Text));
555 
556   cl::opt<std::string> PathRemap(
557       "path-equivalence", cl::Optional,
558       cl::desc("<from>,<to> Map coverage data paths to local source file "
559                "paths"));
560 
561   cl::OptionCategory FilteringCategory("Function filtering options");
562 
563   cl::list<std::string> NameFilters(
564       "name", cl::Optional,
565       cl::desc("Show code coverage only for functions with the given name"),
566       cl::ZeroOrMore, cl::cat(FilteringCategory));
567 
568   cl::list<std::string> NameFilterFiles(
569       "name-whitelist", cl::Optional,
570       cl::desc("Show code coverage only for functions listed in the given "
571                "file"),
572       cl::ZeroOrMore, cl::cat(FilteringCategory));
573 
574   cl::list<std::string> NameRegexFilters(
575       "name-regex", cl::Optional,
576       cl::desc("Show code coverage only for functions that match the given "
577                "regular expression"),
578       cl::ZeroOrMore, cl::cat(FilteringCategory));
579 
580   cl::opt<double> RegionCoverageLtFilter(
581       "region-coverage-lt", cl::Optional,
582       cl::desc("Show code coverage only for functions with region coverage "
583                "less than the given threshold"),
584       cl::cat(FilteringCategory));
585 
586   cl::opt<double> RegionCoverageGtFilter(
587       "region-coverage-gt", cl::Optional,
588       cl::desc("Show code coverage only for functions with region coverage "
589                "greater than the given threshold"),
590       cl::cat(FilteringCategory));
591 
592   cl::opt<double> LineCoverageLtFilter(
593       "line-coverage-lt", cl::Optional,
594       cl::desc("Show code coverage only for functions with line coverage less "
595                "than the given threshold"),
596       cl::cat(FilteringCategory));
597 
598   cl::opt<double> LineCoverageGtFilter(
599       "line-coverage-gt", cl::Optional,
600       cl::desc("Show code coverage only for functions with line coverage "
601                "greater than the given threshold"),
602       cl::cat(FilteringCategory));
603 
604   cl::opt<cl::boolOrDefault> UseColor(
605       "use-color", cl::desc("Emit colored output (default=autodetect)"),
606       cl::init(cl::BOU_UNSET));
607 
608   cl::list<std::string> DemanglerOpts(
609       "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
610 
611   cl::opt<bool> RegionSummary(
612       "show-region-summary", cl::Optional,
613       cl::desc("Show region statistics in summary table"),
614       cl::init(true));
615 
616   cl::opt<bool> InstantiationSummary(
617       "show-instantiation-summary", cl::Optional,
618       cl::desc("Show instantiation statistics in summary table"));
619 
620   auto commandLineParser = [&, this](int argc, const char **argv) -> int {
621     cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
622     ViewOpts.Debug = DebugDump;
623 
624     if (!CovFilename.empty())
625       ObjectFilenames.emplace_back(CovFilename);
626     for (const std::string &Filename : CovFilenames)
627       ObjectFilenames.emplace_back(Filename);
628     if (ObjectFilenames.empty()) {
629       errs() << "No filenames specified!\n";
630       ::exit(1);
631     }
632 
633     ViewOpts.Format = Format;
634     switch (ViewOpts.Format) {
635     case CoverageViewOptions::OutputFormat::Text:
636       ViewOpts.Colors = UseColor == cl::BOU_UNSET
637                             ? sys::Process::StandardOutHasColors()
638                             : UseColor == cl::BOU_TRUE;
639       break;
640     case CoverageViewOptions::OutputFormat::HTML:
641       if (UseColor == cl::BOU_FALSE)
642         errs() << "Color output cannot be disabled when generating html.\n";
643       ViewOpts.Colors = true;
644       break;
645     }
646 
647     // If path-equivalence was given and is a comma seperated pair then set
648     // PathRemapping.
649     auto EquivPair = StringRef(PathRemap).split(',');
650     if (!(EquivPair.first.empty() && EquivPair.second.empty()))
651       PathRemapping = EquivPair;
652 
653     // If a demangler is supplied, check if it exists and register it.
654     if (DemanglerOpts.size()) {
655       auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
656       if (!DemanglerPathOrErr) {
657         error("Could not find the demangler!",
658               DemanglerPathOrErr.getError().message());
659         return 1;
660       }
661       DemanglerOpts[0] = *DemanglerPathOrErr;
662       ViewOpts.DemanglerOpts.swap(DemanglerOpts);
663     }
664 
665     // Read in -name-whitelist files.
666     if (!NameFilterFiles.empty()) {
667       std::string SpecialCaseListErr;
668       NameWhitelist =
669           SpecialCaseList::create(NameFilterFiles, SpecialCaseListErr);
670       if (!NameWhitelist)
671         error(SpecialCaseListErr);
672     }
673 
674     // Create the function filters
675     if (!NameFilters.empty() || NameWhitelist || !NameRegexFilters.empty()) {
676       auto NameFilterer = llvm::make_unique<CoverageFilters>();
677       for (const auto &Name : NameFilters)
678         NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
679       if (NameWhitelist)
680         NameFilterer->push_back(
681             llvm::make_unique<NameWhitelistCoverageFilter>(*NameWhitelist));
682       for (const auto &Regex : NameRegexFilters)
683         NameFilterer->push_back(
684             llvm::make_unique<NameRegexCoverageFilter>(Regex));
685       Filters.push_back(std::move(NameFilterer));
686     }
687     if (RegionCoverageLtFilter.getNumOccurrences() ||
688         RegionCoverageGtFilter.getNumOccurrences() ||
689         LineCoverageLtFilter.getNumOccurrences() ||
690         LineCoverageGtFilter.getNumOccurrences()) {
691       auto StatFilterer = llvm::make_unique<CoverageFilters>();
692       if (RegionCoverageLtFilter.getNumOccurrences())
693         StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
694             RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
695       if (RegionCoverageGtFilter.getNumOccurrences())
696         StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
697             RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
698       if (LineCoverageLtFilter.getNumOccurrences())
699         StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
700             LineCoverageFilter::LessThan, LineCoverageLtFilter));
701       if (LineCoverageGtFilter.getNumOccurrences())
702         StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
703             RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
704       Filters.push_back(std::move(StatFilterer));
705     }
706 
707     if (!Arches.empty()) {
708       for (const std::string &Arch : Arches) {
709         if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
710           error("Unknown architecture: " + Arch);
711           return 1;
712         }
713         CoverageArches.emplace_back(Arch);
714       }
715       if (CoverageArches.size() != ObjectFilenames.size()) {
716         error("Number of architectures doesn't match the number of objects");
717         return 1;
718       }
719     }
720 
721     for (const std::string &File : InputSourceFiles)
722       collectPaths(File);
723 
724     if (DebugDumpCollectedPaths) {
725       for (const std::string &SF : SourceFiles)
726         outs() << SF << '\n';
727       ::exit(0);
728     }
729 
730     ViewOpts.ShowRegionSummary = RegionSummary;
731     ViewOpts.ShowInstantiationSummary = InstantiationSummary;
732 
733     return 0;
734   };
735 
736   switch (Cmd) {
737   case Show:
738     return show(argc, argv, commandLineParser);
739   case Report:
740     return report(argc, argv, commandLineParser);
741   case Export:
742     return export_(argc, argv, commandLineParser);
743   }
744   return 0;
745 }
746 
747 int CodeCoverageTool::show(int argc, const char **argv,
748                            CommandLineParserType commandLineParser) {
749 
750   cl::OptionCategory ViewCategory("Viewing options");
751 
752   cl::opt<bool> ShowLineExecutionCounts(
753       "show-line-counts", cl::Optional,
754       cl::desc("Show the execution counts for each line"), cl::init(true),
755       cl::cat(ViewCategory));
756 
757   cl::opt<bool> ShowRegions(
758       "show-regions", cl::Optional,
759       cl::desc("Show the execution counts for each region"),
760       cl::cat(ViewCategory));
761 
762   cl::opt<bool> ShowBestLineRegionsCounts(
763       "show-line-counts-or-regions", cl::Optional,
764       cl::desc("Show the execution counts for each line, or the execution "
765                "counts for each region on lines that have multiple regions"),
766       cl::cat(ViewCategory));
767 
768   cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
769                                cl::desc("Show expanded source regions"),
770                                cl::cat(ViewCategory));
771 
772   cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
773                                    cl::desc("Show function instantiations"),
774                                    cl::init(true), cl::cat(ViewCategory));
775 
776   cl::opt<std::string> ShowOutputDirectory(
777       "output-dir", cl::init(""),
778       cl::desc("Directory in which coverage information is written out"));
779   cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
780                                  cl::aliasopt(ShowOutputDirectory));
781 
782   cl::opt<uint32_t> TabSize(
783       "tab-size", cl::init(2),
784       cl::desc(
785           "Set tab expansion size for html coverage reports (default = 2)"));
786 
787   cl::opt<std::string> ProjectTitle(
788       "project-title", cl::Optional,
789       cl::desc("Set project title for the coverage report"));
790 
791   cl::opt<unsigned> NumThreads(
792       "num-threads", cl::init(0),
793       cl::desc("Number of merge threads to use (default: autodetect)"));
794   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
795                         cl::aliasopt(NumThreads));
796 
797   auto Err = commandLineParser(argc, argv);
798   if (Err)
799     return Err;
800 
801   ViewOpts.ShowLineNumbers = true;
802   ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
803                            !ShowRegions || ShowBestLineRegionsCounts;
804   ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
805   ViewOpts.ShowExpandedRegions = ShowExpansions;
806   ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
807   ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
808   ViewOpts.TabSize = TabSize;
809   ViewOpts.ProjectTitle = ProjectTitle;
810 
811   if (ViewOpts.hasOutputDirectory()) {
812     if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
813       error("Could not create output directory!", E.message());
814       return 1;
815     }
816   }
817 
818   sys::fs::file_status Status;
819   if (sys::fs::status(PGOFilename, Status)) {
820     error("profdata file error: can not get the file status. \n");
821     return 1;
822   }
823 
824   auto ModifiedTime = Status.getLastModificationTime();
825   std::string ModifiedTimeStr = to_string(ModifiedTime);
826   size_t found = ModifiedTimeStr.rfind(':');
827   ViewOpts.CreatedTimeStr = (found != std::string::npos)
828                                 ? "Created: " + ModifiedTimeStr.substr(0, found)
829                                 : "Created: " + ModifiedTimeStr;
830 
831   auto Coverage = load();
832   if (!Coverage)
833     return 1;
834 
835   auto Printer = CoveragePrinter::create(ViewOpts);
836 
837   if (!Filters.empty()) {
838     auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
839     if (Error E = OSOrErr.takeError()) {
840       error("Could not create view file!", toString(std::move(E)));
841       return 1;
842     }
843     auto OS = std::move(OSOrErr.get());
844 
845     // Show functions.
846     for (const auto &Function : Coverage->getCoveredFunctions()) {
847       if (!Filters.matches(Function))
848         continue;
849 
850       auto mainView = createFunctionView(Function, *Coverage);
851       if (!mainView) {
852         warning("Could not read coverage for '" + Function.Name + "'.");
853         continue;
854       }
855 
856       mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
857     }
858 
859     Printer->closeViewFile(std::move(OS));
860     return 0;
861   }
862 
863   // Show files
864   bool ShowFilenames =
865       (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
866       (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
867 
868   if (SourceFiles.empty())
869     // Get the source files from the function coverage mapping.
870     for (StringRef Filename : Coverage->getUniqueSourceFiles())
871       SourceFiles.push_back(Filename);
872 
873   // Create an index out of the source files.
874   if (ViewOpts.hasOutputDirectory()) {
875     if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) {
876       error("Could not create index file!", toString(std::move(E)));
877       return 1;
878     }
879   }
880 
881   // If NumThreads is not specified, auto-detect a good default.
882   if (NumThreads == 0)
883     NumThreads =
884         std::max(1U, std::min(llvm::heavyweight_hardware_concurrency(),
885                               unsigned(SourceFiles.size())));
886 
887   if (!ViewOpts.hasOutputDirectory() || NumThreads == 1) {
888     for (const std::string &SourceFile : SourceFiles)
889       writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
890                           ShowFilenames);
891   } else {
892     // In -output-dir mode, it's safe to use multiple threads to print files.
893     ThreadPool Pool(NumThreads);
894     for (const std::string &SourceFile : SourceFiles)
895       Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
896                  Coverage.get(), Printer.get(), ShowFilenames);
897     Pool.wait();
898   }
899 
900   return 0;
901 }
902 
903 int CodeCoverageTool::report(int argc, const char **argv,
904                              CommandLineParserType commandLineParser) {
905   cl::opt<bool> ShowFunctionSummaries(
906       "show-functions", cl::Optional, cl::init(false),
907       cl::desc("Show coverage summaries for each function"));
908 
909   auto Err = commandLineParser(argc, argv);
910   if (Err)
911     return Err;
912 
913   if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
914     error("HTML output for summary reports is not yet supported.");
915     return 1;
916   }
917 
918   auto Coverage = load();
919   if (!Coverage)
920     return 1;
921 
922   CoverageReport Report(ViewOpts, *Coverage.get());
923   if (!ShowFunctionSummaries)
924     Report.renderFileReports(llvm::outs());
925   else
926     Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
927   return 0;
928 }
929 
930 int CodeCoverageTool::export_(int argc, const char **argv,
931                               CommandLineParserType commandLineParser) {
932 
933   auto Err = commandLineParser(argc, argv);
934   if (Err)
935     return Err;
936 
937   if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text) {
938     error("Coverage data can only be exported as textual JSON.");
939     return 1;
940   }
941 
942   auto Coverage = load();
943   if (!Coverage) {
944     error("Could not load coverage information");
945     return 1;
946   }
947 
948   exportCoverageDataToJson(*Coverage.get(), ViewOpts, outs());
949 
950   return 0;
951 }
952 
953 int showMain(int argc, const char *argv[]) {
954   CodeCoverageTool Tool;
955   return Tool.run(CodeCoverageTool::Show, argc, argv);
956 }
957 
958 int reportMain(int argc, const char *argv[]) {
959   CodeCoverageTool Tool;
960   return Tool.run(CodeCoverageTool::Report, argc, argv);
961 }
962 
963 int exportMain(int argc, const char *argv[]) {
964   CodeCoverageTool Tool;
965   return Tool.run(CodeCoverageTool::Export, argc, argv);
966 }
967