CodeCoverage.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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. DC.DemangledNames[Function.Name] = Symbols[I++];
  389. }
  390. void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
  391. CoverageMapping *Coverage,
  392. CoveragePrinter *Printer,
  393. bool ShowFilenames) {
  394. auto View = createSourceFileView(SourceFile, *Coverage);
  395. if (!View) {
  396. warning("The file '" + SourceFile + "' isn't covered.");
  397. return;
  398. }
  399. auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
  400. if (Error E = OSOrErr.takeError()) {
  401. error("Could not create view file!", toString(std::move(E)));
  402. return;
  403. }
  404. auto OS = std::move(OSOrErr.get());
  405. View->print(*OS.get(), /*Wholefile=*/true,
  406. /*ShowSourceName=*/ShowFilenames);
  407. Printer->closeViewFile(std::move(OS));
  408. }
  409. int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
  410. cl::opt<std::string> CovFilename(
  411. cl::Positional, cl::desc("Covered executable or object file."));
  412. cl::list<std::string> CovFilenames(
  413. "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
  414. cl::CommaSeparated);
  415. cl::list<std::string> InputSourceFiles(
  416. cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
  417. cl::opt<bool> DebugDumpCollectedPaths(
  418. "dump-collected-paths", cl::Optional, cl::Hidden,
  419. cl::desc("Show the collected paths to source files"));
  420. cl::opt<std::string, true> PGOFilename(
  421. "instr-profile", cl::Required, cl::location(this->PGOFilename),
  422. cl::desc(
  423. "File with the profile data obtained after an instrumented run"));
  424. cl::opt<std::string> Arch(
  425. "arch", cl::desc("architecture of the coverage mapping binary"));
  426. cl::opt<bool> DebugDump("dump", cl::Optional,
  427. cl::desc("Show internal debug dump"));
  428. cl::opt<CoverageViewOptions::OutputFormat> Format(
  429. "format", cl::desc("Output format for line-based coverage reports"),
  430. cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
  431. "Text output"),
  432. clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
  433. "HTML output")),
  434. cl::init(CoverageViewOptions::OutputFormat::Text));
  435. cl::opt<bool> FilenameEquivalence(
  436. "filename-equivalence", cl::Optional,
  437. cl::desc("Treat source files as equivalent to paths in the coverage data "
  438. "when the file names match, even if the full paths do not"));
  439. cl::OptionCategory FilteringCategory("Function filtering options");
  440. cl::list<std::string> NameFilters(
  441. "name", cl::Optional,
  442. cl::desc("Show code coverage only for functions with the given name"),
  443. cl::ZeroOrMore, cl::cat(FilteringCategory));
  444. cl::list<std::string> NameRegexFilters(
  445. "name-regex", cl::Optional,
  446. cl::desc("Show code coverage only for functions that match the given "
  447. "regular expression"),
  448. cl::ZeroOrMore, cl::cat(FilteringCategory));
  449. cl::opt<double> RegionCoverageLtFilter(
  450. "region-coverage-lt", cl::Optional,
  451. cl::desc("Show code coverage only for functions with region coverage "
  452. "less than the given threshold"),
  453. cl::cat(FilteringCategory));
  454. cl::opt<double> RegionCoverageGtFilter(
  455. "region-coverage-gt", cl::Optional,
  456. cl::desc("Show code coverage only for functions with region coverage "
  457. "greater than the given threshold"),
  458. cl::cat(FilteringCategory));
  459. cl::opt<double> LineCoverageLtFilter(
  460. "line-coverage-lt", cl::Optional,
  461. cl::desc("Show code coverage only for functions with line coverage less "
  462. "than the given threshold"),
  463. cl::cat(FilteringCategory));
  464. cl::opt<double> LineCoverageGtFilter(
  465. "line-coverage-gt", cl::Optional,
  466. cl::desc("Show code coverage only for functions with line coverage "
  467. "greater than the given threshold"),
  468. cl::cat(FilteringCategory));
  469. cl::opt<cl::boolOrDefault> UseColor(
  470. "use-color", cl::desc("Emit colored output (default=autodetect)"),
  471. cl::init(cl::BOU_UNSET));
  472. cl::list<std::string> DemanglerOpts(
  473. "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
  474. auto commandLineParser = [&, this](int argc, const char **argv) -> int {
  475. cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
  476. ViewOpts.Debug = DebugDump;
  477. CompareFilenamesOnly = FilenameEquivalence;
  478. if (!CovFilename.empty())
  479. ObjectFilenames.emplace_back(CovFilename);
  480. for (const std::string &Filename : CovFilenames)
  481. ObjectFilenames.emplace_back(Filename);
  482. if (ObjectFilenames.empty()) {
  483. errs() << "No filenames specified!\n";
  484. ::exit(1);
  485. }
  486. ViewOpts.Format = Format;
  487. switch (ViewOpts.Format) {
  488. case CoverageViewOptions::OutputFormat::Text:
  489. ViewOpts.Colors = UseColor == cl::BOU_UNSET
  490. ? sys::Process::StandardOutHasColors()
  491. : UseColor == cl::BOU_TRUE;
  492. break;
  493. case CoverageViewOptions::OutputFormat::HTML:
  494. if (UseColor == cl::BOU_FALSE)
  495. errs() << "Color output cannot be disabled when generating html.\n";
  496. ViewOpts.Colors = true;
  497. break;
  498. }
  499. // If a demangler is supplied, check if it exists and register it.
  500. if (DemanglerOpts.size()) {
  501. auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
  502. if (!DemanglerPathOrErr) {
  503. error("Could not find the demangler!",
  504. DemanglerPathOrErr.getError().message());
  505. return 1;
  506. }
  507. DemanglerOpts[0] = *DemanglerPathOrErr;
  508. ViewOpts.DemanglerOpts.swap(DemanglerOpts);
  509. }
  510. // Create the function filters
  511. if (!NameFilters.empty() || !NameRegexFilters.empty()) {
  512. auto NameFilterer = new CoverageFilters;
  513. for (const auto &Name : NameFilters)
  514. NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
  515. for (const auto &Regex : NameRegexFilters)
  516. NameFilterer->push_back(
  517. llvm::make_unique<NameRegexCoverageFilter>(Regex));
  518. Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
  519. }
  520. if (RegionCoverageLtFilter.getNumOccurrences() ||
  521. RegionCoverageGtFilter.getNumOccurrences() ||
  522. LineCoverageLtFilter.getNumOccurrences() ||
  523. LineCoverageGtFilter.getNumOccurrences()) {
  524. auto StatFilterer = new CoverageFilters;
  525. if (RegionCoverageLtFilter.getNumOccurrences())
  526. StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
  527. RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
  528. if (RegionCoverageGtFilter.getNumOccurrences())
  529. StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
  530. RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
  531. if (LineCoverageLtFilter.getNumOccurrences())
  532. StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
  533. LineCoverageFilter::LessThan, LineCoverageLtFilter));
  534. if (LineCoverageGtFilter.getNumOccurrences())
  535. StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
  536. RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
  537. Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
  538. }
  539. if (!Arch.empty() &&
  540. Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
  541. error("Unknown architecture: " + Arch);
  542. return 1;
  543. }
  544. CoverageArch = Arch;
  545. for (const std::string &File : InputSourceFiles)
  546. collectPaths(File);
  547. if (DebugDumpCollectedPaths) {
  548. for (const std::string &SF : SourceFiles)
  549. outs() << SF << '\n';
  550. ::exit(0);
  551. }
  552. return 0;
  553. };
  554. switch (Cmd) {
  555. case Show:
  556. return show(argc, argv, commandLineParser);
  557. case Report:
  558. return report(argc, argv, commandLineParser);
  559. case Export:
  560. return export_(argc, argv, commandLineParser);
  561. }
  562. return 0;
  563. }
  564. int CodeCoverageTool::show(int argc, const char **argv,
  565. CommandLineParserType commandLineParser) {
  566. cl::OptionCategory ViewCategory("Viewing options");
  567. cl::opt<bool> ShowLineExecutionCounts(
  568. "show-line-counts", cl::Optional,
  569. cl::desc("Show the execution counts for each line"), cl::init(true),
  570. cl::cat(ViewCategory));
  571. cl::opt<bool> ShowRegions(
  572. "show-regions", cl::Optional,
  573. cl::desc("Show the execution counts for each region"),
  574. cl::cat(ViewCategory));
  575. cl::opt<bool> ShowBestLineRegionsCounts(
  576. "show-line-counts-or-regions", cl::Optional,
  577. cl::desc("Show the execution counts for each line, or the execution "
  578. "counts for each region on lines that have multiple regions"),
  579. cl::cat(ViewCategory));
  580. cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
  581. cl::desc("Show expanded source regions"),
  582. cl::cat(ViewCategory));
  583. cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
  584. cl::desc("Show function instantiations"),
  585. cl::cat(ViewCategory));
  586. cl::opt<std::string> ShowOutputDirectory(
  587. "output-dir", cl::init(""),
  588. cl::desc("Directory in which coverage information is written out"));
  589. cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
  590. cl::aliasopt(ShowOutputDirectory));
  591. cl::opt<uint32_t> TabSize(
  592. "tab-size", cl::init(2),
  593. cl::desc(
  594. "Set tab expansion size for html coverage reports (default = 2)"));
  595. cl::opt<std::string> ProjectTitle(
  596. "project-title", cl::Optional,
  597. cl::desc("Set project title for the coverage report"));
  598. auto Err = commandLineParser(argc, argv);
  599. if (Err)
  600. return Err;
  601. ViewOpts.ShowLineNumbers = true;
  602. ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
  603. !ShowRegions || ShowBestLineRegionsCounts;
  604. ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
  605. ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
  606. ViewOpts.ShowExpandedRegions = ShowExpansions;
  607. ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
  608. ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
  609. ViewOpts.TabSize = TabSize;
  610. ViewOpts.ProjectTitle = ProjectTitle;
  611. if (ViewOpts.hasOutputDirectory()) {
  612. if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
  613. error("Could not create output directory!", E.message());
  614. return 1;
  615. }
  616. }
  617. sys::fs::file_status Status;
  618. if (sys::fs::status(PGOFilename, Status)) {
  619. error("profdata file error: can not get the file status. \n");
  620. return 1;
  621. }
  622. auto ModifiedTime = Status.getLastModificationTime();
  623. std::string ModifiedTimeStr = to_string(ModifiedTime);
  624. size_t found = ModifiedTimeStr.rfind(':');
  625. ViewOpts.CreatedTimeStr = (found != std::string::npos)
  626. ? "Created: " + ModifiedTimeStr.substr(0, found)
  627. : "Created: " + ModifiedTimeStr;
  628. auto Coverage = load();
  629. if (!Coverage)
  630. return 1;
  631. auto Printer = CoveragePrinter::create(ViewOpts);
  632. if (!Filters.empty()) {
  633. auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
  634. if (Error E = OSOrErr.takeError()) {
  635. error("Could not create view file!", toString(std::move(E)));
  636. return 1;
  637. }
  638. auto OS = std::move(OSOrErr.get());
  639. // Show functions.
  640. for (const auto &Function : Coverage->getCoveredFunctions()) {
  641. if (!Filters.matches(Function))
  642. continue;
  643. auto mainView = createFunctionView(Function, *Coverage);
  644. if (!mainView) {
  645. warning("Could not read coverage for '" + Function.Name + "'.");
  646. continue;
  647. }
  648. mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
  649. }
  650. Printer->closeViewFile(std::move(OS));
  651. return 0;
  652. }
  653. // Show files
  654. bool ShowFilenames =
  655. (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
  656. (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
  657. if (SourceFiles.empty())
  658. // Get the source files from the function coverage mapping.
  659. for (StringRef Filename : Coverage->getUniqueSourceFiles())
  660. SourceFiles.push_back(Filename);
  661. // Create an index out of the source files.
  662. if (ViewOpts.hasOutputDirectory()) {
  663. if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) {
  664. error("Could not create index file!", toString(std::move(E)));
  665. return 1;
  666. }
  667. }
  668. // FIXME: Sink the hardware_concurrency() == 1 check into ThreadPool.
  669. if (!ViewOpts.hasOutputDirectory() ||
  670. std::thread::hardware_concurrency() == 1) {
  671. for (const std::string &SourceFile : SourceFiles)
  672. writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
  673. ShowFilenames);
  674. } else {
  675. // In -output-dir mode, it's safe to use multiple threads to print files.
  676. ThreadPool Pool;
  677. for (const std::string &SourceFile : SourceFiles)
  678. Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
  679. Coverage.get(), Printer.get(), ShowFilenames);
  680. Pool.wait();
  681. }
  682. return 0;
  683. }
  684. int CodeCoverageTool::report(int argc, const char **argv,
  685. CommandLineParserType commandLineParser) {
  686. auto Err = commandLineParser(argc, argv);
  687. if (Err)
  688. return Err;
  689. if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
  690. error("HTML output for summary reports is not yet supported.");
  691. auto Coverage = load();
  692. if (!Coverage)
  693. return 1;
  694. CoverageReport Report(ViewOpts, *Coverage.get());
  695. if (SourceFiles.empty())
  696. Report.renderFileReports(llvm::outs());
  697. else
  698. Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
  699. return 0;
  700. }
  701. int CodeCoverageTool::export_(int argc, const char **argv,
  702. CommandLineParserType commandLineParser) {
  703. auto Err = commandLineParser(argc, argv);
  704. if (Err)
  705. return Err;
  706. auto Coverage = load();
  707. if (!Coverage) {
  708. error("Could not load coverage information");
  709. return 1;
  710. }
  711. exportCoverageDataToJson(*Coverage.get(), outs());
  712. return 0;
  713. }
  714. int showMain(int argc, const char *argv[]) {
  715. CodeCoverageTool Tool;
  716. return Tool.run(CodeCoverageTool::Show, argc, argv);
  717. }
  718. int reportMain(int argc, const char *argv[]) {
  719. CodeCoverageTool Tool;
  720. return Tool.run(CodeCoverageTool::Report, argc, argv);
  721. }
  722. int exportMain(int argc, const char *argv[]) {
  723. CodeCoverageTool Tool;
  724. return Tool.run(CodeCoverageTool::Export, argc, argv);
  725. }