CodeCoverage.cpp 25 KB

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