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