xref: /freebsd/contrib/llvm-project/llvm/tools/llvm-cov/CodeCoverage.cpp (revision 734e82fe33aa764367791a7d603b383996c6b40b)
1 //===- CodeCoverage.cpp - Coverage tool based on profiling instrumentation-===//
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 // The 'CodeCoverageTool' class implements a command line tool to analyze and
10 // report coverage information using the profiling instrumentation and code
11 // coverage mapping.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "CoverageExporterJson.h"
16 #include "CoverageExporterLcov.h"
17 #include "CoverageFilters.h"
18 #include "CoverageReport.h"
19 #include "CoverageSummaryInfo.h"
20 #include "CoverageViewOptions.h"
21 #include "RenderingSupport.h"
22 #include "SourceCoverageView.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Debuginfod/BuildIDFetcher.h"
27 #include "llvm/Debuginfod/Debuginfod.h"
28 #include "llvm/Debuginfod/HTTPClient.h"
29 #include "llvm/Object/BuildID.h"
30 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
31 #include "llvm/ProfileData/InstrProfReader.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Format.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/Process.h"
38 #include "llvm/Support/Program.h"
39 #include "llvm/Support/ScopedPrinter.h"
40 #include "llvm/Support/SpecialCaseList.h"
41 #include "llvm/Support/ThreadPool.h"
42 #include "llvm/Support/Threading.h"
43 #include "llvm/Support/ToolOutputFile.h"
44 #include "llvm/Support/VirtualFileSystem.h"
45 
46 #include <functional>
47 #include <map>
48 #include <optional>
49 #include <system_error>
50 
51 using namespace llvm;
52 using namespace coverage;
53 
54 void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping,
55                               const CoverageViewOptions &Options,
56                               raw_ostream &OS);
57 
58 namespace {
59 /// The implementation of the coverage tool.
60 class CodeCoverageTool {
61 public:
62   enum Command {
63     /// The show command.
64     Show,
65     /// The report command.
66     Report,
67     /// The export command.
68     Export
69   };
70 
71   int run(Command Cmd, int argc, const char **argv);
72 
73 private:
74   /// Print the error message to the error output stream.
75   void error(const Twine &Message, StringRef Whence = "");
76 
77   /// Print the warning message to the error output stream.
78   void warning(const Twine &Message, StringRef Whence = "");
79 
80   /// Convert \p Path into an absolute path and append it to the list
81   /// of collected paths.
82   void addCollectedPath(const std::string &Path);
83 
84   /// If \p Path is a regular file, collect the path. If it's a
85   /// directory, recursively collect all of the paths within the directory.
86   void collectPaths(const std::string &Path);
87 
88   /// Check if the two given files are the same file.
89   bool isEquivalentFile(StringRef FilePath1, StringRef FilePath2);
90 
91   /// Retrieve a file status with a cache.
92   std::optional<sys::fs::file_status> getFileStatus(StringRef FilePath);
93 
94   /// Return a memory buffer for the given source file.
95   ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
96 
97   /// Create source views for the expansions of the view.
98   void attachExpansionSubViews(SourceCoverageView &View,
99                                ArrayRef<ExpansionRecord> Expansions,
100                                const CoverageMapping &Coverage);
101 
102   /// Create source views for the branches of the view.
103   void attachBranchSubViews(SourceCoverageView &View, StringRef SourceName,
104                             ArrayRef<CountedRegion> Branches,
105                             const MemoryBuffer &File,
106                             CoverageData &CoverageInfo);
107 
108   /// Create the source view of a particular function.
109   std::unique_ptr<SourceCoverageView>
110   createFunctionView(const FunctionRecord &Function,
111                      const CoverageMapping &Coverage);
112 
113   /// Create the main source view of a particular source file.
114   std::unique_ptr<SourceCoverageView>
115   createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
116 
117   /// Load the coverage mapping data. Return nullptr if an error occurred.
118   std::unique_ptr<CoverageMapping> load();
119 
120   /// Create a mapping from files in the Coverage data to local copies
121   /// (path-equivalence).
122   void remapPathNames(const CoverageMapping &Coverage);
123 
124   /// Remove input source files which aren't mapped by \p Coverage.
125   void removeUnmappedInputs(const CoverageMapping &Coverage);
126 
127   /// If a demangler is available, demangle all symbol names.
128   void demangleSymbols(const CoverageMapping &Coverage);
129 
130   /// Write out a source file view to the filesystem.
131   void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
132                            CoveragePrinter *Printer, bool ShowFilenames);
133 
134   typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
135 
136   int doShow(int argc, const char **argv,
137              CommandLineParserType commandLineParser);
138 
139   int doReport(int argc, const char **argv,
140                CommandLineParserType commandLineParser);
141 
142   int doExport(int argc, const char **argv,
143                CommandLineParserType commandLineParser);
144 
145   std::vector<StringRef> ObjectFilenames;
146   CoverageViewOptions ViewOpts;
147   CoverageFiltersMatchAll Filters;
148   CoverageFilters IgnoreFilenameFilters;
149 
150   /// True if InputSourceFiles are provided.
151   bool HadSourceFiles = false;
152 
153   /// The path to the indexed profile.
154   std::string PGOFilename;
155 
156   /// A list of input source files.
157   std::vector<std::string> SourceFiles;
158 
159   /// In -path-equivalence mode, this maps the absolute paths from the coverage
160   /// mapping data to the input source files.
161   StringMap<std::string> RemappedFilenames;
162 
163   /// The coverage data path to be remapped from, and the source path to be
164   /// remapped to, when using -path-equivalence.
165   std::optional<std::pair<std::string, std::string>> PathRemapping;
166 
167   /// File status cache used when finding the same file.
168   StringMap<std::optional<sys::fs::file_status>> FileStatusCache;
169 
170   /// The architecture the coverage mapping data targets.
171   std::vector<StringRef> CoverageArches;
172 
173   /// A cache for demangled symbols.
174   DemangleCache DC;
175 
176   /// A lock which guards printing to stderr.
177   std::mutex ErrsLock;
178 
179   /// A container for input source file buffers.
180   std::mutex LoadedSourceFilesLock;
181   std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
182       LoadedSourceFiles;
183 
184   /// Allowlist from -name-allowlist to be used for filtering.
185   std::unique_ptr<SpecialCaseList> NameAllowlist;
186 
187   std::unique_ptr<object::BuildIDFetcher> BIDFetcher;
188 };
189 }
190 
191 static std::string getErrorString(const Twine &Message, StringRef Whence,
192                                   bool Warning) {
193   std::string Str = (Warning ? "warning" : "error");
194   Str += ": ";
195   if (!Whence.empty())
196     Str += Whence.str() + ": ";
197   Str += Message.str() + "\n";
198   return Str;
199 }
200 
201 void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
202   std::unique_lock<std::mutex> Guard{ErrsLock};
203   ViewOpts.colored_ostream(errs(), raw_ostream::RED)
204       << getErrorString(Message, Whence, false);
205 }
206 
207 void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
208   std::unique_lock<std::mutex> Guard{ErrsLock};
209   ViewOpts.colored_ostream(errs(), raw_ostream::RED)
210       << getErrorString(Message, Whence, true);
211 }
212 
213 void CodeCoverageTool::addCollectedPath(const std::string &Path) {
214   SmallString<128> EffectivePath(Path);
215   if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
216     error(EC.message(), Path);
217     return;
218   }
219   sys::path::remove_dots(EffectivePath, /*remove_dot_dot=*/true);
220   if (!IgnoreFilenameFilters.matchesFilename(EffectivePath))
221     SourceFiles.emplace_back(EffectivePath.str());
222   HadSourceFiles = !SourceFiles.empty();
223 }
224 
225 void CodeCoverageTool::collectPaths(const std::string &Path) {
226   llvm::sys::fs::file_status Status;
227   llvm::sys::fs::status(Path, Status);
228   if (!llvm::sys::fs::exists(Status)) {
229     if (PathRemapping)
230       addCollectedPath(Path);
231     else
232       warning("Source file doesn't exist, proceeded by ignoring it.", Path);
233     return;
234   }
235 
236   if (llvm::sys::fs::is_regular_file(Status)) {
237     addCollectedPath(Path);
238     return;
239   }
240 
241   if (llvm::sys::fs::is_directory(Status)) {
242     std::error_code EC;
243     for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
244          F != E; F.increment(EC)) {
245 
246       auto Status = F->status();
247       if (!Status) {
248         warning(Status.getError().message(), F->path());
249         continue;
250       }
251 
252       if (Status->type() == llvm::sys::fs::file_type::regular_file)
253         addCollectedPath(F->path());
254     }
255   }
256 }
257 
258 std::optional<sys::fs::file_status>
259 CodeCoverageTool::getFileStatus(StringRef FilePath) {
260   auto It = FileStatusCache.try_emplace(FilePath);
261   auto &CachedStatus = It.first->getValue();
262   if (!It.second)
263     return CachedStatus;
264 
265   sys::fs::file_status Status;
266   if (!sys::fs::status(FilePath, Status))
267     CachedStatus = Status;
268   return CachedStatus;
269 }
270 
271 bool CodeCoverageTool::isEquivalentFile(StringRef FilePath1,
272                                         StringRef FilePath2) {
273   auto Status1 = getFileStatus(FilePath1);
274   auto Status2 = getFileStatus(FilePath2);
275   return Status1 && Status2 && sys::fs::equivalent(*Status1, *Status2);
276 }
277 
278 ErrorOr<const MemoryBuffer &>
279 CodeCoverageTool::getSourceFile(StringRef SourceFile) {
280   // If we've remapped filenames, look up the real location for this file.
281   std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
282   if (!RemappedFilenames.empty()) {
283     auto Loc = RemappedFilenames.find(SourceFile);
284     if (Loc != RemappedFilenames.end())
285       SourceFile = Loc->second;
286   }
287   for (const auto &Files : LoadedSourceFiles)
288     if (isEquivalentFile(SourceFile, Files.first))
289       return *Files.second;
290   auto Buffer = MemoryBuffer::getFile(SourceFile);
291   if (auto EC = Buffer.getError()) {
292     error(EC.message(), SourceFile);
293     return EC;
294   }
295   LoadedSourceFiles.emplace_back(std::string(SourceFile),
296                                  std::move(Buffer.get()));
297   return *LoadedSourceFiles.back().second;
298 }
299 
300 void CodeCoverageTool::attachExpansionSubViews(
301     SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
302     const CoverageMapping &Coverage) {
303   if (!ViewOpts.ShowExpandedRegions)
304     return;
305   for (const auto &Expansion : Expansions) {
306     auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
307     if (ExpansionCoverage.empty())
308       continue;
309     auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
310     if (!SourceBuffer)
311       continue;
312 
313     auto SubViewBranches = ExpansionCoverage.getBranches();
314     auto SubViewExpansions = ExpansionCoverage.getExpansions();
315     auto SubView =
316         SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
317                                    ViewOpts, std::move(ExpansionCoverage));
318     attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
319     attachBranchSubViews(*SubView, Expansion.Function.Name, SubViewBranches,
320                          SourceBuffer.get(), ExpansionCoverage);
321     View.addExpansion(Expansion.Region, std::move(SubView));
322   }
323 }
324 
325 void CodeCoverageTool::attachBranchSubViews(SourceCoverageView &View,
326                                             StringRef SourceName,
327                                             ArrayRef<CountedRegion> Branches,
328                                             const MemoryBuffer &File,
329                                             CoverageData &CoverageInfo) {
330   if (!ViewOpts.ShowBranchCounts && !ViewOpts.ShowBranchPercents)
331     return;
332 
333   const auto *NextBranch = Branches.begin();
334   const auto *EndBranch = Branches.end();
335 
336   // Group branches that have the same line number into the same subview.
337   while (NextBranch != EndBranch) {
338     std::vector<CountedRegion> ViewBranches;
339     unsigned CurrentLine = NextBranch->LineStart;
340 
341     while (NextBranch != EndBranch && CurrentLine == NextBranch->LineStart)
342       ViewBranches.push_back(*NextBranch++);
343 
344     if (!ViewBranches.empty()) {
345       auto SubView = SourceCoverageView::create(SourceName, File, ViewOpts,
346                                                 std::move(CoverageInfo));
347       View.addBranch(CurrentLine, ViewBranches, std::move(SubView));
348     }
349   }
350 }
351 
352 std::unique_ptr<SourceCoverageView>
353 CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
354                                      const CoverageMapping &Coverage) {
355   auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
356   if (FunctionCoverage.empty())
357     return nullptr;
358   auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
359   if (!SourceBuffer)
360     return nullptr;
361 
362   auto Branches = FunctionCoverage.getBranches();
363   auto Expansions = FunctionCoverage.getExpansions();
364   auto View = SourceCoverageView::create(DC.demangle(Function.Name),
365                                          SourceBuffer.get(), ViewOpts,
366                                          std::move(FunctionCoverage));
367   attachExpansionSubViews(*View, Expansions, Coverage);
368   attachBranchSubViews(*View, DC.demangle(Function.Name), Branches,
369                        SourceBuffer.get(), FunctionCoverage);
370 
371   return View;
372 }
373 
374 std::unique_ptr<SourceCoverageView>
375 CodeCoverageTool::createSourceFileView(StringRef SourceFile,
376                                        const CoverageMapping &Coverage) {
377   auto SourceBuffer = getSourceFile(SourceFile);
378   if (!SourceBuffer)
379     return nullptr;
380   auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
381   if (FileCoverage.empty())
382     return nullptr;
383 
384   auto Branches = FileCoverage.getBranches();
385   auto Expansions = FileCoverage.getExpansions();
386   auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
387                                          ViewOpts, std::move(FileCoverage));
388   attachExpansionSubViews(*View, Expansions, Coverage);
389   attachBranchSubViews(*View, SourceFile, Branches, SourceBuffer.get(),
390                        FileCoverage);
391   if (!ViewOpts.ShowFunctionInstantiations)
392     return View;
393 
394   for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) {
395     // Skip functions which have a single instantiation.
396     if (Group.size() < 2)
397       continue;
398 
399     for (const FunctionRecord *Function : Group.getInstantiations()) {
400       std::unique_ptr<SourceCoverageView> SubView{nullptr};
401 
402       StringRef Funcname = DC.demangle(Function->Name);
403 
404       if (Function->ExecutionCount > 0) {
405         auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
406         auto SubViewExpansions = SubViewCoverage.getExpansions();
407         auto SubViewBranches = SubViewCoverage.getBranches();
408         SubView = SourceCoverageView::create(
409             Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
410         attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
411         attachBranchSubViews(*SubView, SourceFile, SubViewBranches,
412                              SourceBuffer.get(), SubViewCoverage);
413       }
414 
415       unsigned FileID = Function->CountedRegions.front().FileID;
416       unsigned Line = 0;
417       for (const auto &CR : Function->CountedRegions)
418         if (CR.FileID == FileID)
419           Line = std::max(CR.LineEnd, Line);
420       View->addInstantiation(Funcname, Line, std::move(SubView));
421     }
422   }
423   return View;
424 }
425 
426 static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
427   sys::fs::file_status Status;
428   if (sys::fs::status(LHS, Status))
429     return false;
430   auto LHSTime = Status.getLastModificationTime();
431   if (sys::fs::status(RHS, Status))
432     return false;
433   auto RHSTime = Status.getLastModificationTime();
434   return LHSTime > RHSTime;
435 }
436 
437 std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
438   for (StringRef ObjectFilename : ObjectFilenames)
439     if (modifiedTimeGT(ObjectFilename, PGOFilename))
440       warning("profile data may be out of date - object is newer",
441               ObjectFilename);
442   auto CoverageOrErr =
443       CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches,
444                             ViewOpts.CompilationDirectory, BIDFetcher.get());
445   if (Error E = CoverageOrErr.takeError()) {
446     error("Failed to load coverage: " + toString(std::move(E)));
447     return nullptr;
448   }
449   auto Coverage = std::move(CoverageOrErr.get());
450   unsigned Mismatched = Coverage->getMismatchedCount();
451   if (Mismatched) {
452     warning(Twine(Mismatched) + " functions have mismatched data");
453 
454     if (ViewOpts.Debug) {
455       for (const auto &HashMismatch : Coverage->getHashMismatches())
456         errs() << "hash-mismatch: "
457                << "No profile record found for '" << HashMismatch.first << "'"
458                << " with hash = 0x" << Twine::utohexstr(HashMismatch.second)
459                << '\n';
460     }
461   }
462 
463   remapPathNames(*Coverage);
464 
465   if (!SourceFiles.empty())
466     removeUnmappedInputs(*Coverage);
467 
468   demangleSymbols(*Coverage);
469 
470   return Coverage;
471 }
472 
473 void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
474   if (!PathRemapping)
475     return;
476 
477   // Convert remapping paths to native paths with trailing seperators.
478   auto nativeWithTrailing = [](StringRef Path) -> std::string {
479     if (Path.empty())
480       return "";
481     SmallString<128> NativePath;
482     sys::path::native(Path, NativePath);
483     sys::path::remove_dots(NativePath, true);
484     if (!NativePath.empty() && !sys::path::is_separator(NativePath.back()))
485       NativePath += sys::path::get_separator();
486     return NativePath.c_str();
487   };
488   std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
489   std::string RemapTo = nativeWithTrailing(PathRemapping->second);
490 
491   // Create a mapping from coverage data file paths to local paths.
492   for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
493     SmallString<128> NativeFilename;
494     sys::path::native(Filename, NativeFilename);
495     sys::path::remove_dots(NativeFilename, true);
496     if (NativeFilename.startswith(RemapFrom)) {
497       RemappedFilenames[Filename] =
498           RemapTo + NativeFilename.substr(RemapFrom.size()).str();
499     }
500   }
501 
502   // Convert input files from local paths to coverage data file paths.
503   StringMap<std::string> InvRemappedFilenames;
504   for (const auto &RemappedFilename : RemappedFilenames)
505     InvRemappedFilenames[RemappedFilename.getValue()] =
506         std::string(RemappedFilename.getKey());
507 
508   for (std::string &Filename : SourceFiles) {
509     SmallString<128> NativeFilename;
510     sys::path::native(Filename, NativeFilename);
511     auto CovFileName = InvRemappedFilenames.find(NativeFilename);
512     if (CovFileName != InvRemappedFilenames.end())
513       Filename = CovFileName->second;
514   }
515 }
516 
517 void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
518   std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
519 
520   // The user may have specified source files which aren't in the coverage
521   // mapping. Filter these files away.
522   llvm::erase_if(SourceFiles, [&](const std::string &SF) {
523     return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(), SF);
524   });
525 }
526 
527 void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
528   if (!ViewOpts.hasDemangler())
529     return;
530 
531   // Pass function names to the demangler in a temporary file.
532   int InputFD;
533   SmallString<256> InputPath;
534   std::error_code EC =
535       sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
536   if (EC) {
537     error(InputPath, EC.message());
538     return;
539   }
540   ToolOutputFile InputTOF{InputPath, InputFD};
541 
542   unsigned NumSymbols = 0;
543   for (const auto &Function : Coverage.getCoveredFunctions()) {
544     InputTOF.os() << Function.Name << '\n';
545     ++NumSymbols;
546   }
547   InputTOF.os().close();
548 
549   // Use another temporary file to store the demangler's output.
550   int OutputFD;
551   SmallString<256> OutputPath;
552   EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
553                                     OutputPath);
554   if (EC) {
555     error(OutputPath, EC.message());
556     return;
557   }
558   ToolOutputFile OutputTOF{OutputPath, OutputFD};
559   OutputTOF.os().close();
560 
561   // Invoke the demangler.
562   std::vector<StringRef> ArgsV;
563   ArgsV.reserve(ViewOpts.DemanglerOpts.size());
564   for (StringRef Arg : ViewOpts.DemanglerOpts)
565     ArgsV.push_back(Arg);
566   std::optional<StringRef> Redirects[] = {
567       InputPath.str(), OutputPath.str(), {""}};
568   std::string ErrMsg;
569   int RC =
570       sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV,
571                           /*env=*/std::nullopt, Redirects, /*secondsToWait=*/0,
572                           /*memoryLimit=*/0, &ErrMsg);
573   if (RC) {
574     error(ErrMsg, ViewOpts.DemanglerOpts[0]);
575     return;
576   }
577 
578   // Parse the demangler's output.
579   auto BufOrError = MemoryBuffer::getFile(OutputPath);
580   if (!BufOrError) {
581     error(OutputPath, BufOrError.getError().message());
582     return;
583   }
584 
585   std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
586 
587   SmallVector<StringRef, 8> Symbols;
588   StringRef DemanglerData = DemanglerBuf->getBuffer();
589   DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
590                       /*KeepEmpty=*/false);
591   if (Symbols.size() != NumSymbols) {
592     error("Demangler did not provide expected number of symbols");
593     return;
594   }
595 
596   // Cache the demangled names.
597   unsigned I = 0;
598   for (const auto &Function : Coverage.getCoveredFunctions())
599     // On Windows, lines in the demangler's output file end with "\r\n".
600     // Splitting by '\n' keeps '\r's, so cut them now.
601     DC.DemangledNames[Function.Name] = std::string(Symbols[I++].rtrim());
602 }
603 
604 void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
605                                            CoverageMapping *Coverage,
606                                            CoveragePrinter *Printer,
607                                            bool ShowFilenames) {
608   auto View = createSourceFileView(SourceFile, *Coverage);
609   if (!View) {
610     warning("The file '" + SourceFile + "' isn't covered.");
611     return;
612   }
613 
614   auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
615   if (Error E = OSOrErr.takeError()) {
616     error("Could not create view file!", toString(std::move(E)));
617     return;
618   }
619   auto OS = std::move(OSOrErr.get());
620 
621   View->print(*OS.get(), /*Wholefile=*/true,
622               /*ShowSourceName=*/ShowFilenames,
623               /*ShowTitle=*/ViewOpts.hasOutputDirectory());
624   Printer->closeViewFile(std::move(OS));
625 }
626 
627 int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
628   cl::opt<std::string> CovFilename(
629       cl::Positional, cl::desc("Covered executable or object file."));
630 
631   cl::list<std::string> CovFilenames(
632       "object", cl::desc("Coverage executable or object file"));
633 
634   cl::opt<bool> DebugDumpCollectedObjects(
635       "dump-collected-objects", cl::Optional, cl::Hidden,
636       cl::desc("Show the collected coverage object files"));
637 
638   cl::list<std::string> InputSourceFiles("sources", cl::Positional,
639                                          cl::desc("<Source files>"));
640 
641   cl::opt<bool> DebugDumpCollectedPaths(
642       "dump-collected-paths", cl::Optional, cl::Hidden,
643       cl::desc("Show the collected paths to source files"));
644 
645   cl::opt<std::string, true> PGOFilename(
646       "instr-profile", cl::Required, cl::location(this->PGOFilename),
647       cl::desc(
648           "File with the profile data obtained after an instrumented run"));
649 
650   cl::list<std::string> Arches(
651       "arch", cl::desc("architectures of the coverage mapping binaries"));
652 
653   cl::opt<bool> DebugDump("dump", cl::Optional,
654                           cl::desc("Show internal debug dump"));
655 
656   cl::list<std::string> DebugFileDirectory(
657       "debug-file-directory",
658       cl::desc("Directories to search for object files by build ID"));
659   cl::opt<bool> Debuginfod(
660       "debuginfod", cl::ZeroOrMore,
661       cl::desc("Use debuginfod to look up object files from profile"),
662       cl::init(canUseDebuginfod()));
663 
664   cl::opt<CoverageViewOptions::OutputFormat> Format(
665       "format", cl::desc("Output format for line-based coverage reports"),
666       cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
667                             "Text output"),
668                  clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
669                             "HTML output"),
670                  clEnumValN(CoverageViewOptions::OutputFormat::Lcov, "lcov",
671                             "lcov tracefile output")),
672       cl::init(CoverageViewOptions::OutputFormat::Text));
673 
674   cl::opt<std::string> PathRemap(
675       "path-equivalence", cl::Optional,
676       cl::desc("<from>,<to> Map coverage data paths to local source file "
677                "paths"));
678 
679   cl::OptionCategory FilteringCategory("Function filtering options");
680 
681   cl::list<std::string> NameFilters(
682       "name", cl::Optional,
683       cl::desc("Show code coverage only for functions with the given name"),
684       cl::cat(FilteringCategory));
685 
686   cl::list<std::string> NameFilterFiles(
687       "name-allowlist", cl::Optional,
688       cl::desc("Show code coverage only for functions listed in the given "
689                "file"),
690       cl::cat(FilteringCategory));
691 
692   cl::list<std::string> NameRegexFilters(
693       "name-regex", cl::Optional,
694       cl::desc("Show code coverage only for functions that match the given "
695                "regular expression"),
696       cl::cat(FilteringCategory));
697 
698   cl::list<std::string> IgnoreFilenameRegexFilters(
699       "ignore-filename-regex", cl::Optional,
700       cl::desc("Skip source code files with file paths that match the given "
701                "regular expression"),
702       cl::cat(FilteringCategory));
703 
704   cl::opt<double> RegionCoverageLtFilter(
705       "region-coverage-lt", cl::Optional,
706       cl::desc("Show code coverage only for functions with region coverage "
707                "less than the given threshold"),
708       cl::cat(FilteringCategory));
709 
710   cl::opt<double> RegionCoverageGtFilter(
711       "region-coverage-gt", cl::Optional,
712       cl::desc("Show code coverage only for functions with region coverage "
713                "greater than the given threshold"),
714       cl::cat(FilteringCategory));
715 
716   cl::opt<double> LineCoverageLtFilter(
717       "line-coverage-lt", cl::Optional,
718       cl::desc("Show code coverage only for functions with line coverage less "
719                "than the given threshold"),
720       cl::cat(FilteringCategory));
721 
722   cl::opt<double> LineCoverageGtFilter(
723       "line-coverage-gt", cl::Optional,
724       cl::desc("Show code coverage only for functions with line coverage "
725                "greater than the given threshold"),
726       cl::cat(FilteringCategory));
727 
728   cl::opt<cl::boolOrDefault> UseColor(
729       "use-color", cl::desc("Emit colored output (default=autodetect)"),
730       cl::init(cl::BOU_UNSET));
731 
732   cl::list<std::string> DemanglerOpts(
733       "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
734 
735   cl::opt<bool> RegionSummary(
736       "show-region-summary", cl::Optional,
737       cl::desc("Show region statistics in summary table"),
738       cl::init(true));
739 
740   cl::opt<bool> BranchSummary(
741       "show-branch-summary", cl::Optional,
742       cl::desc("Show branch condition statistics in summary table"),
743       cl::init(true));
744 
745   cl::opt<bool> InstantiationSummary(
746       "show-instantiation-summary", cl::Optional,
747       cl::desc("Show instantiation statistics in summary table"));
748 
749   cl::opt<bool> SummaryOnly(
750       "summary-only", cl::Optional,
751       cl::desc("Export only summary information for each source file"));
752 
753   cl::opt<unsigned> NumThreads(
754       "num-threads", cl::init(0),
755       cl::desc("Number of merge threads to use (default: autodetect)"));
756   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
757                         cl::aliasopt(NumThreads));
758 
759   cl::opt<std::string> CompilationDirectory(
760       "compilation-dir", cl::init(""),
761       cl::desc("Directory used as a base for relative coverage mapping paths"));
762 
763   auto commandLineParser = [&, this](int argc, const char **argv) -> int {
764     cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
765     ViewOpts.Debug = DebugDump;
766     if (Debuginfod) {
767       HTTPClient::initialize();
768       BIDFetcher = std::make_unique<DebuginfodFetcher>(DebugFileDirectory);
769     } else {
770       BIDFetcher = std::make_unique<object::BuildIDFetcher>(DebugFileDirectory);
771     }
772 
773     if (!CovFilename.empty())
774       ObjectFilenames.emplace_back(CovFilename);
775     for (const std::string &Filename : CovFilenames)
776       ObjectFilenames.emplace_back(Filename);
777     if (ObjectFilenames.empty() && !Debuginfod && DebugFileDirectory.empty()) {
778       errs() << "No filenames specified!\n";
779       ::exit(1);
780     }
781 
782     if (DebugDumpCollectedObjects) {
783       for (StringRef OF : ObjectFilenames)
784         outs() << OF << '\n';
785       ::exit(0);
786     }
787 
788     ViewOpts.Format = Format;
789     switch (ViewOpts.Format) {
790     case CoverageViewOptions::OutputFormat::Text:
791       ViewOpts.Colors = UseColor == cl::BOU_UNSET
792                             ? sys::Process::StandardOutHasColors()
793                             : UseColor == cl::BOU_TRUE;
794       break;
795     case CoverageViewOptions::OutputFormat::HTML:
796       if (UseColor == cl::BOU_FALSE)
797         errs() << "Color output cannot be disabled when generating html.\n";
798       ViewOpts.Colors = true;
799       break;
800     case CoverageViewOptions::OutputFormat::Lcov:
801       if (UseColor == cl::BOU_TRUE)
802         errs() << "Color output cannot be enabled when generating lcov.\n";
803       ViewOpts.Colors = false;
804       break;
805     }
806 
807     // If path-equivalence was given and is a comma seperated pair then set
808     // PathRemapping.
809     if (!PathRemap.empty()) {
810       auto EquivPair = StringRef(PathRemap).split(',');
811       if (EquivPair.first.empty() || EquivPair.second.empty()) {
812         error("invalid argument '" + PathRemap +
813                   "', must be in format 'from,to'",
814               "-path-equivalence");
815         return 1;
816       }
817 
818       PathRemapping = {std::string(EquivPair.first),
819                        std::string(EquivPair.second)};
820     }
821 
822     // If a demangler is supplied, check if it exists and register it.
823     if (!DemanglerOpts.empty()) {
824       auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
825       if (!DemanglerPathOrErr) {
826         error("Could not find the demangler!",
827               DemanglerPathOrErr.getError().message());
828         return 1;
829       }
830       DemanglerOpts[0] = *DemanglerPathOrErr;
831       ViewOpts.DemanglerOpts.swap(DemanglerOpts);
832     }
833 
834     // Read in -name-allowlist files.
835     if (!NameFilterFiles.empty()) {
836       std::string SpecialCaseListErr;
837       NameAllowlist = SpecialCaseList::create(
838           NameFilterFiles, *vfs::getRealFileSystem(), SpecialCaseListErr);
839       if (!NameAllowlist)
840         error(SpecialCaseListErr);
841     }
842 
843     // Create the function filters
844     if (!NameFilters.empty() || NameAllowlist || !NameRegexFilters.empty()) {
845       auto NameFilterer = std::make_unique<CoverageFilters>();
846       for (const auto &Name : NameFilters)
847         NameFilterer->push_back(std::make_unique<NameCoverageFilter>(Name));
848       if (NameAllowlist && !NameFilterFiles.empty())
849         NameFilterer->push_back(
850             std::make_unique<NameAllowlistCoverageFilter>(*NameAllowlist));
851       for (const auto &Regex : NameRegexFilters)
852         NameFilterer->push_back(
853             std::make_unique<NameRegexCoverageFilter>(Regex));
854       Filters.push_back(std::move(NameFilterer));
855     }
856 
857     if (RegionCoverageLtFilter.getNumOccurrences() ||
858         RegionCoverageGtFilter.getNumOccurrences() ||
859         LineCoverageLtFilter.getNumOccurrences() ||
860         LineCoverageGtFilter.getNumOccurrences()) {
861       auto StatFilterer = std::make_unique<CoverageFilters>();
862       if (RegionCoverageLtFilter.getNumOccurrences())
863         StatFilterer->push_back(std::make_unique<RegionCoverageFilter>(
864             RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
865       if (RegionCoverageGtFilter.getNumOccurrences())
866         StatFilterer->push_back(std::make_unique<RegionCoverageFilter>(
867             RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
868       if (LineCoverageLtFilter.getNumOccurrences())
869         StatFilterer->push_back(std::make_unique<LineCoverageFilter>(
870             LineCoverageFilter::LessThan, LineCoverageLtFilter));
871       if (LineCoverageGtFilter.getNumOccurrences())
872         StatFilterer->push_back(std::make_unique<LineCoverageFilter>(
873             RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
874       Filters.push_back(std::move(StatFilterer));
875     }
876 
877     // Create the ignore filename filters.
878     for (const auto &RE : IgnoreFilenameRegexFilters)
879       IgnoreFilenameFilters.push_back(
880           std::make_unique<NameRegexCoverageFilter>(RE));
881 
882     if (!Arches.empty()) {
883       for (const std::string &Arch : Arches) {
884         if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
885           error("Unknown architecture: " + Arch);
886           return 1;
887         }
888         CoverageArches.emplace_back(Arch);
889       }
890       if (CoverageArches.size() != 1 &&
891           CoverageArches.size() != ObjectFilenames.size()) {
892         error("Number of architectures doesn't match the number of objects");
893         return 1;
894       }
895     }
896 
897     // IgnoreFilenameFilters are applied even when InputSourceFiles specified.
898     for (const std::string &File : InputSourceFiles)
899       collectPaths(File);
900 
901     if (DebugDumpCollectedPaths) {
902       for (const std::string &SF : SourceFiles)
903         outs() << SF << '\n';
904       ::exit(0);
905     }
906 
907     ViewOpts.ShowBranchSummary = BranchSummary;
908     ViewOpts.ShowRegionSummary = RegionSummary;
909     ViewOpts.ShowInstantiationSummary = InstantiationSummary;
910     ViewOpts.ExportSummaryOnly = SummaryOnly;
911     ViewOpts.NumThreads = NumThreads;
912     ViewOpts.CompilationDirectory = CompilationDirectory;
913 
914     return 0;
915   };
916 
917   switch (Cmd) {
918   case Show:
919     return doShow(argc, argv, commandLineParser);
920   case Report:
921     return doReport(argc, argv, commandLineParser);
922   case Export:
923     return doExport(argc, argv, commandLineParser);
924   }
925   return 0;
926 }
927 
928 int CodeCoverageTool::doShow(int argc, const char **argv,
929                              CommandLineParserType commandLineParser) {
930 
931   cl::OptionCategory ViewCategory("Viewing options");
932 
933   cl::opt<bool> ShowLineExecutionCounts(
934       "show-line-counts", cl::Optional,
935       cl::desc("Show the execution counts for each line"), cl::init(true),
936       cl::cat(ViewCategory));
937 
938   cl::opt<bool> ShowRegions(
939       "show-regions", cl::Optional,
940       cl::desc("Show the execution counts for each region"),
941       cl::cat(ViewCategory));
942 
943   cl::opt<CoverageViewOptions::BranchOutputType> ShowBranches(
944       "show-branches", cl::Optional,
945       cl::desc("Show coverage for branch conditions"), cl::cat(ViewCategory),
946       cl::values(clEnumValN(CoverageViewOptions::BranchOutputType::Count,
947                             "count", "Show True/False counts"),
948                  clEnumValN(CoverageViewOptions::BranchOutputType::Percent,
949                             "percent", "Show True/False percent")),
950       cl::init(CoverageViewOptions::BranchOutputType::Off));
951 
952   cl::opt<bool> ShowBestLineRegionsCounts(
953       "show-line-counts-or-regions", cl::Optional,
954       cl::desc("Show the execution counts for each line, or the execution "
955                "counts for each region on lines that have multiple regions"),
956       cl::cat(ViewCategory));
957 
958   cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
959                                cl::desc("Show expanded source regions"),
960                                cl::cat(ViewCategory));
961 
962   cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
963                                    cl::desc("Show function instantiations"),
964                                    cl::init(true), cl::cat(ViewCategory));
965 
966   cl::opt<std::string> ShowOutputDirectory(
967       "output-dir", cl::init(""),
968       cl::desc("Directory in which coverage information is written out"));
969   cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
970                                  cl::aliasopt(ShowOutputDirectory));
971 
972   cl::opt<uint32_t> TabSize(
973       "tab-size", cl::init(2),
974       cl::desc(
975           "Set tab expansion size for html coverage reports (default = 2)"));
976 
977   cl::opt<std::string> ProjectTitle(
978       "project-title", cl::Optional,
979       cl::desc("Set project title for the coverage report"));
980 
981   cl::opt<std::string> CovWatermark(
982       "coverage-watermark", cl::Optional,
983       cl::desc("<high>,<low> value indicate thresholds for high and low"
984                "coverage watermark"));
985 
986   auto Err = commandLineParser(argc, argv);
987   if (Err)
988     return Err;
989 
990   if (ViewOpts.Format == CoverageViewOptions::OutputFormat::Lcov) {
991     error("Lcov format should be used with 'llvm-cov export'.");
992     return 1;
993   }
994 
995   ViewOpts.HighCovWatermark = 100.0;
996   ViewOpts.LowCovWatermark = 80.0;
997   if (!CovWatermark.empty()) {
998     auto WaterMarkPair = StringRef(CovWatermark).split(',');
999     if (WaterMarkPair.first.empty() || WaterMarkPair.second.empty()) {
1000       error("invalid argument '" + CovWatermark +
1001                 "', must be in format 'high,low'",
1002             "-coverage-watermark");
1003       return 1;
1004     }
1005 
1006     char *EndPointer = nullptr;
1007     ViewOpts.HighCovWatermark =
1008         strtod(WaterMarkPair.first.begin(), &EndPointer);
1009     if (EndPointer != WaterMarkPair.first.end()) {
1010       error("invalid number '" + WaterMarkPair.first +
1011                 "', invalid value for 'high'",
1012             "-coverage-watermark");
1013       return 1;
1014     }
1015 
1016     ViewOpts.LowCovWatermark =
1017         strtod(WaterMarkPair.second.begin(), &EndPointer);
1018     if (EndPointer != WaterMarkPair.second.end()) {
1019       error("invalid number '" + WaterMarkPair.second +
1020                 "', invalid value for 'low'",
1021             "-coverage-watermark");
1022       return 1;
1023     }
1024 
1025     if (ViewOpts.HighCovWatermark > 100 || ViewOpts.LowCovWatermark < 0 ||
1026         ViewOpts.HighCovWatermark <= ViewOpts.LowCovWatermark) {
1027       error(
1028           "invalid number range '" + CovWatermark +
1029               "', must be both high and low should be between 0-100, and high "
1030               "> low",
1031           "-coverage-watermark");
1032       return 1;
1033     }
1034   }
1035 
1036   ViewOpts.ShowLineNumbers = true;
1037   ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
1038                            !ShowRegions || ShowBestLineRegionsCounts;
1039   ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
1040   ViewOpts.ShowExpandedRegions = ShowExpansions;
1041   ViewOpts.ShowBranchCounts =
1042       ShowBranches == CoverageViewOptions::BranchOutputType::Count;
1043   ViewOpts.ShowBranchPercents =
1044       ShowBranches == CoverageViewOptions::BranchOutputType::Percent;
1045   ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
1046   ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
1047   ViewOpts.TabSize = TabSize;
1048   ViewOpts.ProjectTitle = ProjectTitle;
1049 
1050   if (ViewOpts.hasOutputDirectory()) {
1051     if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
1052       error("Could not create output directory!", E.message());
1053       return 1;
1054     }
1055   }
1056 
1057   sys::fs::file_status Status;
1058   if (std::error_code EC = sys::fs::status(PGOFilename, Status)) {
1059     error("Could not read profile data!" + EC.message(), PGOFilename);
1060     return 1;
1061   }
1062 
1063   auto ModifiedTime = Status.getLastModificationTime();
1064   std::string ModifiedTimeStr = to_string(ModifiedTime);
1065   size_t found = ModifiedTimeStr.rfind(':');
1066   ViewOpts.CreatedTimeStr = (found != std::string::npos)
1067                                 ? "Created: " + ModifiedTimeStr.substr(0, found)
1068                                 : "Created: " + ModifiedTimeStr;
1069 
1070   auto Coverage = load();
1071   if (!Coverage)
1072     return 1;
1073 
1074   auto Printer = CoveragePrinter::create(ViewOpts);
1075 
1076   if (SourceFiles.empty() && !HadSourceFiles)
1077     // Get the source files from the function coverage mapping.
1078     for (StringRef Filename : Coverage->getUniqueSourceFiles()) {
1079       if (!IgnoreFilenameFilters.matchesFilename(Filename))
1080         SourceFiles.push_back(std::string(Filename));
1081     }
1082 
1083   // Create an index out of the source files.
1084   if (ViewOpts.hasOutputDirectory()) {
1085     if (Error E = Printer->createIndexFile(SourceFiles, *Coverage, Filters)) {
1086       error("Could not create index file!", toString(std::move(E)));
1087       return 1;
1088     }
1089   }
1090 
1091   if (!Filters.empty()) {
1092     // Build the map of filenames to functions.
1093     std::map<llvm::StringRef, std::vector<const FunctionRecord *>>
1094         FilenameFunctionMap;
1095     for (const auto &SourceFile : SourceFiles)
1096       for (const auto &Function : Coverage->getCoveredFunctions(SourceFile))
1097         if (Filters.matches(*Coverage, Function))
1098           FilenameFunctionMap[SourceFile].push_back(&Function);
1099 
1100     // Only print filter matching functions for each file.
1101     for (const auto &FileFunc : FilenameFunctionMap) {
1102       StringRef File = FileFunc.first;
1103       const auto &Functions = FileFunc.second;
1104 
1105       auto OSOrErr = Printer->createViewFile(File, /*InToplevel=*/false);
1106       if (Error E = OSOrErr.takeError()) {
1107         error("Could not create view file!", toString(std::move(E)));
1108         return 1;
1109       }
1110       auto OS = std::move(OSOrErr.get());
1111 
1112       bool ShowTitle = ViewOpts.hasOutputDirectory();
1113       for (const auto *Function : Functions) {
1114         auto FunctionView = createFunctionView(*Function, *Coverage);
1115         if (!FunctionView) {
1116           warning("Could not read coverage for '" + Function->Name + "'.");
1117           continue;
1118         }
1119         FunctionView->print(*OS.get(), /*WholeFile=*/false,
1120                             /*ShowSourceName=*/true, ShowTitle);
1121         ShowTitle = false;
1122       }
1123 
1124       Printer->closeViewFile(std::move(OS));
1125     }
1126     return 0;
1127   }
1128 
1129   // Show files
1130   bool ShowFilenames =
1131       (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
1132       (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
1133 
1134   ThreadPoolStrategy S = hardware_concurrency(ViewOpts.NumThreads);
1135   if (ViewOpts.NumThreads == 0) {
1136     // If NumThreads is not specified, create one thread for each input, up to
1137     // the number of hardware cores.
1138     S = heavyweight_hardware_concurrency(SourceFiles.size());
1139     S.Limit = true;
1140   }
1141 
1142   if (!ViewOpts.hasOutputDirectory() || S.ThreadsRequested == 1) {
1143     for (const std::string &SourceFile : SourceFiles)
1144       writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
1145                           ShowFilenames);
1146   } else {
1147     // In -output-dir mode, it's safe to use multiple threads to print files.
1148     ThreadPool Pool(S);
1149     for (const std::string &SourceFile : SourceFiles)
1150       Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
1151                  Coverage.get(), Printer.get(), ShowFilenames);
1152     Pool.wait();
1153   }
1154 
1155   return 0;
1156 }
1157 
1158 int CodeCoverageTool::doReport(int argc, const char **argv,
1159                                CommandLineParserType commandLineParser) {
1160   cl::opt<bool> ShowFunctionSummaries(
1161       "show-functions", cl::Optional, cl::init(false),
1162       cl::desc("Show coverage summaries for each function"));
1163 
1164   auto Err = commandLineParser(argc, argv);
1165   if (Err)
1166     return Err;
1167 
1168   if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
1169     error("HTML output for summary reports is not yet supported.");
1170     return 1;
1171   } else if (ViewOpts.Format == CoverageViewOptions::OutputFormat::Lcov) {
1172     error("Lcov format should be used with 'llvm-cov export'.");
1173     return 1;
1174   }
1175 
1176   sys::fs::file_status Status;
1177   if (std::error_code EC = sys::fs::status(PGOFilename, Status)) {
1178     error("Could not read profile data!" + EC.message(), PGOFilename);
1179     return 1;
1180   }
1181 
1182   auto Coverage = load();
1183   if (!Coverage)
1184     return 1;
1185 
1186   CoverageReport Report(ViewOpts, *Coverage);
1187   if (!ShowFunctionSummaries) {
1188     if (SourceFiles.empty())
1189       Report.renderFileReports(llvm::outs(), IgnoreFilenameFilters);
1190     else
1191       Report.renderFileReports(llvm::outs(), SourceFiles);
1192   } else {
1193     if (SourceFiles.empty()) {
1194       error("Source files must be specified when -show-functions=true is "
1195             "specified");
1196       return 1;
1197     }
1198 
1199     Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
1200   }
1201   return 0;
1202 }
1203 
1204 int CodeCoverageTool::doExport(int argc, const char **argv,
1205                                CommandLineParserType commandLineParser) {
1206 
1207   cl::OptionCategory ExportCategory("Exporting options");
1208 
1209   cl::opt<bool> SkipExpansions("skip-expansions", cl::Optional,
1210                                cl::desc("Don't export expanded source regions"),
1211                                cl::cat(ExportCategory));
1212 
1213   cl::opt<bool> SkipFunctions("skip-functions", cl::Optional,
1214                               cl::desc("Don't export per-function data"),
1215                               cl::cat(ExportCategory));
1216 
1217   cl::opt<bool> SkipBranches("skip-branches", cl::Optional,
1218                               cl::desc("Don't export branch data (LCOV)"),
1219                               cl::cat(ExportCategory));
1220 
1221   auto Err = commandLineParser(argc, argv);
1222   if (Err)
1223     return Err;
1224 
1225   ViewOpts.SkipExpansions = SkipExpansions;
1226   ViewOpts.SkipFunctions = SkipFunctions;
1227   ViewOpts.SkipBranches = SkipBranches;
1228 
1229   if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text &&
1230       ViewOpts.Format != CoverageViewOptions::OutputFormat::Lcov) {
1231     error("Coverage data can only be exported as textual JSON or an "
1232           "lcov tracefile.");
1233     return 1;
1234   }
1235 
1236   sys::fs::file_status Status;
1237   if (std::error_code EC = sys::fs::status(PGOFilename, Status)) {
1238     error("Could not read profile data!" + EC.message(), PGOFilename);
1239     return 1;
1240   }
1241 
1242   auto Coverage = load();
1243   if (!Coverage) {
1244     error("Could not load coverage information");
1245     return 1;
1246   }
1247 
1248   std::unique_ptr<CoverageExporter> Exporter;
1249 
1250   switch (ViewOpts.Format) {
1251   case CoverageViewOptions::OutputFormat::Text:
1252     Exporter =
1253         std::make_unique<CoverageExporterJson>(*Coverage, ViewOpts, outs());
1254     break;
1255   case CoverageViewOptions::OutputFormat::HTML:
1256     // Unreachable because we should have gracefully terminated with an error
1257     // above.
1258     llvm_unreachable("Export in HTML is not supported!");
1259   case CoverageViewOptions::OutputFormat::Lcov:
1260     Exporter =
1261         std::make_unique<CoverageExporterLcov>(*Coverage, ViewOpts, outs());
1262     break;
1263   }
1264 
1265   if (SourceFiles.empty())
1266     Exporter->renderRoot(IgnoreFilenameFilters);
1267   else
1268     Exporter->renderRoot(SourceFiles);
1269 
1270   return 0;
1271 }
1272 
1273 int showMain(int argc, const char *argv[]) {
1274   CodeCoverageTool Tool;
1275   return Tool.run(CodeCoverageTool::Show, argc, argv);
1276 }
1277 
1278 int reportMain(int argc, const char *argv[]) {
1279   CodeCoverageTool Tool;
1280   return Tool.run(CodeCoverageTool::Report, argc, argv);
1281 }
1282 
1283 int exportMain(int argc, const char *argv[]) {
1284   CodeCoverageTool Tool;
1285   return Tool.run(CodeCoverageTool::Export, argc, argv);
1286 }
1287