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