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