CodeCoverage.cpp 34 KB

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