CodeCoverage.cpp 31 KB

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