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