CodeCoverage.cpp 30 KB

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