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