CodeCoverage.cpp 30 KB

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