1 //===- CodeCoverage.cpp - Coverage tool based on profiling instrumentation-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The 'CodeCoverageTool' class implements a command line tool to analyze and
11 // report coverage information using the profiling instrumentation and code
14 //===----------------------------------------------------------------------===//
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"
41 #include <system_error>
44 using namespace coverage;
46 void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping,
47 const CoverageViewOptions &Options,
51 /// \brief The implementation of the coverage tool.
52 class CodeCoverageTool {
55 /// \brief The show command.
57 /// \brief The report command.
59 /// \brief The export command.
63 int run(Command Cmd, int argc, const char **argv);
66 /// \brief Print the error message to the error output stream.
67 void error(const Twine &Message, StringRef Whence = "");
69 /// \brief Print the warning message to the error output stream.
70 void warning(const Twine &Message, StringRef Whence = "");
72 /// \brief Convert \p Path into an absolute path and append it to the list
73 /// of collected paths.
74 void addCollectedPath(const std::string &Path);
76 /// \brief If \p Path is a regular file, collect the path. If it's a
77 /// directory, recursively collect all of the paths within the directory.
78 void collectPaths(const std::string &Path);
80 /// \brief Return a memory buffer for the given source file.
81 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
83 /// \brief Create source views for the expansions of the view.
84 void attachExpansionSubViews(SourceCoverageView &View,
85 ArrayRef<ExpansionRecord> Expansions,
86 const CoverageMapping &Coverage);
88 /// \brief Create the source view of a particular function.
89 std::unique_ptr<SourceCoverageView>
90 createFunctionView(const FunctionRecord &Function,
91 const CoverageMapping &Coverage);
93 /// \brief Create the main source view of a particular source file.
94 std::unique_ptr<SourceCoverageView>
95 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
97 /// \brief Load the coverage mapping data. Return nullptr if an error occurred.
98 std::unique_ptr<CoverageMapping> load();
100 /// \brief Create a mapping from files in the Coverage data to local copies
101 /// (path-equivalence).
102 void remapPathNames(const CoverageMapping &Coverage);
104 /// \brief Remove input source files which aren't mapped by \p Coverage.
105 void removeUnmappedInputs(const CoverageMapping &Coverage);
107 /// \brief If a demangler is available, demangle all symbol names.
108 void demangleSymbols(const CoverageMapping &Coverage);
110 /// \brief Write out a source file view to the filesystem.
111 void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
112 CoveragePrinter *Printer, bool ShowFilenames);
114 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
116 int show(int argc, const char **argv,
117 CommandLineParserType commandLineParser);
119 int report(int argc, const char **argv,
120 CommandLineParserType commandLineParser);
122 int export_(int argc, const char **argv,
123 CommandLineParserType commandLineParser);
125 std::vector<StringRef> ObjectFilenames;
126 CoverageViewOptions ViewOpts;
127 CoverageFiltersMatchAll Filters;
129 /// The path to the indexed profile.
130 std::string PGOFilename;
132 /// A list of input source files.
133 std::vector<std::string> SourceFiles;
135 /// In -path-equivalence mode, this maps the absolute paths from the coverage
136 /// mapping data to the input source files.
137 StringMap<std::string> RemappedFilenames;
139 /// The coverage data path to be remapped from, and the source path to be
140 /// remapped to, when using -path-equivalence.
141 Optional<std::pair<std::string, std::string>> PathRemapping;
143 /// The architecture the coverage mapping data targets.
144 std::vector<StringRef> CoverageArches;
146 /// A cache for demangled symbols.
149 /// A lock which guards printing to stderr.
152 /// A container for input source file buffers.
153 std::mutex LoadedSourceFilesLock;
154 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
157 /// Whitelist from -name-whitelist to be used for filtering.
158 std::unique_ptr<SpecialCaseList> NameWhitelist;
162 static std::string getErrorString(const Twine &Message, StringRef Whence,
164 std::string Str = (Warning ? "warning" : "error");
167 Str += Whence.str() + ": ";
168 Str += Message.str() + "\n";
172 void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
173 std::unique_lock<std::mutex> Guard{ErrsLock};
174 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
175 << getErrorString(Message, Whence, false);
178 void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
179 std::unique_lock<std::mutex> Guard{ErrsLock};
180 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
181 << getErrorString(Message, Whence, true);
184 void CodeCoverageTool::addCollectedPath(const std::string &Path) {
185 SmallString<128> EffectivePath(Path);
186 if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
187 error(EC.message(), Path);
190 sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true);
191 SourceFiles.emplace_back(EffectivePath.str());
194 void CodeCoverageTool::collectPaths(const std::string &Path) {
195 llvm::sys::fs::file_status Status;
196 llvm::sys::fs::status(Path, Status);
197 if (!llvm::sys::fs::exists(Status)) {
199 addCollectedPath(Path);
201 error("Missing source file", Path);
205 if (llvm::sys::fs::is_regular_file(Status)) {
206 addCollectedPath(Path);
210 if (llvm::sys::fs::is_directory(Status)) {
212 for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
213 F != E && !EC; F.increment(EC)) {
214 if (llvm::sys::fs::is_regular_file(F->path()))
215 addCollectedPath(F->path());
218 warning(EC.message(), Path);
222 ErrorOr<const MemoryBuffer &>
223 CodeCoverageTool::getSourceFile(StringRef SourceFile) {
224 // If we've remapped filenames, look up the real location for this file.
225 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
226 if (!RemappedFilenames.empty()) {
227 auto Loc = RemappedFilenames.find(SourceFile);
228 if (Loc != RemappedFilenames.end())
229 SourceFile = Loc->second;
231 for (const auto &Files : LoadedSourceFiles)
232 if (sys::fs::equivalent(SourceFile, Files.first))
233 return *Files.second;
234 auto Buffer = MemoryBuffer::getFile(SourceFile);
235 if (auto EC = Buffer.getError()) {
236 error(EC.message(), SourceFile);
239 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
240 return *LoadedSourceFiles.back().second;
243 void CodeCoverageTool::attachExpansionSubViews(
244 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
245 const CoverageMapping &Coverage) {
246 if (!ViewOpts.ShowExpandedRegions)
248 for (const auto &Expansion : Expansions) {
249 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
250 if (ExpansionCoverage.empty())
252 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
256 auto SubViewExpansions = ExpansionCoverage.getExpansions();
258 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
259 ViewOpts, std::move(ExpansionCoverage));
260 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
261 View.addExpansion(Expansion.Region, std::move(SubView));
265 std::unique_ptr<SourceCoverageView>
266 CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
267 const CoverageMapping &Coverage) {
268 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
269 if (FunctionCoverage.empty())
271 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
275 auto Expansions = FunctionCoverage.getExpansions();
276 auto View = SourceCoverageView::create(DC.demangle(Function.Name),
277 SourceBuffer.get(), ViewOpts,
278 std::move(FunctionCoverage));
279 attachExpansionSubViews(*View, Expansions, Coverage);
284 std::unique_ptr<SourceCoverageView>
285 CodeCoverageTool::createSourceFileView(StringRef SourceFile,
286 const CoverageMapping &Coverage) {
287 auto SourceBuffer = getSourceFile(SourceFile);
290 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
291 if (FileCoverage.empty())
294 auto Expansions = FileCoverage.getExpansions();
295 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
296 ViewOpts, std::move(FileCoverage));
297 attachExpansionSubViews(*View, Expansions, Coverage);
298 if (!ViewOpts.ShowFunctionInstantiations)
301 for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) {
302 // Skip functions which have a single instantiation.
303 if (Group.size() < 2)
306 for (const FunctionRecord *Function : Group.getInstantiations()) {
307 std::unique_ptr<SourceCoverageView> SubView{nullptr};
309 StringRef Funcname = DC.demangle(Function->Name);
311 if (Function->ExecutionCount > 0) {
312 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
313 auto SubViewExpansions = SubViewCoverage.getExpansions();
314 SubView = SourceCoverageView::create(
315 Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
316 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
319 unsigned FileID = Function->CountedRegions.front().FileID;
321 for (const auto &CR : Function->CountedRegions)
322 if (CR.FileID == FileID)
323 Line = std::max(CR.LineEnd, Line);
324 View->addInstantiation(Funcname, Line, std::move(SubView));
330 static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
331 sys::fs::file_status Status;
332 if (sys::fs::status(LHS, Status))
334 auto LHSTime = Status.getLastModificationTime();
335 if (sys::fs::status(RHS, Status))
337 auto RHSTime = Status.getLastModificationTime();
338 return LHSTime > RHSTime;
341 std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
342 for (StringRef ObjectFilename : ObjectFilenames)
343 if (modifiedTimeGT(ObjectFilename, PGOFilename))
344 warning("profile data may be out of date - object is newer",
347 CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches);
348 if (Error E = CoverageOrErr.takeError()) {
349 error("Failed to load coverage: " + toString(std::move(E)),
350 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "));
353 auto Coverage = std::move(CoverageOrErr.get());
354 unsigned Mismatched = Coverage->getMismatchedCount();
356 warning(utostr(Mismatched) + " functions have mismatched data");
358 if (ViewOpts.Debug) {
359 for (const auto &HashMismatch : Coverage->getHashMismatches())
360 errs() << "hash-mismatch: "
361 << "No profile record found for '" << HashMismatch.first << "'"
362 << " with hash = 0x" << utohexstr(HashMismatch.second) << "\n";
364 for (const auto &CounterMismatch : Coverage->getCounterMismatches())
365 errs() << "counter-mismatch: "
366 << "Coverage mapping for " << CounterMismatch.first
367 << " only has " << CounterMismatch.second
368 << " valid counter expressions\n";
372 remapPathNames(*Coverage);
374 if (!SourceFiles.empty())
375 removeUnmappedInputs(*Coverage);
377 demangleSymbols(*Coverage);
382 void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
386 // Convert remapping paths to native paths with trailing seperators.
387 auto nativeWithTrailing = [](StringRef Path) -> std::string {
390 SmallString<128> NativePath;
391 sys::path::native(Path, NativePath);
392 if (!sys::path::is_separator(NativePath.back()))
393 NativePath += sys::path::get_separator();
394 return NativePath.c_str();
396 std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
397 std::string RemapTo = nativeWithTrailing(PathRemapping->second);
399 // Create a mapping from coverage data file paths to local paths.
400 for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
401 SmallString<128> NativeFilename;
402 sys::path::native(Filename, NativeFilename);
403 if (NativeFilename.startswith(RemapFrom)) {
404 RemappedFilenames[Filename] =
405 RemapTo + NativeFilename.substr(RemapFrom.size()).str();
409 // Convert input files from local paths to coverage data file paths.
410 StringMap<std::string> InvRemappedFilenames;
411 for (const auto &RemappedFilename : RemappedFilenames)
412 InvRemappedFilenames[RemappedFilename.getValue()] = RemappedFilename.getKey();
414 for (std::string &Filename : SourceFiles) {
415 SmallString<128> NativeFilename;
416 sys::path::native(Filename, NativeFilename);
417 auto CovFileName = InvRemappedFilenames.find(NativeFilename);
418 if (CovFileName != InvRemappedFilenames.end())
419 Filename = CovFileName->second;
423 void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
424 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
426 auto UncoveredFilesIt = SourceFiles.end();
427 // The user may have specified source files which aren't in the coverage
428 // mapping. Filter these files away.
429 UncoveredFilesIt = std::remove_if(
430 SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
431 return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
435 SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
438 void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
439 if (!ViewOpts.hasDemangler())
442 // Pass function names to the demangler in a temporary file.
444 SmallString<256> InputPath;
446 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
448 error(InputPath, EC.message());
451 ToolOutputFile InputTOF{InputPath, InputFD};
453 unsigned NumSymbols = 0;
454 for (const auto &Function : Coverage.getCoveredFunctions()) {
455 InputTOF.os() << Function.Name << '\n';
458 InputTOF.os().close();
460 // Use another temporary file to store the demangler's output.
462 SmallString<256> OutputPath;
463 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
466 error(OutputPath, EC.message());
469 ToolOutputFile OutputTOF{OutputPath, OutputFD};
470 OutputTOF.os().close();
472 // Invoke the demangler.
473 std::vector<const char *> ArgsV;
474 for (const std::string &Arg : ViewOpts.DemanglerOpts)
475 ArgsV.push_back(Arg.c_str());
476 ArgsV.push_back(nullptr);
477 Optional<StringRef> Redirects[] = {InputPath.str(), OutputPath.str(), {""}};
479 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
480 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
481 /*memoryLimit=*/0, &ErrMsg);
483 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
487 // Parse the demangler's output.
488 auto BufOrError = MemoryBuffer::getFile(OutputPath);
490 error(OutputPath, BufOrError.getError().message());
494 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
496 SmallVector<StringRef, 8> Symbols;
497 StringRef DemanglerData = DemanglerBuf->getBuffer();
498 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
499 /*KeepEmpty=*/false);
500 if (Symbols.size() != NumSymbols) {
501 error("Demangler did not provide expected number of symbols");
505 // Cache the demangled names.
507 for (const auto &Function : Coverage.getCoveredFunctions())
508 // On Windows, lines in the demangler's output file end with "\r\n".
509 // Splitting by '\n' keeps '\r's, so cut them now.
510 DC.DemangledNames[Function.Name] = Symbols[I++].rtrim();
513 void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
514 CoverageMapping *Coverage,
515 CoveragePrinter *Printer,
516 bool ShowFilenames) {
517 auto View = createSourceFileView(SourceFile, *Coverage);
519 warning("The file '" + SourceFile + "' isn't covered.");
523 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
524 if (Error E = OSOrErr.takeError()) {
525 error("Could not create view file!", toString(std::move(E)));
528 auto OS = std::move(OSOrErr.get());
530 View->print(*OS.get(), /*Wholefile=*/true,
531 /*ShowSourceName=*/ShowFilenames,
532 /*ShowTitle=*/ViewOpts.hasOutputDirectory());
533 Printer->closeViewFile(std::move(OS));
536 int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
537 cl::opt<std::string> CovFilename(
538 cl::Positional, cl::desc("Covered executable or object file."));
540 cl::list<std::string> CovFilenames(
541 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
544 cl::list<std::string> InputSourceFiles(
545 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
547 cl::opt<bool> DebugDumpCollectedPaths(
548 "dump-collected-paths", cl::Optional, cl::Hidden,
549 cl::desc("Show the collected paths to source files"));
551 cl::opt<std::string, true> PGOFilename(
552 "instr-profile", cl::Required, cl::location(this->PGOFilename),
554 "File with the profile data obtained after an instrumented run"));
556 cl::list<std::string> Arches(
557 "arch", cl::desc("architectures of the coverage mapping binaries"));
559 cl::opt<bool> DebugDump("dump", cl::Optional,
560 cl::desc("Show internal debug dump"));
562 cl::opt<CoverageViewOptions::OutputFormat> Format(
563 "format", cl::desc("Output format for line-based coverage reports"),
564 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
566 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
568 cl::init(CoverageViewOptions::OutputFormat::Text));
570 cl::opt<std::string> PathRemap(
571 "path-equivalence", cl::Optional,
572 cl::desc("<from>,<to> Map coverage data paths to local source file "
575 cl::OptionCategory FilteringCategory("Function filtering options");
577 cl::list<std::string> NameFilters(
578 "name", cl::Optional,
579 cl::desc("Show code coverage only for functions with the given name"),
580 cl::ZeroOrMore, cl::cat(FilteringCategory));
582 cl::list<std::string> NameFilterFiles(
583 "name-whitelist", cl::Optional,
584 cl::desc("Show code coverage only for functions listed in the given "
586 cl::ZeroOrMore, cl::cat(FilteringCategory));
588 cl::list<std::string> NameRegexFilters(
589 "name-regex", cl::Optional,
590 cl::desc("Show code coverage only for functions that match the given "
591 "regular expression"),
592 cl::ZeroOrMore, cl::cat(FilteringCategory));
594 cl::opt<double> RegionCoverageLtFilter(
595 "region-coverage-lt", cl::Optional,
596 cl::desc("Show code coverage only for functions with region coverage "
597 "less than the given threshold"),
598 cl::cat(FilteringCategory));
600 cl::opt<double> RegionCoverageGtFilter(
601 "region-coverage-gt", cl::Optional,
602 cl::desc("Show code coverage only for functions with region coverage "
603 "greater than the given threshold"),
604 cl::cat(FilteringCategory));
606 cl::opt<double> LineCoverageLtFilter(
607 "line-coverage-lt", cl::Optional,
608 cl::desc("Show code coverage only for functions with line coverage less "
609 "than the given threshold"),
610 cl::cat(FilteringCategory));
612 cl::opt<double> LineCoverageGtFilter(
613 "line-coverage-gt", cl::Optional,
614 cl::desc("Show code coverage only for functions with line coverage "
615 "greater than the given threshold"),
616 cl::cat(FilteringCategory));
618 cl::opt<cl::boolOrDefault> UseColor(
619 "use-color", cl::desc("Emit colored output (default=autodetect)"),
620 cl::init(cl::BOU_UNSET));
622 cl::list<std::string> DemanglerOpts(
623 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
625 cl::opt<bool> RegionSummary(
626 "show-region-summary", cl::Optional,
627 cl::desc("Show region statistics in summary table"),
630 cl::opt<bool> InstantiationSummary(
631 "show-instantiation-summary", cl::Optional,
632 cl::desc("Show instantiation statistics in summary table"));
634 cl::opt<bool> SummaryOnly(
635 "summary-only", cl::Optional,
636 cl::desc("Export only summary information for each source file"));
638 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
639 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
640 ViewOpts.Debug = DebugDump;
642 if (!CovFilename.empty())
643 ObjectFilenames.emplace_back(CovFilename);
644 for (const std::string &Filename : CovFilenames)
645 ObjectFilenames.emplace_back(Filename);
646 if (ObjectFilenames.empty()) {
647 errs() << "No filenames specified!\n";
651 ViewOpts.Format = Format;
652 switch (ViewOpts.Format) {
653 case CoverageViewOptions::OutputFormat::Text:
654 ViewOpts.Colors = UseColor == cl::BOU_UNSET
655 ? sys::Process::StandardOutHasColors()
656 : UseColor == cl::BOU_TRUE;
658 case CoverageViewOptions::OutputFormat::HTML:
659 if (UseColor == cl::BOU_FALSE)
660 errs() << "Color output cannot be disabled when generating html.\n";
661 ViewOpts.Colors = true;
665 // If path-equivalence was given and is a comma seperated pair then set
667 auto EquivPair = StringRef(PathRemap).split(',');
668 if (!(EquivPair.first.empty() && EquivPair.second.empty()))
669 PathRemapping = EquivPair;
671 // If a demangler is supplied, check if it exists and register it.
672 if (DemanglerOpts.size()) {
673 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
674 if (!DemanglerPathOrErr) {
675 error("Could not find the demangler!",
676 DemanglerPathOrErr.getError().message());
679 DemanglerOpts[0] = *DemanglerPathOrErr;
680 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
683 // Read in -name-whitelist files.
684 if (!NameFilterFiles.empty()) {
685 std::string SpecialCaseListErr;
687 SpecialCaseList::create(NameFilterFiles, SpecialCaseListErr);
689 error(SpecialCaseListErr);
692 // Create the function filters
693 if (!NameFilters.empty() || NameWhitelist || !NameRegexFilters.empty()) {
694 auto NameFilterer = llvm::make_unique<CoverageFilters>();
695 for (const auto &Name : NameFilters)
696 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
698 NameFilterer->push_back(
699 llvm::make_unique<NameWhitelistCoverageFilter>(*NameWhitelist));
700 for (const auto &Regex : NameRegexFilters)
701 NameFilterer->push_back(
702 llvm::make_unique<NameRegexCoverageFilter>(Regex));
703 Filters.push_back(std::move(NameFilterer));
705 if (RegionCoverageLtFilter.getNumOccurrences() ||
706 RegionCoverageGtFilter.getNumOccurrences() ||
707 LineCoverageLtFilter.getNumOccurrences() ||
708 LineCoverageGtFilter.getNumOccurrences()) {
709 auto StatFilterer = llvm::make_unique<CoverageFilters>();
710 if (RegionCoverageLtFilter.getNumOccurrences())
711 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
712 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
713 if (RegionCoverageGtFilter.getNumOccurrences())
714 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
715 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
716 if (LineCoverageLtFilter.getNumOccurrences())
717 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
718 LineCoverageFilter::LessThan, LineCoverageLtFilter));
719 if (LineCoverageGtFilter.getNumOccurrences())
720 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
721 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
722 Filters.push_back(std::move(StatFilterer));
725 if (!Arches.empty()) {
726 for (const std::string &Arch : Arches) {
727 if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
728 error("Unknown architecture: " + Arch);
731 CoverageArches.emplace_back(Arch);
733 if (CoverageArches.size() != ObjectFilenames.size()) {
734 error("Number of architectures doesn't match the number of objects");
739 for (const std::string &File : InputSourceFiles)
742 if (DebugDumpCollectedPaths) {
743 for (const std::string &SF : SourceFiles)
744 outs() << SF << '\n';
748 ViewOpts.ShowRegionSummary = RegionSummary;
749 ViewOpts.ShowInstantiationSummary = InstantiationSummary;
750 ViewOpts.ExportSummaryOnly = SummaryOnly;
757 return show(argc, argv, commandLineParser);
759 return report(argc, argv, commandLineParser);
761 return export_(argc, argv, commandLineParser);
766 int CodeCoverageTool::show(int argc, const char **argv,
767 CommandLineParserType commandLineParser) {
769 cl::OptionCategory ViewCategory("Viewing options");
771 cl::opt<bool> ShowLineExecutionCounts(
772 "show-line-counts", cl::Optional,
773 cl::desc("Show the execution counts for each line"), cl::init(true),
774 cl::cat(ViewCategory));
776 cl::opt<bool> ShowRegions(
777 "show-regions", cl::Optional,
778 cl::desc("Show the execution counts for each region"),
779 cl::cat(ViewCategory));
781 cl::opt<bool> ShowBestLineRegionsCounts(
782 "show-line-counts-or-regions", cl::Optional,
783 cl::desc("Show the execution counts for each line, or the execution "
784 "counts for each region on lines that have multiple regions"),
785 cl::cat(ViewCategory));
787 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
788 cl::desc("Show expanded source regions"),
789 cl::cat(ViewCategory));
791 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
792 cl::desc("Show function instantiations"),
793 cl::init(true), cl::cat(ViewCategory));
795 cl::opt<std::string> ShowOutputDirectory(
796 "output-dir", cl::init(""),
797 cl::desc("Directory in which coverage information is written out"));
798 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
799 cl::aliasopt(ShowOutputDirectory));
801 cl::opt<uint32_t> TabSize(
802 "tab-size", cl::init(2),
804 "Set tab expansion size for html coverage reports (default = 2)"));
806 cl::opt<std::string> ProjectTitle(
807 "project-title", cl::Optional,
808 cl::desc("Set project title for the coverage report"));
810 cl::opt<unsigned> NumThreads(
811 "num-threads", cl::init(0),
812 cl::desc("Number of merge threads to use (default: autodetect)"));
813 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
814 cl::aliasopt(NumThreads));
816 auto Err = commandLineParser(argc, argv);
820 ViewOpts.ShowLineNumbers = true;
821 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
822 !ShowRegions || ShowBestLineRegionsCounts;
823 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
824 ViewOpts.ShowExpandedRegions = ShowExpansions;
825 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
826 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
827 ViewOpts.TabSize = TabSize;
828 ViewOpts.ProjectTitle = ProjectTitle;
830 if (ViewOpts.hasOutputDirectory()) {
831 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
832 error("Could not create output directory!", E.message());
837 sys::fs::file_status Status;
838 if (sys::fs::status(PGOFilename, Status)) {
839 error("profdata file error: can not get the file status. \n");
843 auto ModifiedTime = Status.getLastModificationTime();
844 std::string ModifiedTimeStr = to_string(ModifiedTime);
845 size_t found = ModifiedTimeStr.rfind(':');
846 ViewOpts.CreatedTimeStr = (found != std::string::npos)
847 ? "Created: " + ModifiedTimeStr.substr(0, found)
848 : "Created: " + ModifiedTimeStr;
850 auto Coverage = load();
854 auto Printer = CoveragePrinter::create(ViewOpts);
856 if (SourceFiles.empty())
857 // Get the source files from the function coverage mapping.
858 for (StringRef Filename : Coverage->getUniqueSourceFiles())
859 SourceFiles.push_back(Filename);
861 // Create an index out of the source files.
862 if (ViewOpts.hasOutputDirectory()) {
863 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage, Filters)) {
864 error("Could not create index file!", toString(std::move(E)));
869 if (!Filters.empty()) {
870 // Build the map of filenames to functions.
871 std::map<llvm::StringRef, std::vector<const FunctionRecord *>>
873 for (const auto &SourceFile : SourceFiles)
874 for (const auto &Function : Coverage->getCoveredFunctions(SourceFile))
875 if (Filters.matches(*Coverage.get(), Function))
876 FilenameFunctionMap[SourceFile].push_back(&Function);
878 // Only print filter matching functions for each file.
879 for (const auto &FileFunc : FilenameFunctionMap) {
880 StringRef File = FileFunc.first;
881 const auto &Functions = FileFunc.second;
883 auto OSOrErr = Printer->createViewFile(File, /*InToplevel=*/false);
884 if (Error E = OSOrErr.takeError()) {
885 error("Could not create view file!", toString(std::move(E)));
888 auto OS = std::move(OSOrErr.get());
890 bool ShowTitle = ViewOpts.hasOutputDirectory();
891 for (const auto *Function : Functions) {
892 auto FunctionView = createFunctionView(*Function, *Coverage);
894 warning("Could not read coverage for '" + Function->Name + "'.");
897 FunctionView->print(*OS.get(), /*WholeFile=*/false,
898 /*ShowSourceName=*/true, ShowTitle);
902 Printer->closeViewFile(std::move(OS));
909 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
910 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
912 // If NumThreads is not specified, auto-detect a good default.
915 std::max(1U, std::min(llvm::heavyweight_hardware_concurrency(),
916 unsigned(SourceFiles.size())));
918 if (!ViewOpts.hasOutputDirectory() || NumThreads == 1) {
919 for (const std::string &SourceFile : SourceFiles)
920 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
923 // In -output-dir mode, it's safe to use multiple threads to print files.
924 ThreadPool Pool(NumThreads);
925 for (const std::string &SourceFile : SourceFiles)
926 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
927 Coverage.get(), Printer.get(), ShowFilenames);
934 int CodeCoverageTool::report(int argc, const char **argv,
935 CommandLineParserType commandLineParser) {
936 cl::opt<bool> ShowFunctionSummaries(
937 "show-functions", cl::Optional, cl::init(false),
938 cl::desc("Show coverage summaries for each function"));
940 auto Err = commandLineParser(argc, argv);
944 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
945 error("HTML output for summary reports is not yet supported.");
949 auto Coverage = load();
953 CoverageReport Report(ViewOpts, *Coverage.get());
954 if (!ShowFunctionSummaries) {
955 if (SourceFiles.empty())
956 Report.renderFileReports(llvm::outs());
958 Report.renderFileReports(llvm::outs(), SourceFiles);
960 if (SourceFiles.empty()) {
961 error("Source files must be specified when -show-functions=true is "
966 Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
971 int CodeCoverageTool::export_(int argc, const char **argv,
972 CommandLineParserType commandLineParser) {
974 auto Err = commandLineParser(argc, argv);
978 if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text) {
979 error("Coverage data can only be exported as textual JSON.");
983 auto Coverage = load();
985 error("Could not load coverage information");
989 exportCoverageDataToJson(*Coverage.get(), ViewOpts, outs());
994 int showMain(int argc, const char *argv[]) {
995 CodeCoverageTool Tool;
996 return Tool.run(CodeCoverageTool::Show, argc, argv);
999 int reportMain(int argc, const char *argv[]) {
1000 CodeCoverageTool Tool;
1001 return Tool.run(CodeCoverageTool::Report, argc, argv);
1004 int exportMain(int argc, const char *argv[]) {
1005 CodeCoverageTool Tool;
1006 return Tool.run(CodeCoverageTool::Export, argc, argv);