blob: 728e00e7c3c2b0040efa448da9937d6a2f0e8d87 [file] [log] [blame]
Alex Lorenz6c7a6a12014-08-22 22:56:03 +00001//===- 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
Max Morozfc04e852018-01-04 19:33:29 +000016#include "CoverageExporterJson.h"
Max Morozfcdc2672018-11-09 16:10:44 +000017#include "CoverageExporterLcov.h"
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000018#include "CoverageFilters.h"
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000019#include "CoverageReport.h"
Vedant Kumar48584472017-02-05 20:10:58 +000020#include "CoverageSummaryInfo.h"
Chandler Carruth1b279142015-01-14 11:23:27 +000021#include "CoverageViewOptions.h"
Easwaran Ramana96d53702016-04-29 18:53:05 +000022#include "RenderingSupport.h"
Chandler Carruth1b279142015-01-14 11:23:27 +000023#include "SourceCoverageView.h"
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000024#include "llvm/ADT/SmallString.h"
Chandler Carruth1b279142015-01-14 11:23:27 +000025#include "llvm/ADT/StringRef.h"
Justin Bognerd39109d2015-03-11 02:30:51 +000026#include "llvm/ADT/Triple.h"
Easwaran Ramana96d53702016-04-29 18:53:05 +000027#include "llvm/ProfileData/Coverage/CoverageMapping.h"
Chandler Carruth1b279142015-01-14 11:23:27 +000028#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/FileSystem.h"
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000031#include "llvm/Support/Format.h"
Vedant Kumar13ca1cc2016-07-15 22:44:57 +000032#include "llvm/Support/MemoryBuffer.h"
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000033#include "llvm/Support/Path.h"
Justin Bognercc690d62015-03-19 00:02:23 +000034#include "llvm/Support/Process.h"
Vedant Kumar13ca1cc2016-07-15 22:44:57 +000035#include "llvm/Support/Program.h"
Pavel Labath2864c2a2016-10-24 10:59:17 +000036#include "llvm/Support/ScopedPrinter.h"
Vedant Kumar9240c452016-07-13 21:38:36 +000037#include "llvm/Support/ThreadPool.h"
Max Morozd6352ca2018-01-05 16:15:07 +000038#include "llvm/Support/Threading.h"
Vedant Kumar13ca1cc2016-07-15 22:44:57 +000039#include "llvm/Support/ToolOutputFile.h"
Sean Eveson078c2c32017-09-28 10:07:30 +000040
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000041#include <functional>
Sean Eveson078c2c32017-09-28 10:07:30 +000042#include <map>
Justin Bogner39d5e802014-09-09 05:32:18 +000043#include <system_error>
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000044
45using namespace llvm;
46using namespace coverage;
47
Vedant Kumar5b5c5e72016-10-25 00:08:33 +000048void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping,
Vedant Kumar31b24fc2017-09-08 18:44:49 +000049 const CoverageViewOptions &Options,
Vedant Kumar53397d12016-07-26 22:50:58 +000050 raw_ostream &OS);
51
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000052namespace {
Adrian Prantl26b584c2018-05-01 15:54:18 +000053/// The implementation of the coverage tool.
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000054class CodeCoverageTool {
55public:
56 enum Command {
Adrian Prantl26b584c2018-05-01 15:54:18 +000057 /// The show command.
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000058 Show,
Adrian Prantl26b584c2018-05-01 15:54:18 +000059 /// The report command.
Vedant Kumar53397d12016-07-26 22:50:58 +000060 Report,
Adrian Prantl26b584c2018-05-01 15:54:18 +000061 /// The export command.
Vedant Kumar53397d12016-07-26 22:50:58 +000062 Export
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000063 };
64
Vedant Kumarae0e2432016-09-22 21:49:47 +000065 int run(Command Cmd, int argc, const char **argv);
66
67private:
Adrian Prantl26b584c2018-05-01 15:54:18 +000068 /// Print the error message to the error output stream.
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000069 void error(const Twine &Message, StringRef Whence = "");
70
Adrian Prantl26b584c2018-05-01 15:54:18 +000071 /// Print the warning message to the error output stream.
Vedant Kumara3ff2122016-07-18 17:53:12 +000072 void warning(const Twine &Message, StringRef Whence = "");
Vedant Kumar9240c452016-07-13 21:38:36 +000073
Adrian Prantl26b584c2018-05-01 15:54:18 +000074 /// Convert \p Path into an absolute path and append it to the list
Vedant Kumarfd066352016-09-23 18:57:32 +000075 /// of collected paths.
Vedant Kumar75f03af2016-06-28 16:12:18 +000076 void addCollectedPath(const std::string &Path);
77
Adrian Prantl26b584c2018-05-01 15:54:18 +000078 /// If \p Path is a regular file, collect the path. If it's a
Vedant Kumaref76be02016-09-22 21:49:43 +000079 /// directory, recursively collect all of the paths within the directory.
80 void collectPaths(const std::string &Path);
81
Adrian Prantl26b584c2018-05-01 15:54:18 +000082 /// Return a memory buffer for the given source file.
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000083 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
84
Adrian Prantl26b584c2018-05-01 15:54:18 +000085 /// Create source views for the expansions of the view.
Justin Bogner9eb38162014-09-20 15:31:56 +000086 void attachExpansionSubViews(SourceCoverageView &View,
87 ArrayRef<ExpansionRecord> Expansions,
Vedant Kumar7b18a762016-07-15 01:19:33 +000088 const CoverageMapping &Coverage);
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000089
Adrian Prantl26b584c2018-05-01 15:54:18 +000090 /// Create the source view of a particular function.
Justin Bogner297149b2014-09-19 19:07:17 +000091 std::unique_ptr<SourceCoverageView>
Vedant Kumar7b18a762016-07-15 01:19:33 +000092 createFunctionView(const FunctionRecord &Function,
93 const CoverageMapping &Coverage);
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000094
Adrian Prantl26b584c2018-05-01 15:54:18 +000095 /// Create the main source view of a particular source file.
Justin Bogner297149b2014-09-19 19:07:17 +000096 std::unique_ptr<SourceCoverageView>
Vedant Kumar7b18a762016-07-15 01:19:33 +000097 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
Alex Lorenz6c7a6a12014-08-22 22:56:03 +000098
Adrian Prantl26b584c2018-05-01 15:54:18 +000099 /// Load the coverage mapping data. Return nullptr if an error occurred.
Justin Bogner9eb38162014-09-20 15:31:56 +0000100 std::unique_ptr<CoverageMapping> load();
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000101
Adrian Prantl26b584c2018-05-01 15:54:18 +0000102 /// Create a mapping from files in the Coverage data to local copies
Sean Eveson8574d592017-08-14 10:20:12 +0000103 /// (path-equivalence).
104 void remapPathNames(const CoverageMapping &Coverage);
105
Adrian Prantl26b584c2018-05-01 15:54:18 +0000106 /// Remove input source files which aren't mapped by \p Coverage.
Vedant Kumar3de4fb32016-09-23 20:13:41 +0000107 void removeUnmappedInputs(const CoverageMapping &Coverage);
108
Adrian Prantl26b584c2018-05-01 15:54:18 +0000109 /// If a demangler is available, demangle all symbol names.
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000110 void demangleSymbols(const CoverageMapping &Coverage);
111
Adrian Prantl26b584c2018-05-01 15:54:18 +0000112 /// Write out a source file view to the filesystem.
Vedant Kumar4c50ebb2016-10-19 17:55:44 +0000113 void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
114 CoveragePrinter *Printer, bool ShowFilenames);
115
Benjamin Kramer36538ff2016-06-08 19:09:22 +0000116 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000117
Max Morozfc04e852018-01-04 19:33:29 +0000118 int doShow(int argc, const char **argv,
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000119 CommandLineParserType commandLineParser);
120
Max Morozfc04e852018-01-04 19:33:29 +0000121 int doReport(int argc, const char **argv,
122 CommandLineParserType commandLineParser);
123
124 int doExport(int argc, const char **argv,
125 CommandLineParserType commandLineParser);
Vedant Kumar53397d12016-07-26 22:50:58 +0000126
Vedant Kumard4998ec2016-10-25 17:40:55 +0000127 std::vector<StringRef> ObjectFilenames;
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000128 CoverageViewOptions ViewOpts;
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000129 CoverageFiltersMatchAll Filters;
Max Moroz06fa6832018-04-09 15:20:35 +0000130 CoverageFilters IgnoreFilenameFilters;
Vedant Kumarae0e2432016-09-22 21:49:47 +0000131
132 /// The path to the indexed profile.
133 std::string PGOFilename;
134
135 /// A list of input source files.
Vedant Kumarfd066352016-09-23 18:57:32 +0000136 std::vector<std::string> SourceFiles;
Vedant Kumarae0e2432016-09-22 21:49:47 +0000137
Sean Eveson8574d592017-08-14 10:20:12 +0000138 /// In -path-equivalence mode, this maps the absolute paths from the coverage
139 /// mapping data to the input source files.
Justin Bognerddbcfa02014-09-19 08:13:12 +0000140 StringMap<std::string> RemappedFilenames;
Vedant Kumarae0e2432016-09-22 21:49:47 +0000141
Sean Eveson8574d592017-08-14 10:20:12 +0000142 /// The coverage data path to be remapped from, and the source path to be
143 /// remapped to, when using -path-equivalence.
144 Optional<std::pair<std::string, std::string>> PathRemapping;
145
Vedant Kumarae0e2432016-09-22 21:49:47 +0000146 /// The architecture the coverage mapping data targets.
Vedant Kumare72b8812017-08-01 21:23:26 +0000147 std::vector<StringRef> CoverageArches;
Vedant Kumar75f03af2016-06-28 16:12:18 +0000148
Vedant Kumar48584472017-02-05 20:10:58 +0000149 /// A cache for demangled symbols.
150 DemangleCache DC;
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000151
Vedant Kumar95f97422017-02-05 20:10:55 +0000152 /// A lock which guards printing to stderr.
Vedant Kumara3ff2122016-07-18 17:53:12 +0000153 std::mutex ErrsLock;
Vedant Kumar9240c452016-07-13 21:38:36 +0000154
Vedant Kumara5ec41d2016-07-15 22:44:54 +0000155 /// A container for input source file buffers.
Vedant Kumar9240c452016-07-13 21:38:36 +0000156 std::mutex LoadedSourceFilesLock;
157 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
158 LoadedSourceFiles;
Sean Eveson10edef12017-08-31 09:11:31 +0000159
160 /// Whitelist from -name-whitelist to be used for filtering.
161 std::unique_ptr<SpecialCaseList> NameWhitelist;
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000162};
163}
164
Vedant Kumar9240c452016-07-13 21:38:36 +0000165static std::string getErrorString(const Twine &Message, StringRef Whence,
166 bool Warning) {
167 std::string Str = (Warning ? "warning" : "error");
168 Str += ": ";
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000169 if (!Whence.empty())
Vedant Kumarb972a0f2016-07-15 01:53:39 +0000170 Str += Whence.str() + ": ";
Vedant Kumar9240c452016-07-13 21:38:36 +0000171 Str += Message.str() + "\n";
172 return Str;
173}
174
175void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
Vedant Kumara3ff2122016-07-18 17:53:12 +0000176 std::unique_lock<std::mutex> Guard{ErrsLock};
177 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
178 << getErrorString(Message, Whence, false);
Vedant Kumar9240c452016-07-13 21:38:36 +0000179}
180
Vedant Kumara3ff2122016-07-18 17:53:12 +0000181void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
182 std::unique_lock<std::mutex> Guard{ErrsLock};
183 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
184 << getErrorString(Message, Whence, true);
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000185}
186
Vedant Kumar75f03af2016-06-28 16:12:18 +0000187void CodeCoverageTool::addCollectedPath(const std::string &Path) {
Sean Eveson8574d592017-08-14 10:20:12 +0000188 SmallString<128> EffectivePath(Path);
189 if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
190 error(EC.message(), Path);
191 return;
Vedant Kumaref76be02016-09-22 21:49:43 +0000192 }
Sean Eveson8574d592017-08-14 10:20:12 +0000193 sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true);
Max Moroz06fa6832018-04-09 15:20:35 +0000194 if (!IgnoreFilenameFilters.matchesFilename(EffectivePath))
195 SourceFiles.emplace_back(EffectivePath.str());
Vedant Kumar75f03af2016-06-28 16:12:18 +0000196}
197
Vedant Kumaref76be02016-09-22 21:49:43 +0000198void CodeCoverageTool::collectPaths(const std::string &Path) {
199 llvm::sys::fs::file_status Status;
200 llvm::sys::fs::status(Path, Status);
201 if (!llvm::sys::fs::exists(Status)) {
Sean Eveson8574d592017-08-14 10:20:12 +0000202 if (PathRemapping)
Vedant Kumaref76be02016-09-22 21:49:43 +0000203 addCollectedPath(Path);
204 else
Max Moroz2cb4aed2018-04-05 19:43:24 +0000205 warning("Source file doesn't exist, proceeded by ignoring it.", Path);
Vedant Kumaref76be02016-09-22 21:49:43 +0000206 return;
207 }
208
209 if (llvm::sys::fs::is_regular_file(Status)) {
210 addCollectedPath(Path);
211 return;
212 }
213
214 if (llvm::sys::fs::is_directory(Status)) {
215 std::error_code EC;
216 for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
Max Moroz2cb4aed2018-04-05 19:43:24 +0000217 F != E; F.increment(EC)) {
218
Sam McCalla46ae182018-10-01 12:17:05 +0000219 auto Status = F->status();
220 if (!Status) {
221 warning(Status.getError().message(), F->path());
Max Moroz2cb4aed2018-04-05 19:43:24 +0000222 continue;
223 }
224
Sam McCalla46ae182018-10-01 12:17:05 +0000225 if (Status->type() == llvm::sys::fs::file_type::regular_file)
Vedant Kumaref76be02016-09-22 21:49:43 +0000226 addCollectedPath(F->path());
227 }
Vedant Kumaref76be02016-09-22 21:49:43 +0000228 }
229}
230
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000231ErrorOr<const MemoryBuffer &>
232CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bognerddbcfa02014-09-19 08:13:12 +0000233 // If we've remapped filenames, look up the real location for this file.
Vedant Kumar343b2712016-07-15 01:19:36 +0000234 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Justin Bognerddbcfa02014-09-19 08:13:12 +0000235 if (!RemappedFilenames.empty()) {
236 auto Loc = RemappedFilenames.find(SourceFile);
237 if (Loc != RemappedFilenames.end())
238 SourceFile = Loc->second;
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000239 }
Justin Bognerddbcfa02014-09-19 08:13:12 +0000240 for (const auto &Files : LoadedSourceFiles)
241 if (sys::fs::equivalent(SourceFile, Files.first))
242 return *Files.second;
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000243 auto Buffer = MemoryBuffer::getFile(SourceFile);
244 if (auto EC = Buffer.getError()) {
Vedant Kumara3ff2122016-07-18 17:53:12 +0000245 error(EC.message(), SourceFile);
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000246 return EC;
247 }
Benjamin Kramer9589ff82015-05-29 19:43:39 +0000248 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000249 return *LoadedSourceFiles.back().second;
250}
251
Vedant Kumar7b18a762016-07-15 01:19:33 +0000252void CodeCoverageTool::attachExpansionSubViews(
253 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
254 const CoverageMapping &Coverage) {
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000255 if (!ViewOpts.ShowExpandedRegions)
256 return;
Justin Bogner9eb38162014-09-20 15:31:56 +0000257 for (const auto &Expansion : Expansions) {
258 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
259 if (ExpansionCoverage.empty())
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000260 continue;
Justin Bogner9eb38162014-09-20 15:31:56 +0000261 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
262 if (!SourceBuffer)
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000263 continue;
Justin Bogner9eb38162014-09-20 15:31:56 +0000264
265 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumara9bf3122016-06-25 02:58:30 +0000266 auto SubView =
267 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
268 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner9eb38162014-09-20 15:31:56 +0000269 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
270 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000271 }
272}
273
Justin Bogner297149b2014-09-19 19:07:17 +0000274std::unique_ptr<SourceCoverageView>
Justin Bogner9eb38162014-09-20 15:31:56 +0000275CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumar7b18a762016-07-15 01:19:33 +0000276 const CoverageMapping &Coverage) {
Justin Bogner9eb38162014-09-20 15:31:56 +0000277 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
278 if (FunctionCoverage.empty())
Justin Bogner297149b2014-09-19 19:07:17 +0000279 return nullptr;
Justin Bogner9eb38162014-09-20 15:31:56 +0000280 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner297149b2014-09-19 19:07:17 +0000281 if (!SourceBuffer)
282 return nullptr;
Justin Bogner9eb38162014-09-20 15:31:56 +0000283
284 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumar48584472017-02-05 20:10:58 +0000285 auto View = SourceCoverageView::create(DC.demangle(Function.Name),
Vedant Kumard2e36ca2016-09-08 00:56:48 +0000286 SourceBuffer.get(), ViewOpts,
287 std::move(FunctionCoverage));
Justin Bogner9eb38162014-09-20 15:31:56 +0000288 attachExpansionSubViews(*View, Expansions, Coverage);
289
290 return View;
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000291}
292
Justin Bogner9eb38162014-09-20 15:31:56 +0000293std::unique_ptr<SourceCoverageView>
294CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumar7b18a762016-07-15 01:19:33 +0000295 const CoverageMapping &Coverage) {
Justin Bogner297149b2014-09-19 19:07:17 +0000296 auto SourceBuffer = getSourceFile(SourceFile);
297 if (!SourceBuffer)
298 return nullptr;
Justin Bogner9eb38162014-09-20 15:31:56 +0000299 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
300 if (FileCoverage.empty())
Justin Bogner297149b2014-09-19 19:07:17 +0000301 return nullptr;
Justin Bogner9eb38162014-09-20 15:31:56 +0000302
303 auto Expansions = FileCoverage.getExpansions();
Vedant Kumara9bf3122016-06-25 02:58:30 +0000304 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
305 ViewOpts, std::move(FileCoverage));
Justin Bogner9eb38162014-09-20 15:31:56 +0000306 attachExpansionSubViews(*View, Expansions, Coverage);
Vedant Kumarf6b53452017-08-02 23:35:24 +0000307 if (!ViewOpts.ShowFunctionInstantiations)
308 return View;
Justin Bogner9eb38162014-09-20 15:31:56 +0000309
Vedant Kumara8dfa812017-08-02 23:35:25 +0000310 for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) {
311 // Skip functions which have a single instantiation.
312 if (Group.size() < 2)
313 continue;
Justin Bogner9eb38162014-09-20 15:31:56 +0000314
Vedant Kumara8dfa812017-08-02 23:35:25 +0000315 for (const FunctionRecord *Function : Group.getInstantiations()) {
316 std::unique_ptr<SourceCoverageView> SubView{nullptr};
Vedant Kumar13908072016-09-20 21:27:48 +0000317
Vedant Kumara8dfa812017-08-02 23:35:25 +0000318 StringRef Funcname = DC.demangle(Function->Name);
319
320 if (Function->ExecutionCount > 0) {
321 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
322 auto SubViewExpansions = SubViewCoverage.getExpansions();
323 SubView = SourceCoverageView::create(
324 Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
325 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
326 }
327
328 unsigned FileID = Function->CountedRegions.front().FileID;
329 unsigned Line = 0;
330 for (const auto &CR : Function->CountedRegions)
331 if (CR.FileID == FileID)
332 Line = std::max(CR.LineEnd, Line);
333 View->addInstantiation(Funcname, Line, std::move(SubView));
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000334 }
335 }
Justin Bogner297149b2014-09-19 19:07:17 +0000336 return View;
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000337}
338
Justin Bogner0e93e262015-05-04 04:09:38 +0000339static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
340 sys::fs::file_status Status;
341 if (sys::fs::status(LHS, Status))
342 return false;
343 auto LHSTime = Status.getLastModificationTime();
344 if (sys::fs::status(RHS, Status))
345 return false;
346 auto RHSTime = Status.getLastModificationTime();
347 return LHSTime > RHSTime;
348}
349
Justin Bogner9eb38162014-09-20 15:31:56 +0000350std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Vedant Kumard4998ec2016-10-25 17:40:55 +0000351 for (StringRef ObjectFilename : ObjectFilenames)
352 if (modifiedTimeGT(ObjectFilename, PGOFilename))
353 warning("profile data may be out of date - object is newer",
354 ObjectFilename);
Vedant Kumara3ff2122016-07-18 17:53:12 +0000355 auto CoverageOrErr =
Vedant Kumare72b8812017-08-01 21:23:26 +0000356 CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches);
Vedant Kumarc77570e2016-05-19 03:54:45 +0000357 if (Error E = CoverageOrErr.takeError()) {
Vedant Kumard4998ec2016-10-25 17:40:55 +0000358 error("Failed to load coverage: " + toString(std::move(E)),
359 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "));
Justin Bogner9eb38162014-09-20 15:31:56 +0000360 return nullptr;
361 }
362 auto Coverage = std::move(CoverageOrErr.get());
363 unsigned Mismatched = Coverage->getMismatchedCount();
Vedant Kumar3d39fc22017-09-21 01:11:30 +0000364 if (Mismatched) {
Benjamin Kramerca5092a2017-12-28 16:58:54 +0000365 warning(Twine(Mismatched) + " functions have mismatched data");
Justin Bognerddbcfa02014-09-19 08:13:12 +0000366
Vedant Kumar3d39fc22017-09-21 01:11:30 +0000367 if (ViewOpts.Debug) {
368 for (const auto &HashMismatch : Coverage->getHashMismatches())
369 errs() << "hash-mismatch: "
370 << "No profile record found for '" << HashMismatch.first << "'"
Benjamin Kramerca5092a2017-12-28 16:58:54 +0000371 << " with hash = 0x" << Twine::utohexstr(HashMismatch.second)
372 << '\n';
Vedant Kumar3d39fc22017-09-21 01:11:30 +0000373 }
374 }
375
Sean Eveson8574d592017-08-14 10:20:12 +0000376 remapPathNames(*Coverage);
377
Vedant Kumar3de4fb32016-09-23 20:13:41 +0000378 if (!SourceFiles.empty())
379 removeUnmappedInputs(*Coverage);
380
381 demangleSymbols(*Coverage);
382
383 return Coverage;
384}
385
Sean Eveson8574d592017-08-14 10:20:12 +0000386void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
387 if (!PathRemapping)
388 return;
389
390 // Convert remapping paths to native paths with trailing seperators.
391 auto nativeWithTrailing = [](StringRef Path) -> std::string {
392 if (Path.empty())
393 return "";
394 SmallString<128> NativePath;
395 sys::path::native(Path, NativePath);
396 if (!sys::path::is_separator(NativePath.back()))
397 NativePath += sys::path::get_separator();
398 return NativePath.c_str();
399 };
400 std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
401 std::string RemapTo = nativeWithTrailing(PathRemapping->second);
402
403 // Create a mapping from coverage data file paths to local paths.
404 for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
405 SmallString<128> NativeFilename;
406 sys::path::native(Filename, NativeFilename);
407 if (NativeFilename.startswith(RemapFrom)) {
408 RemappedFilenames[Filename] =
409 RemapTo + NativeFilename.substr(RemapFrom.size()).str();
410 }
411 }
412
413 // Convert input files from local paths to coverage data file paths.
414 StringMap<std::string> InvRemappedFilenames;
415 for (const auto &RemappedFilename : RemappedFilenames)
416 InvRemappedFilenames[RemappedFilename.getValue()] = RemappedFilename.getKey();
417
418 for (std::string &Filename : SourceFiles) {
419 SmallString<128> NativeFilename;
420 sys::path::native(Filename, NativeFilename);
421 auto CovFileName = InvRemappedFilenames.find(NativeFilename);
422 if (CovFileName != InvRemappedFilenames.end())
423 Filename = CovFileName->second;
424 }
425}
426
Vedant Kumar3de4fb32016-09-23 20:13:41 +0000427void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
428 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
Vedant Kumardaacf3c2016-09-23 18:57:35 +0000429
430 auto UncoveredFilesIt = SourceFiles.end();
Sean Eveson8574d592017-08-14 10:20:12 +0000431 // The user may have specified source files which aren't in the coverage
432 // mapping. Filter these files away.
433 UncoveredFilesIt = std::remove_if(
434 SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
435 return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
436 SF);
437 });
Justin Bognerddbcfa02014-09-19 08:13:12 +0000438
Vedant Kumardaacf3c2016-09-23 18:57:35 +0000439 SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000440}
441
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000442void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
443 if (!ViewOpts.hasDemangler())
444 return;
445
446 // Pass function names to the demangler in a temporary file.
447 int InputFD;
448 SmallString<256> InputPath;
449 std::error_code EC =
450 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
451 if (EC) {
452 error(InputPath, EC.message());
453 return;
454 }
Reid Kleckner97ca9642017-09-23 01:03:17 +0000455 ToolOutputFile InputTOF{InputPath, InputFD};
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000456
457 unsigned NumSymbols = 0;
458 for (const auto &Function : Coverage.getCoveredFunctions()) {
459 InputTOF.os() << Function.Name << '\n';
460 ++NumSymbols;
461 }
Vedant Kumar84b51122016-07-15 23:08:22 +0000462 InputTOF.os().close();
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000463
464 // Use another temporary file to store the demangler's output.
465 int OutputFD;
466 SmallString<256> OutputPath;
467 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
468 OutputPath);
469 if (EC) {
470 error(OutputPath, EC.message());
471 return;
472 }
Reid Kleckner97ca9642017-09-23 01:03:17 +0000473 ToolOutputFile OutputTOF{OutputPath, OutputFD};
Vedant Kumar84b51122016-07-15 23:08:22 +0000474 OutputTOF.os().close();
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000475
476 // Invoke the demangler.
Zachary Turner0dcc1152018-06-12 17:43:52 +0000477 std::vector<StringRef> ArgsV;
478 for (StringRef Arg : ViewOpts.DemanglerOpts)
479 ArgsV.push_back(Arg);
Alexander Kornienko87e117d2017-09-13 17:03:37 +0000480 Optional<StringRef> Redirects[] = {InputPath.str(), OutputPath.str(), {""}};
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000481 std::string ErrMsg;
Zachary Turner0dcc1152018-06-12 17:43:52 +0000482 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV,
483 /*env=*/None, Redirects, /*secondsToWait=*/0,
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000484 /*memoryLimit=*/0, &ErrMsg);
485 if (RC) {
486 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
487 return;
488 }
489
490 // Parse the demangler's output.
491 auto BufOrError = MemoryBuffer::getFile(OutputPath);
492 if (!BufOrError) {
493 error(OutputPath, BufOrError.getError().message());
494 return;
495 }
496
497 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
498
499 SmallVector<StringRef, 8> Symbols;
500 StringRef DemanglerData = DemanglerBuf->getBuffer();
501 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
502 /*KeepEmpty=*/false);
503 if (Symbols.size() != NumSymbols) {
504 error("Demangler did not provide expected number of symbols");
505 return;
506 }
507
508 // Cache the demangled names.
509 unsigned I = 0;
510 for (const auto &Function : Coverage.getCoveredFunctions())
Igor Kudrine3a95582017-02-19 14:26:52 +0000511 // On Windows, lines in the demangler's output file end with "\r\n".
512 // Splitting by '\n' keeps '\r's, so cut them now.
513 DC.DemangledNames[Function.Name] = Symbols[I++].rtrim();
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000514}
515
Vedant Kumar4c50ebb2016-10-19 17:55:44 +0000516void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
517 CoverageMapping *Coverage,
518 CoveragePrinter *Printer,
519 bool ShowFilenames) {
520 auto View = createSourceFileView(SourceFile, *Coverage);
521 if (!View) {
522 warning("The file '" + SourceFile + "' isn't covered.");
523 return;
524 }
525
526 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
527 if (Error E = OSOrErr.takeError()) {
528 error("Could not create view file!", toString(std::move(E)));
529 return;
530 }
531 auto OS = std::move(OSOrErr.get());
532
533 View->print(*OS.get(), /*Wholefile=*/true,
Sean Eveson078c2c32017-09-28 10:07:30 +0000534 /*ShowSourceName=*/ShowFilenames,
535 /*ShowTitle=*/ViewOpts.hasOutputDirectory());
Vedant Kumar4c50ebb2016-10-19 17:55:44 +0000536 Printer->closeViewFile(std::move(OS));
537}
538
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000539int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Vedant Kumard4998ec2016-10-25 17:40:55 +0000540 cl::opt<std::string> CovFilename(
541 cl::Positional, cl::desc("Covered executable or object file."));
542
543 cl::list<std::string> CovFilenames(
544 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
545 cl::CommaSeparated);
Justin Bogner6e5def62014-10-30 20:51:24 +0000546
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000547 cl::list<std::string> InputSourceFiles(
548 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
549
Vedant Kumaref76be02016-09-22 21:49:43 +0000550 cl::opt<bool> DebugDumpCollectedPaths(
551 "dump-collected-paths", cl::Optional, cl::Hidden,
552 cl::desc("Show the collected paths to source files"));
553
Justin Bogner9eb38162014-09-20 15:31:56 +0000554 cl::opt<std::string, true> PGOFilename(
555 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000556 cl::desc(
557 "File with the profile data obtained after an instrumented run"));
558
Vedant Kumare72b8812017-08-01 21:23:26 +0000559 cl::list<std::string> Arches(
560 "arch", cl::desc("architectures of the coverage mapping binaries"));
Justin Bognerd39109d2015-03-11 02:30:51 +0000561
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000562 cl::opt<bool> DebugDump("dump", cl::Optional,
563 cl::desc("Show internal debug dump"));
564
Vedant Kumarcd29c6b2016-06-29 00:38:21 +0000565 cl::opt<CoverageViewOptions::OutputFormat> Format(
566 "format", cl::desc("Output format for line-based coverage reports"),
567 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
568 "Text output"),
Vedant Kumar55c8c002016-07-06 21:44:05 +0000569 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
Max Morozfcdc2672018-11-09 16:10:44 +0000570 "HTML output"),
571 clEnumValN(CoverageViewOptions::OutputFormat::Lcov, "lcov",
572 "lcov tracefile output")),
Vedant Kumarcd29c6b2016-06-29 00:38:21 +0000573 cl::init(CoverageViewOptions::OutputFormat::Text));
574
Sean Eveson8574d592017-08-14 10:20:12 +0000575 cl::opt<std::string> PathRemap(
576 "path-equivalence", cl::Optional,
577 cl::desc("<from>,<to> Map coverage data paths to local source file "
578 "paths"));
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000579
580 cl::OptionCategory FilteringCategory("Function filtering options");
581
582 cl::list<std::string> NameFilters(
583 "name", cl::Optional,
584 cl::desc("Show code coverage only for functions with the given name"),
585 cl::ZeroOrMore, cl::cat(FilteringCategory));
586
Sean Eveson10edef12017-08-31 09:11:31 +0000587 cl::list<std::string> NameFilterFiles(
588 "name-whitelist", cl::Optional,
589 cl::desc("Show code coverage only for functions listed in the given "
590 "file"),
591 cl::ZeroOrMore, cl::cat(FilteringCategory));
592
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000593 cl::list<std::string> NameRegexFilters(
594 "name-regex", cl::Optional,
595 cl::desc("Show code coverage only for functions that match the given "
596 "regular expression"),
597 cl::ZeroOrMore, cl::cat(FilteringCategory));
598
Max Moroz06fa6832018-04-09 15:20:35 +0000599 cl::list<std::string> IgnoreFilenameRegexFilters(
600 "ignore-filename-regex", cl::Optional,
601 cl::desc("Skip source code files with file paths that match the given "
602 "regular expression"),
603 cl::ZeroOrMore, cl::cat(FilteringCategory));
604
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000605 cl::opt<double> RegionCoverageLtFilter(
606 "region-coverage-lt", cl::Optional,
607 cl::desc("Show code coverage only for functions with region coverage "
608 "less than the given threshold"),
609 cl::cat(FilteringCategory));
610
611 cl::opt<double> RegionCoverageGtFilter(
612 "region-coverage-gt", cl::Optional,
613 cl::desc("Show code coverage only for functions with region coverage "
614 "greater than the given threshold"),
615 cl::cat(FilteringCategory));
616
617 cl::opt<double> LineCoverageLtFilter(
618 "line-coverage-lt", cl::Optional,
619 cl::desc("Show code coverage only for functions with line coverage less "
620 "than the given threshold"),
621 cl::cat(FilteringCategory));
622
623 cl::opt<double> LineCoverageGtFilter(
624 "line-coverage-gt", cl::Optional,
625 cl::desc("Show code coverage only for functions with line coverage "
626 "greater than the given threshold"),
627 cl::cat(FilteringCategory));
628
Justin Bogner12f0d202015-03-19 04:45:16 +0000629 cl::opt<cl::boolOrDefault> UseColor(
630 "use-color", cl::desc("Emit colored output (default=autodetect)"),
631 cl::init(cl::BOU_UNSET));
Justin Bognercc690d62015-03-19 00:02:23 +0000632
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000633 cl::list<std::string> DemanglerOpts(
634 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
635
Eli Friedmand3822e42017-09-11 22:56:20 +0000636 cl::opt<bool> RegionSummary(
637 "show-region-summary", cl::Optional,
638 cl::desc("Show region statistics in summary table"),
639 cl::init(true));
640
641 cl::opt<bool> InstantiationSummary(
642 "show-instantiation-summary", cl::Optional,
643 cl::desc("Show instantiation statistics in summary table"));
644
Max Morozd4b0ab02017-12-11 23:17:46 +0000645 cl::opt<bool> SummaryOnly(
646 "summary-only", cl::Optional,
647 cl::desc("Export only summary information for each source file"));
648
Max Morozd6352ca2018-01-05 16:15:07 +0000649 cl::opt<unsigned> NumThreads(
650 "num-threads", cl::init(0),
651 cl::desc("Number of merge threads to use (default: autodetect)"));
652 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
653 cl::aliasopt(NumThreads));
654
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000655 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
656 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
657 ViewOpts.Debug = DebugDump;
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000658
Vedant Kumard4998ec2016-10-25 17:40:55 +0000659 if (!CovFilename.empty())
660 ObjectFilenames.emplace_back(CovFilename);
661 for (const std::string &Filename : CovFilenames)
662 ObjectFilenames.emplace_back(Filename);
663 if (ObjectFilenames.empty()) {
Vedant Kumar1fc13ff2016-10-25 19:52:57 +0000664 errs() << "No filenames specified!\n";
Vedant Kumard4998ec2016-10-25 17:40:55 +0000665 ::exit(1);
666 }
667
Vedant Kumarcd29c6b2016-06-29 00:38:21 +0000668 ViewOpts.Format = Format;
669 switch (ViewOpts.Format) {
670 case CoverageViewOptions::OutputFormat::Text:
671 ViewOpts.Colors = UseColor == cl::BOU_UNSET
672 ? sys::Process::StandardOutHasColors()
673 : UseColor == cl::BOU_TRUE;
674 break;
Vedant Kumar55c8c002016-07-06 21:44:05 +0000675 case CoverageViewOptions::OutputFormat::HTML:
676 if (UseColor == cl::BOU_FALSE)
Vedant Kumar1fc13ff2016-10-25 19:52:57 +0000677 errs() << "Color output cannot be disabled when generating html.\n";
Vedant Kumar55c8c002016-07-06 21:44:05 +0000678 ViewOpts.Colors = true;
679 break;
Max Morozfcdc2672018-11-09 16:10:44 +0000680 case CoverageViewOptions::OutputFormat::Lcov:
681 if (UseColor == cl::BOU_TRUE)
682 errs() << "Color output cannot be enabled when generating lcov.\n";
683 ViewOpts.Colors = false;
684 break;
Vedant Kumarcd29c6b2016-06-29 00:38:21 +0000685 }
Justin Bognercc690d62015-03-19 00:02:23 +0000686
Sean Eveson8574d592017-08-14 10:20:12 +0000687 // If path-equivalence was given and is a comma seperated pair then set
688 // PathRemapping.
689 auto EquivPair = StringRef(PathRemap).split(',');
690 if (!(EquivPair.first.empty() && EquivPair.second.empty()))
691 PathRemapping = EquivPair;
692
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000693 // If a demangler is supplied, check if it exists and register it.
Jordan Rupprechtf6ea1292018-12-20 00:57:06 +0000694 if (!DemanglerOpts.empty()) {
Vedant Kumar13ca1cc2016-07-15 22:44:57 +0000695 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
696 if (!DemanglerPathOrErr) {
697 error("Could not find the demangler!",
698 DemanglerPathOrErr.getError().message());
699 return 1;
700 }
701 DemanglerOpts[0] = *DemanglerPathOrErr;
702 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
703 }
704
Sean Eveson10edef12017-08-31 09:11:31 +0000705 // Read in -name-whitelist files.
706 if (!NameFilterFiles.empty()) {
707 std::string SpecialCaseListErr;
708 NameWhitelist =
709 SpecialCaseList::create(NameFilterFiles, SpecialCaseListErr);
710 if (!NameWhitelist)
711 error(SpecialCaseListErr);
712 }
713
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000714 // Create the function filters
Sean Eveson10edef12017-08-31 09:11:31 +0000715 if (!NameFilters.empty() || NameWhitelist || !NameRegexFilters.empty()) {
Vedant Kumar0f0fd422017-08-04 00:36:24 +0000716 auto NameFilterer = llvm::make_unique<CoverageFilters>();
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000717 for (const auto &Name : NameFilters)
718 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
Sean Eveson10edef12017-08-31 09:11:31 +0000719 if (NameWhitelist)
720 NameFilterer->push_back(
721 llvm::make_unique<NameWhitelistCoverageFilter>(*NameWhitelist));
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000722 for (const auto &Regex : NameRegexFilters)
723 NameFilterer->push_back(
724 llvm::make_unique<NameRegexCoverageFilter>(Regex));
Vedant Kumar0f0fd422017-08-04 00:36:24 +0000725 Filters.push_back(std::move(NameFilterer));
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000726 }
Max Moroz06fa6832018-04-09 15:20:35 +0000727
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000728 if (RegionCoverageLtFilter.getNumOccurrences() ||
729 RegionCoverageGtFilter.getNumOccurrences() ||
730 LineCoverageLtFilter.getNumOccurrences() ||
731 LineCoverageGtFilter.getNumOccurrences()) {
Vedant Kumar0f0fd422017-08-04 00:36:24 +0000732 auto StatFilterer = llvm::make_unique<CoverageFilters>();
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000733 if (RegionCoverageLtFilter.getNumOccurrences())
734 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
735 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
736 if (RegionCoverageGtFilter.getNumOccurrences())
737 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
738 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
739 if (LineCoverageLtFilter.getNumOccurrences())
740 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
741 LineCoverageFilter::LessThan, LineCoverageLtFilter));
742 if (LineCoverageGtFilter.getNumOccurrences())
743 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
744 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
Vedant Kumar0f0fd422017-08-04 00:36:24 +0000745 Filters.push_back(std::move(StatFilterer));
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000746 }
747
Max Moroz06fa6832018-04-09 15:20:35 +0000748 // Create the ignore filename filters.
749 for (const auto &RE : IgnoreFilenameRegexFilters)
750 IgnoreFilenameFilters.push_back(
751 llvm::make_unique<NameRegexCoverageFilter>(RE));
752
Vedant Kumare72b8812017-08-01 21:23:26 +0000753 if (!Arches.empty()) {
754 for (const std::string &Arch : Arches) {
755 if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
756 error("Unknown architecture: " + Arch);
757 return 1;
758 }
759 CoverageArches.emplace_back(Arch);
760 }
761 if (CoverageArches.size() != ObjectFilenames.size()) {
762 error("Number of architectures doesn't match the number of objects");
763 return 1;
764 }
Justin Bognerd39109d2015-03-11 02:30:51 +0000765 }
766
Max Moroz06fa6832018-04-09 15:20:35 +0000767 // IgnoreFilenameFilters are applied even when InputSourceFiles specified.
Vedant Kumaref76be02016-09-22 21:49:43 +0000768 for (const std::string &File : InputSourceFiles)
769 collectPaths(File);
770
771 if (DebugDumpCollectedPaths) {
Vedant Kumarfd066352016-09-23 18:57:32 +0000772 for (const std::string &SF : SourceFiles)
Vedant Kumaref76be02016-09-22 21:49:43 +0000773 outs() << SF << '\n';
774 ::exit(0);
Justin Bognerddbcfa02014-09-19 08:13:12 +0000775 }
Vedant Kumaref76be02016-09-22 21:49:43 +0000776
Eli Friedmand3822e42017-09-11 22:56:20 +0000777 ViewOpts.ShowRegionSummary = RegionSummary;
778 ViewOpts.ShowInstantiationSummary = InstantiationSummary;
Max Morozd4b0ab02017-12-11 23:17:46 +0000779 ViewOpts.ExportSummaryOnly = SummaryOnly;
Max Morozd6352ca2018-01-05 16:15:07 +0000780 ViewOpts.NumThreads = NumThreads;
Eli Friedmand3822e42017-09-11 22:56:20 +0000781
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000782 return 0;
783 };
784
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000785 switch (Cmd) {
786 case Show:
Max Morozfc04e852018-01-04 19:33:29 +0000787 return doShow(argc, argv, commandLineParser);
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000788 case Report:
Max Morozfc04e852018-01-04 19:33:29 +0000789 return doReport(argc, argv, commandLineParser);
Vedant Kumar53397d12016-07-26 22:50:58 +0000790 case Export:
Max Morozfc04e852018-01-04 19:33:29 +0000791 return doExport(argc, argv, commandLineParser);
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000792 }
793 return 0;
794}
795
Max Morozfc04e852018-01-04 19:33:29 +0000796int CodeCoverageTool::doShow(int argc, const char **argv,
797 CommandLineParserType commandLineParser) {
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000798
799 cl::OptionCategory ViewCategory("Viewing options");
800
801 cl::opt<bool> ShowLineExecutionCounts(
802 "show-line-counts", cl::Optional,
803 cl::desc("Show the execution counts for each line"), cl::init(true),
804 cl::cat(ViewCategory));
805
806 cl::opt<bool> ShowRegions(
807 "show-regions", cl::Optional,
808 cl::desc("Show the execution counts for each region"),
809 cl::cat(ViewCategory));
810
811 cl::opt<bool> ShowBestLineRegionsCounts(
812 "show-line-counts-or-regions", cl::Optional,
813 cl::desc("Show the execution counts for each line, or the execution "
814 "counts for each region on lines that have multiple regions"),
815 cl::cat(ViewCategory));
816
817 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
818 cl::desc("Show expanded source regions"),
819 cl::cat(ViewCategory));
820
821 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
822 cl::desc("Show function instantiations"),
Vedant Kumarf6b53452017-08-02 23:35:24 +0000823 cl::init(true), cl::cat(ViewCategory));
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000824
Vedant Kumar40a78f82016-06-28 02:09:39 +0000825 cl::opt<std::string> ShowOutputDirectory(
826 "output-dir", cl::init(""),
827 cl::desc("Directory in which coverage information is written out"));
828 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
829 cl::aliasopt(ShowOutputDirectory));
830
Ying Yi65787e22016-08-04 10:39:43 +0000831 cl::opt<uint32_t> TabSize(
Vedant Kumardf48bd92016-08-04 18:00:42 +0000832 "tab-size", cl::init(2),
833 cl::desc(
834 "Set tab expansion size for html coverage reports (default = 2)"));
Ying Yi65787e22016-08-04 10:39:43 +0000835
Ying Yi1461e992016-08-24 14:27:23 +0000836 cl::opt<std::string> ProjectTitle(
837 "project-title", cl::Optional,
838 cl::desc("Set project title for the coverage report"));
839
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000840 auto Err = commandLineParser(argc, argv);
841 if (Err)
842 return Err;
843
Max Morozfcdc2672018-11-09 16:10:44 +0000844 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::Lcov) {
845 error("Lcov format should be used with 'llvm-cov export'.");
846 return 1;
847 }
848
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000849 ViewOpts.ShowLineNumbers = true;
850 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
851 !ShowRegions || ShowBestLineRegionsCounts;
852 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000853 ViewOpts.ShowExpandedRegions = ShowExpansions;
854 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar40a78f82016-06-28 02:09:39 +0000855 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
Ying Yi65787e22016-08-04 10:39:43 +0000856 ViewOpts.TabSize = TabSize;
Ying Yi1461e992016-08-24 14:27:23 +0000857 ViewOpts.ProjectTitle = ProjectTitle;
Vedant Kumar40a78f82016-06-28 02:09:39 +0000858
Vedant Kumar184c2242016-06-28 16:12:20 +0000859 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar40a78f82016-06-28 02:09:39 +0000860 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
861 error("Could not create output directory!", E.message());
862 return 1;
863 }
864 }
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000865
Ying Yi1461e992016-08-24 14:27:23 +0000866 sys::fs::file_status Status;
867 if (sys::fs::status(PGOFilename, Status)) {
868 error("profdata file error: can not get the file status. \n");
869 return 1;
870 }
871
872 auto ModifiedTime = Status.getLastModificationTime();
Pavel Labath2864c2a2016-10-24 10:59:17 +0000873 std::string ModifiedTimeStr = to_string(ModifiedTime);
Benjamin Kramerbf60ce02016-11-30 10:01:11 +0000874 size_t found = ModifiedTimeStr.rfind(':');
Ying Yi1461e992016-08-24 14:27:23 +0000875 ViewOpts.CreatedTimeStr = (found != std::string::npos)
876 ? "Created: " + ModifiedTimeStr.substr(0, found)
877 : "Created: " + ModifiedTimeStr;
878
Justin Bogner9eb38162014-09-20 15:31:56 +0000879 auto Coverage = load();
880 if (!Coverage)
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000881 return 1;
882
Vedant Kumar028d73c2016-06-28 16:12:24 +0000883 auto Printer = CoveragePrinter::create(ViewOpts);
884
Sean Eveson950974f2017-09-27 16:20:07 +0000885 if (SourceFiles.empty())
886 // Get the source files from the function coverage mapping.
Max Moroz06fa6832018-04-09 15:20:35 +0000887 for (StringRef Filename : Coverage->getUniqueSourceFiles()) {
888 if (!IgnoreFilenameFilters.matchesFilename(Filename))
889 SourceFiles.push_back(Filename);
890 }
Sean Eveson950974f2017-09-27 16:20:07 +0000891
892 // Create an index out of the source files.
893 if (ViewOpts.hasOutputDirectory()) {
Sean Eveson078c2c32017-09-28 10:07:30 +0000894 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage, Filters)) {
Sean Eveson950974f2017-09-27 16:20:07 +0000895 error("Could not create index file!", toString(std::move(E)));
896 return 1;
897 }
898 }
899
Sean Eveson078c2c32017-09-28 10:07:30 +0000900 if (!Filters.empty()) {
901 // Build the map of filenames to functions.
902 std::map<llvm::StringRef, std::vector<const FunctionRecord *>>
903 FilenameFunctionMap;
904 for (const auto &SourceFile : SourceFiles)
905 for (const auto &Function : Coverage->getCoveredFunctions(SourceFile))
906 if (Filters.matches(*Coverage.get(), Function))
907 FilenameFunctionMap[SourceFile].push_back(&Function);
908
909 // Only print filter matching functions for each file.
910 for (const auto &FileFunc : FilenameFunctionMap) {
911 StringRef File = FileFunc.first;
912 const auto &Functions = FileFunc.second;
913
914 auto OSOrErr = Printer->createViewFile(File, /*InToplevel=*/false);
915 if (Error E = OSOrErr.takeError()) {
916 error("Could not create view file!", toString(std::move(E)));
917 return 1;
918 }
919 auto OS = std::move(OSOrErr.get());
920
Sean Eveson69863c02017-10-04 08:54:37 +0000921 bool ShowTitle = ViewOpts.hasOutputDirectory();
Sean Eveson078c2c32017-09-28 10:07:30 +0000922 for (const auto *Function : Functions) {
923 auto FunctionView = createFunctionView(*Function, *Coverage);
924 if (!FunctionView) {
925 warning("Could not read coverage for '" + Function->Name + "'.");
926 continue;
927 }
928 FunctionView->print(*OS.get(), /*WholeFile=*/false,
929 /*ShowSourceName=*/true, ShowTitle);
930 ShowTitle = false;
931 }
932
933 Printer->closeViewFile(std::move(OS));
934 }
935 return 0;
936 }
937
938 // Show files
939 bool ShowFilenames =
940 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
941 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
942
Max Morozd6352ca2018-01-05 16:15:07 +0000943 auto NumThreads = ViewOpts.NumThreads;
944
Vedant Kumar574c5162017-07-11 01:23:29 +0000945 // If NumThreads is not specified, auto-detect a good default.
946 if (NumThreads == 0)
947 NumThreads =
948 std::max(1U, std::min(llvm::heavyweight_hardware_concurrency(),
949 unsigned(SourceFiles.size())));
950
951 if (!ViewOpts.hasOutputDirectory() || NumThreads == 1) {
Vedant Kumar4c50ebb2016-10-19 17:55:44 +0000952 for (const std::string &SourceFile : SourceFiles)
953 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
954 ShowFilenames);
955 } else {
956 // In -output-dir mode, it's safe to use multiple threads to print files.
Vedant Kumar574c5162017-07-11 01:23:29 +0000957 ThreadPool Pool(NumThreads);
Vedant Kumar4c50ebb2016-10-19 17:55:44 +0000958 for (const std::string &SourceFile : SourceFiles)
959 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
960 Coverage.get(), Printer.get(), ShowFilenames);
961 Pool.wait();
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000962 }
963
964 return 0;
965}
966
Max Morozfc04e852018-01-04 19:33:29 +0000967int CodeCoverageTool::doReport(int argc, const char **argv,
968 CommandLineParserType commandLineParser) {
Vedant Kumar2006b412017-02-05 20:11:08 +0000969 cl::opt<bool> ShowFunctionSummaries(
970 "show-functions", cl::Optional, cl::init(false),
971 cl::desc("Show coverage summaries for each function"));
972
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000973 auto Err = commandLineParser(argc, argv);
974 if (Err)
975 return Err;
976
Vedant Kumar09f10e72017-02-28 16:57:28 +0000977 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
Vedant Kumar55c8c002016-07-06 21:44:05 +0000978 error("HTML output for summary reports is not yet supported.");
Vedant Kumar09f10e72017-02-28 16:57:28 +0000979 return 1;
Max Morozfcdc2672018-11-09 16:10:44 +0000980 } else if (ViewOpts.Format == CoverageViewOptions::OutputFormat::Lcov) {
981 error("Lcov format should be used with 'llvm-cov export'.");
982 return 1;
Vedant Kumar09f10e72017-02-28 16:57:28 +0000983 }
Vedant Kumar55c8c002016-07-06 21:44:05 +0000984
Justin Bogner9eb38162014-09-20 15:31:56 +0000985 auto Coverage = load();
986 if (!Coverage)
Alex Lorenz6c7a6a12014-08-22 22:56:03 +0000987 return 1;
988
Vedant Kumarff7a0df2016-09-06 22:45:57 +0000989 CoverageReport Report(ViewOpts, *Coverage.get());
Vedant Kumar35ccd0b2017-09-25 23:10:03 +0000990 if (!ShowFunctionSummaries) {
Max Morozb5d60b82017-10-13 14:44:51 +0000991 if (SourceFiles.empty())
Max Moroz06fa6832018-04-09 15:20:35 +0000992 Report.renderFileReports(llvm::outs(), IgnoreFilenameFilters);
Max Morozb5d60b82017-10-13 14:44:51 +0000993 else
994 Report.renderFileReports(llvm::outs(), SourceFiles);
Vedant Kumar35ccd0b2017-09-25 23:10:03 +0000995 } else {
996 if (SourceFiles.empty()) {
997 error("Source files must be specified when -show-functions=true is "
998 "specified");
999 return 1;
1000 }
1001
Vedant Kumarb766e932017-02-05 20:11:03 +00001002 Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
Vedant Kumar35ccd0b2017-09-25 23:10:03 +00001003 }
Alex Lorenz6c7a6a12014-08-22 22:56:03 +00001004 return 0;
1005}
1006
Max Morozfc04e852018-01-04 19:33:29 +00001007int CodeCoverageTool::doExport(int argc, const char **argv,
1008 CommandLineParserType commandLineParser) {
Vedant Kumar53397d12016-07-26 22:50:58 +00001009
1010 auto Err = commandLineParser(argc, argv);
1011 if (Err)
1012 return Err;
1013
Max Morozfcdc2672018-11-09 16:10:44 +00001014 if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text &&
1015 ViewOpts.Format != CoverageViewOptions::OutputFormat::Lcov) {
1016 error("Coverage data can only be exported as textual JSON or an "
1017 "lcov tracefile.");
Vedant Kumar09f10e72017-02-28 16:57:28 +00001018 return 1;
1019 }
1020
Vedant Kumar53397d12016-07-26 22:50:58 +00001021 auto Coverage = load();
1022 if (!Coverage) {
1023 error("Could not load coverage information");
1024 return 1;
1025 }
1026
Max Morozfcdc2672018-11-09 16:10:44 +00001027 std::unique_ptr<CoverageExporter> Exporter;
1028
1029 switch (ViewOpts.Format) {
1030 case CoverageViewOptions::OutputFormat::Text:
1031 Exporter = llvm::make_unique<CoverageExporterJson>(*Coverage.get(),
1032 ViewOpts, outs());
1033 break;
1034 case CoverageViewOptions::OutputFormat::HTML:
1035 // Unreachable because we should have gracefully terminated with an error
1036 // above.
1037 llvm_unreachable("Export in HTML is not supported!");
1038 case CoverageViewOptions::OutputFormat::Lcov:
1039 Exporter = llvm::make_unique<CoverageExporterLcov>(*Coverage.get(),
1040 ViewOpts, outs());
1041 break;
Max Morozfcdc2672018-11-09 16:10:44 +00001042 }
Max Morozfc04e852018-01-04 19:33:29 +00001043
1044 if (SourceFiles.empty())
Max Morozfcdc2672018-11-09 16:10:44 +00001045 Exporter->renderRoot(IgnoreFilenameFilters);
Max Morozfc04e852018-01-04 19:33:29 +00001046 else
Max Morozfcdc2672018-11-09 16:10:44 +00001047 Exporter->renderRoot(SourceFiles);
Vedant Kumar53397d12016-07-26 22:50:58 +00001048
1049 return 0;
1050}
1051
Justin Bogner76ebe3d2014-10-30 20:57:49 +00001052int showMain(int argc, const char *argv[]) {
Alex Lorenz6c7a6a12014-08-22 22:56:03 +00001053 CodeCoverageTool Tool;
1054 return Tool.run(CodeCoverageTool::Show, argc, argv);
1055}
1056
Justin Bogner76ebe3d2014-10-30 20:57:49 +00001057int reportMain(int argc, const char *argv[]) {
Alex Lorenz6c7a6a12014-08-22 22:56:03 +00001058 CodeCoverageTool Tool;
1059 return Tool.run(CodeCoverageTool::Report, argc, argv);
1060}
Vedant Kumar53397d12016-07-26 22:50:58 +00001061
1062int exportMain(int argc, const char *argv[]) {
1063 CodeCoverageTool Tool;
1064 return Tool.run(CodeCoverageTool::Export, argc, argv);
1065}