CodeCoverage.cpp 36 KB

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