blob: 59cb708a42c1ff29c82f957367ca8a1de1ed7bf5 [file] [log] [blame]
Alex Lorenze82d89c2014-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
Alex Lorenze82d89c2014-08-22 22:56:03 +000016#include "CoverageFilters.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000017#include "CoverageReport.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000018#include "CoverageViewOptions.h"
Easwaran Ramandc707122016-04-29 18:53:05 +000019#include "RenderingSupport.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000020#include "SourceCoverageView.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000021#include "llvm/ADT/SmallString.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000022#include "llvm/ADT/StringRef.h"
Justin Bogner43795352015-03-11 02:30:51 +000023#include "llvm/ADT/Triple.h"
Easwaran Ramandc707122016-04-29 18:53:05 +000024#include "llvm/ProfileData/Coverage/CoverageMapping.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000025#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileSystem.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000028#include "llvm/Support/Format.h"
29#include "llvm/Support/Path.h"
Justin Bognercfb53e42015-03-19 00:02:23 +000030#include "llvm/Support/Process.h"
Vedant Kumar86b2ac632016-07-13 21:38:36 +000031#include "llvm/Support/ThreadPool.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000032#include <functional>
Justin Bognere53be062014-09-09 05:32:18 +000033#include <system_error>
Alex Lorenze82d89c2014-08-22 22:56:03 +000034
35using namespace llvm;
36using namespace coverage;
37
38namespace {
Alex Lorenze82d89c2014-08-22 22:56:03 +000039/// \brief The implementation of the coverage tool.
40class CodeCoverageTool {
41public:
42 enum Command {
43 /// \brief The show command.
44 Show,
45 /// \brief The report command.
46 Report
47 };
48
49 /// \brief Print the error message to the error output stream.
50 void error(const Twine &Message, StringRef Whence = "");
51
Vedant Kumar86b2ac632016-07-13 21:38:36 +000052 /// \brief Record (but do not print) an error message in a thread-safe way.
53 void deferError(const Twine &Message, StringRef Whence = "");
54
55 /// \brief Record (but do not print) a warning message in a thread-safe way.
56 void deferWarning(const Twine &Message, StringRef Whence = "");
57
58 /// \brief Print (and then clear) all deferred error and warning messages.
59 void consumeDeferredMessages();
60
Vedant Kumarcef440f2016-06-28 16:12:18 +000061 /// \brief Append a reference to a private copy of \p Path into SourceFiles.
62 void addCollectedPath(const std::string &Path);
63
Alex Lorenze82d89c2014-08-22 22:56:03 +000064 /// \brief Return a memory buffer for the given source file.
65 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
66
Justin Bogner953e2402014-09-20 15:31:56 +000067 /// \brief Create source views for the expansions of the view.
68 void attachExpansionSubViews(SourceCoverageView &View,
69 ArrayRef<ExpansionRecord> Expansions,
Vedant Kumarf681e2e2016-07-15 01:19:33 +000070 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000071
Justin Bogner953e2402014-09-20 15:31:56 +000072 /// \brief Create the source view of a particular function.
Justin Bogner5a6edad2014-09-19 19:07:17 +000073 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000074 createFunctionView(const FunctionRecord &Function,
75 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000076
77 /// \brief Create the main source view of a particular source file.
Justin Bogner5a6edad2014-09-19 19:07:17 +000078 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000079 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000080
Vedant Kumarf681e2e2016-07-15 01:19:33 +000081 /// \brief Load the coverage mapping data. Return nullptr if an error occured.
Justin Bogner953e2402014-09-20 15:31:56 +000082 std::unique_ptr<CoverageMapping> load();
Alex Lorenze82d89c2014-08-22 22:56:03 +000083
84 int run(Command Cmd, int argc, const char **argv);
85
Benjamin Kramerc321e532016-06-08 19:09:22 +000086 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
Alex Lorenze82d89c2014-08-22 22:56:03 +000087
88 int show(int argc, const char **argv,
89 CommandLineParserType commandLineParser);
90
91 int report(int argc, const char **argv,
92 CommandLineParserType commandLineParser);
93
Justin Bognerf6c50552014-10-30 20:51:24 +000094 std::string ObjectFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +000095 CoverageViewOptions ViewOpts;
Justin Bogner953e2402014-09-20 15:31:56 +000096 std::string PGOFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +000097 CoverageFiltersMatchAll Filters;
Vedant Kumarcef440f2016-06-28 16:12:18 +000098 std::vector<StringRef> SourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +000099 bool CompareFilenamesOnly;
Justin Bogner116c1662014-09-19 08:13:12 +0000100 StringMap<std::string> RemappedFilenames;
Frederic Rissebc162a2015-06-22 21:33:24 +0000101 std::string CoverageArch;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000102
103private:
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000104 /// File paths (absolute, or otherwise) to input source files.
Vedant Kumarcef440f2016-06-28 16:12:18 +0000105 std::vector<std::string> CollectedPaths;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000106
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000107 /// Errors and warnings which have not been printed.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000108 std::mutex DeferredMessagesLock;
109 std::vector<std::string> DeferredMessages;
110
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000111 /// A container for input source file buffers.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000112 std::mutex LoadedSourceFilesLock;
113 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
114 LoadedSourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000115};
116}
117
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000118static std::string getErrorString(const Twine &Message, StringRef Whence,
119 bool Warning) {
120 std::string Str = (Warning ? "warning" : "error");
121 Str += ": ";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000122 if (!Whence.empty())
Vedant Kumarb95dc462016-07-15 01:53:39 +0000123 Str += Whence.str() + ": ";
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000124 Str += Message.str() + "\n";
125 return Str;
126}
127
128void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
129 errs() << getErrorString(Message, Whence, false);
130}
131
132void CodeCoverageTool::deferError(const Twine &Message, StringRef Whence) {
133 std::unique_lock<std::mutex> Guard{DeferredMessagesLock};
134 DeferredMessages.emplace_back(getErrorString(Message, Whence, false));
135}
136
137void CodeCoverageTool::deferWarning(const Twine &Message, StringRef Whence) {
138 std::unique_lock<std::mutex> Guard{DeferredMessagesLock};
139 DeferredMessages.emplace_back(getErrorString(Message, Whence, true));
140}
141
142void CodeCoverageTool::consumeDeferredMessages() {
143 std::unique_lock<std::mutex> Guard{DeferredMessagesLock};
144 for (const std::string &Message : DeferredMessages)
145 ViewOpts.colored_ostream(errs(), raw_ostream::RED) << Message;
146 DeferredMessages.clear();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000147}
148
Vedant Kumarcef440f2016-06-28 16:12:18 +0000149void CodeCoverageTool::addCollectedPath(const std::string &Path) {
150 CollectedPaths.push_back(Path);
151 SourceFiles.emplace_back(CollectedPaths.back());
152}
153
Alex Lorenze82d89c2014-08-22 22:56:03 +0000154ErrorOr<const MemoryBuffer &>
155CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bogner116c1662014-09-19 08:13:12 +0000156 // If we've remapped filenames, look up the real location for this file.
Vedant Kumar615b85d2016-07-15 01:19:36 +0000157 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Justin Bogner116c1662014-09-19 08:13:12 +0000158 if (!RemappedFilenames.empty()) {
159 auto Loc = RemappedFilenames.find(SourceFile);
160 if (Loc != RemappedFilenames.end())
161 SourceFile = Loc->second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000162 }
Justin Bogner116c1662014-09-19 08:13:12 +0000163 for (const auto &Files : LoadedSourceFiles)
164 if (sys::fs::equivalent(SourceFile, Files.first))
165 return *Files.second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000166 auto Buffer = MemoryBuffer::getFile(SourceFile);
167 if (auto EC = Buffer.getError()) {
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000168 deferError(EC.message(), SourceFile);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000169 return EC;
170 }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000171 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000172 return *LoadedSourceFiles.back().second;
173}
174
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000175void CodeCoverageTool::attachExpansionSubViews(
176 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
177 const CoverageMapping &Coverage) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000178 if (!ViewOpts.ShowExpandedRegions)
179 return;
Justin Bogner953e2402014-09-20 15:31:56 +0000180 for (const auto &Expansion : Expansions) {
181 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
182 if (ExpansionCoverage.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000183 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000184 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
185 if (!SourceBuffer)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000186 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000187
188 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000189 auto SubView =
190 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
191 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000192 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
193 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000194 }
195}
196
Justin Bogner5a6edad2014-09-19 19:07:17 +0000197std::unique_ptr<SourceCoverageView>
Justin Bogner953e2402014-09-20 15:31:56 +0000198CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000199 const CoverageMapping &Coverage) {
Justin Bogner953e2402014-09-20 15:31:56 +0000200 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
201 if (FunctionCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000202 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000203 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner5a6edad2014-09-19 19:07:17 +0000204 if (!SourceBuffer)
205 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000206
207 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000208 auto View = SourceCoverageView::create(Function.Name, SourceBuffer.get(),
209 ViewOpts, std::move(FunctionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000210 attachExpansionSubViews(*View, Expansions, Coverage);
211
212 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000213}
214
Justin Bogner953e2402014-09-20 15:31:56 +0000215std::unique_ptr<SourceCoverageView>
216CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000217 const CoverageMapping &Coverage) {
Justin Bogner5a6edad2014-09-19 19:07:17 +0000218 auto SourceBuffer = getSourceFile(SourceFile);
219 if (!SourceBuffer)
220 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000221 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
222 if (FileCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000223 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000224
225 auto Expansions = FileCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000226 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
227 ViewOpts, std::move(FileCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000228 attachExpansionSubViews(*View, Expansions, Coverage);
229
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000230 for (const auto *Function : Coverage.getInstantiations(SourceFile)) {
Justin Bogner953e2402014-09-20 15:31:56 +0000231 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
232 auto SubViewExpansions = SubViewCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000233 auto SubView =
234 SourceCoverageView::create(Function->Name, SourceBuffer.get(), ViewOpts,
235 std::move(SubViewCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000236 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
237
238 if (SubView) {
Justin Bogner5e1400a2014-09-17 05:33:20 +0000239 unsigned FileID = Function->CountedRegions.front().FileID;
240 unsigned Line = 0;
241 for (const auto &CR : Function->CountedRegions)
242 if (CR.FileID == FileID)
243 Line = std::max(CR.LineEnd, Line);
Justin Bogner953e2402014-09-20 15:31:56 +0000244 View->addInstantiation(Function->Name, Line, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000245 }
246 }
Justin Bogner5a6edad2014-09-19 19:07:17 +0000247 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000248}
249
Justin Bogner65337d12015-05-04 04:09:38 +0000250static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
251 sys::fs::file_status Status;
252 if (sys::fs::status(LHS, Status))
253 return false;
254 auto LHSTime = Status.getLastModificationTime();
255 if (sys::fs::status(RHS, Status))
256 return false;
257 auto RHSTime = Status.getLastModificationTime();
258 return LHSTime > RHSTime;
259}
260
Justin Bogner953e2402014-09-20 15:31:56 +0000261std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Justin Bogner65337d12015-05-04 04:09:38 +0000262 if (modifiedTimeGT(ObjectFilename, PGOFilename))
263 errs() << "warning: profile data may be out of date - object is newer\n";
Justin Bogner43795352015-03-11 02:30:51 +0000264 auto CoverageOrErr = CoverageMapping::load(ObjectFilename, PGOFilename,
265 CoverageArch);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000266 if (Error E = CoverageOrErr.takeError()) {
Justin Bogner953e2402014-09-20 15:31:56 +0000267 colored_ostream(errs(), raw_ostream::RED)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000268 << "error: Failed to load coverage: " << toString(std::move(E)) << "\n";
Justin Bogner953e2402014-09-20 15:31:56 +0000269 return nullptr;
270 }
271 auto Coverage = std::move(CoverageOrErr.get());
272 unsigned Mismatched = Coverage->getMismatchedCount();
273 if (Mismatched) {
274 colored_ostream(errs(), raw_ostream::RED)
275 << "warning: " << Mismatched << " functions have mismatched data. ";
276 errs() << "\n";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000277 }
Justin Bogner116c1662014-09-19 08:13:12 +0000278
279 if (CompareFilenamesOnly) {
Justin Bogner953e2402014-09-20 15:31:56 +0000280 auto CoveredFiles = Coverage.get()->getUniqueSourceFiles();
Justin Bogner116c1662014-09-19 08:13:12 +0000281 for (auto &SF : SourceFiles) {
282 StringRef SFBase = sys::path::filename(SF);
283 for (const auto &CF : CoveredFiles)
284 if (SFBase == sys::path::filename(CF)) {
285 RemappedFilenames[CF] = SF;
286 SF = CF;
287 break;
288 }
289 }
290 }
291
Justin Bogner953e2402014-09-20 15:31:56 +0000292 return Coverage;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000293}
294
295int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Justin Bognerf6c50552014-10-30 20:51:24 +0000296 cl::opt<std::string, true> ObjectFilename(
297 cl::Positional, cl::Required, cl::location(this->ObjectFilename),
298 cl::desc("Covered executable or object file."));
299
Alex Lorenze82d89c2014-08-22 22:56:03 +0000300 cl::list<std::string> InputSourceFiles(
301 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
302
Justin Bogner953e2402014-09-20 15:31:56 +0000303 cl::opt<std::string, true> PGOFilename(
304 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000305 cl::desc(
306 "File with the profile data obtained after an instrumented run"));
307
Justin Bogner43795352015-03-11 02:30:51 +0000308 cl::opt<std::string> Arch(
309 "arch", cl::desc("architecture of the coverage mapping binary"));
310
Alex Lorenze82d89c2014-08-22 22:56:03 +0000311 cl::opt<bool> DebugDump("dump", cl::Optional,
312 cl::desc("Show internal debug dump"));
313
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000314 cl::opt<CoverageViewOptions::OutputFormat> Format(
315 "format", cl::desc("Output format for line-based coverage reports"),
316 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
317 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000318 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
319 "HTML output"),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000320 clEnumValEnd),
321 cl::init(CoverageViewOptions::OutputFormat::Text));
322
Alex Lorenze82d89c2014-08-22 22:56:03 +0000323 cl::opt<bool> FilenameEquivalence(
324 "filename-equivalence", cl::Optional,
Justin Bogner116c1662014-09-19 08:13:12 +0000325 cl::desc("Treat source files as equivalent to paths in the coverage data "
326 "when the file names match, even if the full paths do not"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000327
328 cl::OptionCategory FilteringCategory("Function filtering options");
329
330 cl::list<std::string> NameFilters(
331 "name", cl::Optional,
332 cl::desc("Show code coverage only for functions with the given name"),
333 cl::ZeroOrMore, cl::cat(FilteringCategory));
334
335 cl::list<std::string> NameRegexFilters(
336 "name-regex", cl::Optional,
337 cl::desc("Show code coverage only for functions that match the given "
338 "regular expression"),
339 cl::ZeroOrMore, cl::cat(FilteringCategory));
340
341 cl::opt<double> RegionCoverageLtFilter(
342 "region-coverage-lt", cl::Optional,
343 cl::desc("Show code coverage only for functions with region coverage "
344 "less than the given threshold"),
345 cl::cat(FilteringCategory));
346
347 cl::opt<double> RegionCoverageGtFilter(
348 "region-coverage-gt", cl::Optional,
349 cl::desc("Show code coverage only for functions with region coverage "
350 "greater than the given threshold"),
351 cl::cat(FilteringCategory));
352
353 cl::opt<double> LineCoverageLtFilter(
354 "line-coverage-lt", cl::Optional,
355 cl::desc("Show code coverage only for functions with line coverage less "
356 "than the given threshold"),
357 cl::cat(FilteringCategory));
358
359 cl::opt<double> LineCoverageGtFilter(
360 "line-coverage-gt", cl::Optional,
361 cl::desc("Show code coverage only for functions with line coverage "
362 "greater than the given threshold"),
363 cl::cat(FilteringCategory));
364
Justin Bogner9deb1d42015-03-19 04:45:16 +0000365 cl::opt<cl::boolOrDefault> UseColor(
366 "use-color", cl::desc("Emit colored output (default=autodetect)"),
367 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000368
Alex Lorenze82d89c2014-08-22 22:56:03 +0000369 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
370 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
371 ViewOpts.Debug = DebugDump;
372 CompareFilenamesOnly = FilenameEquivalence;
373
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000374 ViewOpts.Format = Format;
375 switch (ViewOpts.Format) {
376 case CoverageViewOptions::OutputFormat::Text:
377 ViewOpts.Colors = UseColor == cl::BOU_UNSET
378 ? sys::Process::StandardOutHasColors()
379 : UseColor == cl::BOU_TRUE;
380 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000381 case CoverageViewOptions::OutputFormat::HTML:
382 if (UseColor == cl::BOU_FALSE)
383 error("Color output cannot be disabled when generating html.");
384 ViewOpts.Colors = true;
385 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000386 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000387
Alex Lorenze82d89c2014-08-22 22:56:03 +0000388 // Create the function filters
389 if (!NameFilters.empty() || !NameRegexFilters.empty()) {
390 auto NameFilterer = new CoverageFilters;
391 for (const auto &Name : NameFilters)
392 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
393 for (const auto &Regex : NameRegexFilters)
394 NameFilterer->push_back(
395 llvm::make_unique<NameRegexCoverageFilter>(Regex));
396 Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
397 }
398 if (RegionCoverageLtFilter.getNumOccurrences() ||
399 RegionCoverageGtFilter.getNumOccurrences() ||
400 LineCoverageLtFilter.getNumOccurrences() ||
401 LineCoverageGtFilter.getNumOccurrences()) {
402 auto StatFilterer = new CoverageFilters;
403 if (RegionCoverageLtFilter.getNumOccurrences())
404 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
405 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
406 if (RegionCoverageGtFilter.getNumOccurrences())
407 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
408 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
409 if (LineCoverageLtFilter.getNumOccurrences())
410 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
411 LineCoverageFilter::LessThan, LineCoverageLtFilter));
412 if (LineCoverageGtFilter.getNumOccurrences())
413 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
414 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
415 Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
416 }
417
Frederic Rissebc162a2015-06-22 21:33:24 +0000418 if (!Arch.empty() &&
419 Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
420 errs() << "error: Unknown architecture: " << Arch << "\n";
421 return 1;
Justin Bogner43795352015-03-11 02:30:51 +0000422 }
Frederic Rissebc162a2015-06-22 21:33:24 +0000423 CoverageArch = Arch;
Justin Bogner43795352015-03-11 02:30:51 +0000424
Justin Bogner116c1662014-09-19 08:13:12 +0000425 for (const auto &File : InputSourceFiles) {
426 SmallString<128> Path(File);
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000427 if (!CompareFilenamesOnly)
428 if (std::error_code EC = sys::fs::make_absolute(Path)) {
429 errs() << "error: " << File << ": " << EC.message();
430 return 1;
431 }
Vedant Kumarcef440f2016-06-28 16:12:18 +0000432 addCollectedPath(Path.str());
Justin Bogner116c1662014-09-19 08:13:12 +0000433 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000434 return 0;
435 };
436
Alex Lorenze82d89c2014-08-22 22:56:03 +0000437 switch (Cmd) {
438 case Show:
439 return show(argc, argv, commandLineParser);
440 case Report:
441 return report(argc, argv, commandLineParser);
442 }
443 return 0;
444}
445
446int CodeCoverageTool::show(int argc, const char **argv,
447 CommandLineParserType commandLineParser) {
448
449 cl::OptionCategory ViewCategory("Viewing options");
450
451 cl::opt<bool> ShowLineExecutionCounts(
452 "show-line-counts", cl::Optional,
453 cl::desc("Show the execution counts for each line"), cl::init(true),
454 cl::cat(ViewCategory));
455
456 cl::opt<bool> ShowRegions(
457 "show-regions", cl::Optional,
458 cl::desc("Show the execution counts for each region"),
459 cl::cat(ViewCategory));
460
461 cl::opt<bool> ShowBestLineRegionsCounts(
462 "show-line-counts-or-regions", cl::Optional,
463 cl::desc("Show the execution counts for each line, or the execution "
464 "counts for each region on lines that have multiple regions"),
465 cl::cat(ViewCategory));
466
467 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
468 cl::desc("Show expanded source regions"),
469 cl::cat(ViewCategory));
470
471 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
472 cl::desc("Show function instantiations"),
473 cl::cat(ViewCategory));
474
Vedant Kumar7937ef32016-06-28 02:09:39 +0000475 cl::opt<std::string> ShowOutputDirectory(
476 "output-dir", cl::init(""),
477 cl::desc("Directory in which coverage information is written out"));
478 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
479 cl::aliasopt(ShowOutputDirectory));
480
Alex Lorenze82d89c2014-08-22 22:56:03 +0000481 auto Err = commandLineParser(argc, argv);
482 if (Err)
483 return Err;
484
Alex Lorenze82d89c2014-08-22 22:56:03 +0000485 ViewOpts.ShowLineNumbers = true;
486 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
487 !ShowRegions || ShowBestLineRegionsCounts;
488 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
489 ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
490 ViewOpts.ShowExpandedRegions = ShowExpansions;
491 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000492 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
493
Vedant Kumar64d8a022016-06-28 16:12:20 +0000494 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000495 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
496 error("Could not create output directory!", E.message());
497 return 1;
498 }
499 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000500
Justin Bogner953e2402014-09-20 15:31:56 +0000501 auto Coverage = load();
502 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000503 return 1;
504
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000505 auto Printer = CoveragePrinter::create(ViewOpts);
506
Alex Lorenze82d89c2014-08-22 22:56:03 +0000507 if (!Filters.empty()) {
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000508 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
509 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000510 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000511 return 1;
512 }
513 auto OS = std::move(OSOrErr.get());
514
515 // Show functions.
Justin Bogner953e2402014-09-20 15:31:56 +0000516 for (const auto &Function : Coverage->getCoveredFunctions()) {
517 if (!Filters.matches(Function))
Alex Lorenze82d89c2014-08-22 22:56:03 +0000518 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000519
520 auto mainView = createFunctionView(Function, *Coverage);
Justin Bogner5a6edad2014-09-19 19:07:17 +0000521 if (!mainView) {
Vedant Kumar2c96e882016-06-24 02:33:01 +0000522 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
523 << "warning: Could not read coverage for '" << Function.Name << "'."
524 << "\n";
Justin Bogner5a6edad2014-09-19 19:07:17 +0000525 continue;
526 }
Vedant Kumar7937ef32016-06-28 02:09:39 +0000527
Vedant Kumar7937ef32016-06-28 02:09:39 +0000528 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000529 }
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000530
531 Printer->closeViewFile(std::move(OS));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000532 return 0;
533 }
534
535 // Show files
536 bool ShowFilenames = SourceFiles.size() != 1;
537
Justin Bogner116c1662014-09-19 08:13:12 +0000538 if (SourceFiles.empty())
Vedant Kumar64d8a022016-06-28 16:12:20 +0000539 // Get the source files from the function coverage mapping.
Justin Bogner953e2402014-09-20 15:31:56 +0000540 for (StringRef Filename : Coverage->getUniqueSourceFiles())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000541 SourceFiles.push_back(Filename);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000542
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000543 // Create an index out of the source files.
544 if (ViewOpts.hasOutputDirectory()) {
545 if (Error E = Printer->createIndexFile(SourceFiles)) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000546 error("Could not create index file!", toString(std::move(E)));
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000547 return 1;
548 }
549 }
550
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000551 // In -output-dir mode, it's safe to use multiple threads to print files.
552 unsigned ThreadCount = 1;
553 if (ViewOpts.hasOutputDirectory())
554 ThreadCount = std::thread::hardware_concurrency();
555 ThreadPool Pool(ThreadCount);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000556
Vedant Kumar84c452d2016-07-15 01:19:35 +0000557 for (StringRef SourceFile : SourceFiles) {
558 Pool.async([this, SourceFile, &Coverage, &Printer, ShowFilenames] {
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000559 auto View = createSourceFileView(SourceFile, *Coverage);
560 if (!View) {
561 deferWarning("The file '" + SourceFile.str() + "' isn't covered.");
562 return;
563 }
564
565 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
566 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000567 deferError("Could not create view file!", toString(std::move(E)));
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000568 return;
569 }
570 auto OS = std::move(OSOrErr.get());
571
572 View->print(*OS.get(), /*Wholefile=*/true,
573 /*ShowSourceName=*/ShowFilenames);
574 Printer->closeViewFile(std::move(OS));
575 });
Alex Lorenze82d89c2014-08-22 22:56:03 +0000576 }
577
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000578 Pool.wait();
579
580 consumeDeferredMessages();
581
Alex Lorenze82d89c2014-08-22 22:56:03 +0000582 return 0;
583}
584
585int CodeCoverageTool::report(int argc, const char **argv,
586 CommandLineParserType commandLineParser) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000587 auto Err = commandLineParser(argc, argv);
588 if (Err)
589 return Err;
590
Vedant Kumar4c010922016-07-06 21:44:05 +0000591 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
592 error("HTML output for summary reports is not yet supported.");
593
Justin Bogner953e2402014-09-20 15:31:56 +0000594 auto Coverage = load();
595 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000596 return 1;
597
Justin Bognerf91bc6c2015-02-14 02:01:24 +0000598 CoverageReport Report(ViewOpts, std::move(Coverage));
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000599 if (SourceFiles.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000600 Report.renderFileReports(llvm::outs());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000601 else
602 Report.renderFunctionReports(SourceFiles, llvm::outs());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000603 return 0;
604}
605
Justin Bognerd249a3b2014-10-30 20:57:49 +0000606int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000607 CodeCoverageTool Tool;
608 return Tool.run(CodeCoverageTool::Show, argc, argv);
609}
610
Justin Bognerd249a3b2014-10-30 20:57:49 +0000611int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000612 CodeCoverageTool Tool;
613 return Tool.run(CodeCoverageTool::Report, argc, argv);
614}