blob: 11b38530a1d31aabf2cc1e037e790e45cf66efcb [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"
Vedant Kumar424f51b2016-07-15 22:44:57 +000029#include "llvm/Support/MemoryBuffer.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000030#include "llvm/Support/Path.h"
Justin Bognercfb53e42015-03-19 00:02:23 +000031#include "llvm/Support/Process.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000032#include "llvm/Support/Program.h"
Vedant Kumar86b2ac632016-07-13 21:38:36 +000033#include "llvm/Support/ThreadPool.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000034#include "llvm/Support/ToolOutputFile.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000035#include <functional>
Justin Bognere53be062014-09-09 05:32:18 +000036#include <system_error>
Alex Lorenze82d89c2014-08-22 22:56:03 +000037
38using namespace llvm;
39using namespace coverage;
40
41namespace {
Alex Lorenze82d89c2014-08-22 22:56:03 +000042/// \brief The implementation of the coverage tool.
43class CodeCoverageTool {
44public:
45 enum Command {
46 /// \brief The show command.
47 Show,
48 /// \brief The report command.
49 Report
50 };
51
52 /// \brief Print the error message to the error output stream.
53 void error(const Twine &Message, StringRef Whence = "");
54
Vedant Kumarb3020632016-07-18 17:53:12 +000055 /// \brief Print the warning message to the error output stream.
56 void warning(const Twine &Message, StringRef Whence = "");
Vedant Kumar86b2ac632016-07-13 21:38:36 +000057
Vedant Kumarcef440f2016-06-28 16:12:18 +000058 /// \brief Append a reference to a private copy of \p Path into SourceFiles.
59 void addCollectedPath(const std::string &Path);
60
Alex Lorenze82d89c2014-08-22 22:56:03 +000061 /// \brief Return a memory buffer for the given source file.
62 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
63
Justin Bogner953e2402014-09-20 15:31:56 +000064 /// \brief Create source views for the expansions of the view.
65 void attachExpansionSubViews(SourceCoverageView &View,
66 ArrayRef<ExpansionRecord> Expansions,
Vedant Kumarf681e2e2016-07-15 01:19:33 +000067 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000068
Justin Bogner953e2402014-09-20 15:31:56 +000069 /// \brief Create the source view of a particular function.
Justin Bogner5a6edad2014-09-19 19:07:17 +000070 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000071 createFunctionView(const FunctionRecord &Function,
72 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000073
74 /// \brief Create the main source view of a particular source file.
Justin Bogner5a6edad2014-09-19 19:07:17 +000075 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000076 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000077
Vedant Kumarf681e2e2016-07-15 01:19:33 +000078 /// \brief Load the coverage mapping data. Return nullptr if an error occured.
Justin Bogner953e2402014-09-20 15:31:56 +000079 std::unique_ptr<CoverageMapping> load();
Alex Lorenze82d89c2014-08-22 22:56:03 +000080
Vedant Kumar424f51b2016-07-15 22:44:57 +000081 /// \brief If a demangler is available, demangle all symbol names.
82 void demangleSymbols(const CoverageMapping &Coverage);
83
84 /// \brief Demangle \p Sym if possible. Otherwise, just return \p Sym.
85 StringRef getSymbolForHumans(StringRef Sym) const;
86
Alex Lorenze82d89c2014-08-22 22:56:03 +000087 int run(Command Cmd, int argc, const char **argv);
88
Benjamin Kramerc321e532016-06-08 19:09:22 +000089 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
Alex Lorenze82d89c2014-08-22 22:56:03 +000090
91 int show(int argc, const char **argv,
92 CommandLineParserType commandLineParser);
93
94 int report(int argc, const char **argv,
95 CommandLineParserType commandLineParser);
96
Justin Bognerf6c50552014-10-30 20:51:24 +000097 std::string ObjectFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +000098 CoverageViewOptions ViewOpts;
Justin Bogner953e2402014-09-20 15:31:56 +000099 std::string PGOFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000100 CoverageFiltersMatchAll Filters;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000101 std::vector<StringRef> SourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000102 bool CompareFilenamesOnly;
Justin Bogner116c1662014-09-19 08:13:12 +0000103 StringMap<std::string> RemappedFilenames;
Frederic Rissebc162a2015-06-22 21:33:24 +0000104 std::string CoverageArch;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000105
106private:
Vedant Kumar424f51b2016-07-15 22:44:57 +0000107 /// A cache for demangled symbol names.
108 StringMap<std::string> DemangledNames;
109
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000110 /// File paths (absolute, or otherwise) to input source files.
Vedant Kumarcef440f2016-06-28 16:12:18 +0000111 std::vector<std::string> CollectedPaths;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000112
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000113 /// Errors and warnings which have not been printed.
Vedant Kumarb3020632016-07-18 17:53:12 +0000114 std::mutex ErrsLock;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000115
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000116 /// A container for input source file buffers.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000117 std::mutex LoadedSourceFilesLock;
118 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
119 LoadedSourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000120};
121}
122
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000123static std::string getErrorString(const Twine &Message, StringRef Whence,
124 bool Warning) {
125 std::string Str = (Warning ? "warning" : "error");
126 Str += ": ";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000127 if (!Whence.empty())
Vedant Kumarb95dc462016-07-15 01:53:39 +0000128 Str += Whence.str() + ": ";
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000129 Str += Message.str() + "\n";
130 return Str;
131}
132
133void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000134 std::unique_lock<std::mutex> Guard{ErrsLock};
135 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
136 << getErrorString(Message, Whence, false);
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000137}
138
Vedant Kumarb3020632016-07-18 17:53:12 +0000139void CodeCoverageTool::warning(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, true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000143}
144
Vedant Kumarcef440f2016-06-28 16:12:18 +0000145void CodeCoverageTool::addCollectedPath(const std::string &Path) {
146 CollectedPaths.push_back(Path);
147 SourceFiles.emplace_back(CollectedPaths.back());
148}
149
Alex Lorenze82d89c2014-08-22 22:56:03 +0000150ErrorOr<const MemoryBuffer &>
151CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bogner116c1662014-09-19 08:13:12 +0000152 // If we've remapped filenames, look up the real location for this file.
Vedant Kumar615b85d2016-07-15 01:19:36 +0000153 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Justin Bogner116c1662014-09-19 08:13:12 +0000154 if (!RemappedFilenames.empty()) {
155 auto Loc = RemappedFilenames.find(SourceFile);
156 if (Loc != RemappedFilenames.end())
157 SourceFile = Loc->second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000158 }
Justin Bogner116c1662014-09-19 08:13:12 +0000159 for (const auto &Files : LoadedSourceFiles)
160 if (sys::fs::equivalent(SourceFile, Files.first))
161 return *Files.second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000162 auto Buffer = MemoryBuffer::getFile(SourceFile);
163 if (auto EC = Buffer.getError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000164 error(EC.message(), SourceFile);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000165 return EC;
166 }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000167 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000168 return *LoadedSourceFiles.back().second;
169}
170
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000171void CodeCoverageTool::attachExpansionSubViews(
172 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
173 const CoverageMapping &Coverage) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000174 if (!ViewOpts.ShowExpandedRegions)
175 return;
Justin Bogner953e2402014-09-20 15:31:56 +0000176 for (const auto &Expansion : Expansions) {
177 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
178 if (ExpansionCoverage.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000179 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000180 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
181 if (!SourceBuffer)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000182 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000183
184 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000185 auto SubView =
186 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
187 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000188 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
189 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000190 }
191}
192
Justin Bogner5a6edad2014-09-19 19:07:17 +0000193std::unique_ptr<SourceCoverageView>
Justin Bogner953e2402014-09-20 15:31:56 +0000194CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000195 const CoverageMapping &Coverage) {
Justin Bogner953e2402014-09-20 15:31:56 +0000196 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
197 if (FunctionCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000198 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000199 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner5a6edad2014-09-19 19:07:17 +0000200 if (!SourceBuffer)
201 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000202
203 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000204 auto View = SourceCoverageView::create(getSymbolForHumans(Function.Name),
205 SourceBuffer.get(), ViewOpts,
206 std::move(FunctionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000207 attachExpansionSubViews(*View, Expansions, Coverage);
208
209 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000210}
211
Justin Bogner953e2402014-09-20 15:31:56 +0000212std::unique_ptr<SourceCoverageView>
213CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000214 const CoverageMapping &Coverage) {
Justin Bogner5a6edad2014-09-19 19:07:17 +0000215 auto SourceBuffer = getSourceFile(SourceFile);
216 if (!SourceBuffer)
217 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000218 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
219 if (FileCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000220 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000221
222 auto Expansions = FileCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000223 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
224 ViewOpts, std::move(FileCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000225 attachExpansionSubViews(*View, Expansions, Coverage);
226
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000227 for (const auto *Function : Coverage.getInstantiations(SourceFile)) {
Justin Bogner953e2402014-09-20 15:31:56 +0000228 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
229 auto SubViewExpansions = SubViewCoverage.getExpansions();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000230 auto SubView = SourceCoverageView::create(
231 getSymbolForHumans(Function->Name), SourceBuffer.get(), ViewOpts,
232 std::move(SubViewCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000233 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
234
235 if (SubView) {
Justin Bogner5e1400a2014-09-17 05:33:20 +0000236 unsigned FileID = Function->CountedRegions.front().FileID;
237 unsigned Line = 0;
238 for (const auto &CR : Function->CountedRegions)
239 if (CR.FileID == FileID)
240 Line = std::max(CR.LineEnd, Line);
Justin Bogner953e2402014-09-20 15:31:56 +0000241 View->addInstantiation(Function->Name, Line, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000242 }
243 }
Justin Bogner5a6edad2014-09-19 19:07:17 +0000244 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000245}
246
Justin Bogner65337d12015-05-04 04:09:38 +0000247static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
248 sys::fs::file_status Status;
249 if (sys::fs::status(LHS, Status))
250 return false;
251 auto LHSTime = Status.getLastModificationTime();
252 if (sys::fs::status(RHS, Status))
253 return false;
254 auto RHSTime = Status.getLastModificationTime();
255 return LHSTime > RHSTime;
256}
257
Justin Bogner953e2402014-09-20 15:31:56 +0000258std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Justin Bogner65337d12015-05-04 04:09:38 +0000259 if (modifiedTimeGT(ObjectFilename, PGOFilename))
Vedant Kumarb3020632016-07-18 17:53:12 +0000260 warning("profile data may be out of date - object is newer",
261 ObjectFilename);
262 auto CoverageOrErr =
263 CoverageMapping::load(ObjectFilename, PGOFilename, CoverageArch);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000264 if (Error E = CoverageOrErr.takeError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000265 error("Failed to load coverage: " + toString(std::move(E)), ObjectFilename);
Justin Bogner953e2402014-09-20 15:31:56 +0000266 return nullptr;
267 }
268 auto Coverage = std::move(CoverageOrErr.get());
269 unsigned Mismatched = Coverage->getMismatchedCount();
Vedant Kumarb3020632016-07-18 17:53:12 +0000270 if (Mismatched)
271 warning(utostr(Mismatched) + " functions have mismatched data");
Justin Bogner116c1662014-09-19 08:13:12 +0000272
273 if (CompareFilenamesOnly) {
Justin Bogner953e2402014-09-20 15:31:56 +0000274 auto CoveredFiles = Coverage.get()->getUniqueSourceFiles();
Justin Bogner116c1662014-09-19 08:13:12 +0000275 for (auto &SF : SourceFiles) {
276 StringRef SFBase = sys::path::filename(SF);
277 for (const auto &CF : CoveredFiles)
278 if (SFBase == sys::path::filename(CF)) {
279 RemappedFilenames[CF] = SF;
280 SF = CF;
281 break;
282 }
283 }
284 }
285
Vedant Kumar424f51b2016-07-15 22:44:57 +0000286 demangleSymbols(*Coverage);
287
Justin Bogner953e2402014-09-20 15:31:56 +0000288 return Coverage;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000289}
290
Vedant Kumar424f51b2016-07-15 22:44:57 +0000291void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
292 if (!ViewOpts.hasDemangler())
293 return;
294
295 // Pass function names to the demangler in a temporary file.
296 int InputFD;
297 SmallString<256> InputPath;
298 std::error_code EC =
299 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
300 if (EC) {
301 error(InputPath, EC.message());
302 return;
303 }
304 tool_output_file InputTOF{InputPath, InputFD};
305
306 unsigned NumSymbols = 0;
307 for (const auto &Function : Coverage.getCoveredFunctions()) {
308 InputTOF.os() << Function.Name << '\n';
309 ++NumSymbols;
310 }
Vedant Kumar554357b2016-07-15 23:08:22 +0000311 InputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000312
313 // Use another temporary file to store the demangler's output.
314 int OutputFD;
315 SmallString<256> OutputPath;
316 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
317 OutputPath);
318 if (EC) {
319 error(OutputPath, EC.message());
320 return;
321 }
322 tool_output_file OutputTOF{OutputPath, OutputFD};
Vedant Kumar554357b2016-07-15 23:08:22 +0000323 OutputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000324
325 // Invoke the demangler.
326 std::vector<const char *> ArgsV;
327 for (const std::string &Arg : ViewOpts.DemanglerOpts)
328 ArgsV.push_back(Arg.c_str());
329 ArgsV.push_back(nullptr);
Vedant Kumar38202c02016-07-15 23:15:35 +0000330 StringRef InputPathRef = InputPath.str();
331 StringRef OutputPathRef = OutputPath.str();
332 StringRef StderrRef;
Vedant Kumar424f51b2016-07-15 22:44:57 +0000333 const StringRef *Redirects[] = {&InputPathRef, &OutputPathRef, &StderrRef};
334 std::string ErrMsg;
335 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
336 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
337 /*memoryLimit=*/0, &ErrMsg);
338 if (RC) {
339 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
340 return;
341 }
342
343 // Parse the demangler's output.
344 auto BufOrError = MemoryBuffer::getFile(OutputPath);
345 if (!BufOrError) {
346 error(OutputPath, BufOrError.getError().message());
347 return;
348 }
349
350 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
351
352 SmallVector<StringRef, 8> Symbols;
353 StringRef DemanglerData = DemanglerBuf->getBuffer();
354 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
355 /*KeepEmpty=*/false);
356 if (Symbols.size() != NumSymbols) {
357 error("Demangler did not provide expected number of symbols");
358 return;
359 }
360
361 // Cache the demangled names.
362 unsigned I = 0;
363 for (const auto &Function : Coverage.getCoveredFunctions())
364 DemangledNames[Function.Name] = Symbols[I++];
365}
366
367StringRef CodeCoverageTool::getSymbolForHumans(StringRef Sym) const {
368 const auto DemangledName = DemangledNames.find(Sym);
369 if (DemangledName == DemangledNames.end())
370 return Sym;
371 return DemangledName->getValue();
372}
373
Alex Lorenze82d89c2014-08-22 22:56:03 +0000374int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Justin Bognerf6c50552014-10-30 20:51:24 +0000375 cl::opt<std::string, true> ObjectFilename(
376 cl::Positional, cl::Required, cl::location(this->ObjectFilename),
377 cl::desc("Covered executable or object file."));
378
Alex Lorenze82d89c2014-08-22 22:56:03 +0000379 cl::list<std::string> InputSourceFiles(
380 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
381
Justin Bogner953e2402014-09-20 15:31:56 +0000382 cl::opt<std::string, true> PGOFilename(
383 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000384 cl::desc(
385 "File with the profile data obtained after an instrumented run"));
386
Justin Bogner43795352015-03-11 02:30:51 +0000387 cl::opt<std::string> Arch(
388 "arch", cl::desc("architecture of the coverage mapping binary"));
389
Alex Lorenze82d89c2014-08-22 22:56:03 +0000390 cl::opt<bool> DebugDump("dump", cl::Optional,
391 cl::desc("Show internal debug dump"));
392
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000393 cl::opt<CoverageViewOptions::OutputFormat> Format(
394 "format", cl::desc("Output format for line-based coverage reports"),
395 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
396 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000397 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
398 "HTML output"),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000399 clEnumValEnd),
400 cl::init(CoverageViewOptions::OutputFormat::Text));
401
Alex Lorenze82d89c2014-08-22 22:56:03 +0000402 cl::opt<bool> FilenameEquivalence(
403 "filename-equivalence", cl::Optional,
Justin Bogner116c1662014-09-19 08:13:12 +0000404 cl::desc("Treat source files as equivalent to paths in the coverage data "
405 "when the file names match, even if the full paths do not"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000406
407 cl::OptionCategory FilteringCategory("Function filtering options");
408
409 cl::list<std::string> NameFilters(
410 "name", cl::Optional,
411 cl::desc("Show code coverage only for functions with the given name"),
412 cl::ZeroOrMore, cl::cat(FilteringCategory));
413
414 cl::list<std::string> NameRegexFilters(
415 "name-regex", cl::Optional,
416 cl::desc("Show code coverage only for functions that match the given "
417 "regular expression"),
418 cl::ZeroOrMore, cl::cat(FilteringCategory));
419
420 cl::opt<double> RegionCoverageLtFilter(
421 "region-coverage-lt", cl::Optional,
422 cl::desc("Show code coverage only for functions with region coverage "
423 "less than the given threshold"),
424 cl::cat(FilteringCategory));
425
426 cl::opt<double> RegionCoverageGtFilter(
427 "region-coverage-gt", cl::Optional,
428 cl::desc("Show code coverage only for functions with region coverage "
429 "greater than the given threshold"),
430 cl::cat(FilteringCategory));
431
432 cl::opt<double> LineCoverageLtFilter(
433 "line-coverage-lt", cl::Optional,
434 cl::desc("Show code coverage only for functions with line coverage less "
435 "than the given threshold"),
436 cl::cat(FilteringCategory));
437
438 cl::opt<double> LineCoverageGtFilter(
439 "line-coverage-gt", cl::Optional,
440 cl::desc("Show code coverage only for functions with line coverage "
441 "greater than the given threshold"),
442 cl::cat(FilteringCategory));
443
Justin Bogner9deb1d42015-03-19 04:45:16 +0000444 cl::opt<cl::boolOrDefault> UseColor(
445 "use-color", cl::desc("Emit colored output (default=autodetect)"),
446 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000447
Vedant Kumar424f51b2016-07-15 22:44:57 +0000448 cl::list<std::string> DemanglerOpts(
449 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
450
Alex Lorenze82d89c2014-08-22 22:56:03 +0000451 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
452 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
453 ViewOpts.Debug = DebugDump;
454 CompareFilenamesOnly = FilenameEquivalence;
455
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000456 ViewOpts.Format = Format;
457 switch (ViewOpts.Format) {
458 case CoverageViewOptions::OutputFormat::Text:
459 ViewOpts.Colors = UseColor == cl::BOU_UNSET
460 ? sys::Process::StandardOutHasColors()
461 : UseColor == cl::BOU_TRUE;
462 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000463 case CoverageViewOptions::OutputFormat::HTML:
464 if (UseColor == cl::BOU_FALSE)
465 error("Color output cannot be disabled when generating html.");
466 ViewOpts.Colors = true;
467 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000468 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000469
Vedant Kumar424f51b2016-07-15 22:44:57 +0000470 // If a demangler is supplied, check if it exists and register it.
471 if (DemanglerOpts.size()) {
472 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
473 if (!DemanglerPathOrErr) {
474 error("Could not find the demangler!",
475 DemanglerPathOrErr.getError().message());
476 return 1;
477 }
478 DemanglerOpts[0] = *DemanglerPathOrErr;
479 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
480 }
481
Alex Lorenze82d89c2014-08-22 22:56:03 +0000482 // Create the function filters
483 if (!NameFilters.empty() || !NameRegexFilters.empty()) {
484 auto NameFilterer = new CoverageFilters;
485 for (const auto &Name : NameFilters)
486 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
487 for (const auto &Regex : NameRegexFilters)
488 NameFilterer->push_back(
489 llvm::make_unique<NameRegexCoverageFilter>(Regex));
490 Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
491 }
492 if (RegionCoverageLtFilter.getNumOccurrences() ||
493 RegionCoverageGtFilter.getNumOccurrences() ||
494 LineCoverageLtFilter.getNumOccurrences() ||
495 LineCoverageGtFilter.getNumOccurrences()) {
496 auto StatFilterer = new CoverageFilters;
497 if (RegionCoverageLtFilter.getNumOccurrences())
498 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
499 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
500 if (RegionCoverageGtFilter.getNumOccurrences())
501 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
502 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
503 if (LineCoverageLtFilter.getNumOccurrences())
504 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
505 LineCoverageFilter::LessThan, LineCoverageLtFilter));
506 if (LineCoverageGtFilter.getNumOccurrences())
507 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
508 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
509 Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
510 }
511
Frederic Rissebc162a2015-06-22 21:33:24 +0000512 if (!Arch.empty() &&
513 Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000514 error("Unknown architecture: " + Arch);
Frederic Rissebc162a2015-06-22 21:33:24 +0000515 return 1;
Justin Bogner43795352015-03-11 02:30:51 +0000516 }
Frederic Rissebc162a2015-06-22 21:33:24 +0000517 CoverageArch = Arch;
Justin Bogner43795352015-03-11 02:30:51 +0000518
Justin Bogner116c1662014-09-19 08:13:12 +0000519 for (const auto &File : InputSourceFiles) {
520 SmallString<128> Path(File);
Vedant Kumarb3020632016-07-18 17:53:12 +0000521 if (!CompareFilenamesOnly) {
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000522 if (std::error_code EC = sys::fs::make_absolute(Path)) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000523 error(EC.message(), File);
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000524 return 1;
525 }
Vedant Kumarb3020632016-07-18 17:53:12 +0000526 }
Vedant Kumarcef440f2016-06-28 16:12:18 +0000527 addCollectedPath(Path.str());
Justin Bogner116c1662014-09-19 08:13:12 +0000528 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000529 return 0;
530 };
531
Alex Lorenze82d89c2014-08-22 22:56:03 +0000532 switch (Cmd) {
533 case Show:
534 return show(argc, argv, commandLineParser);
535 case Report:
536 return report(argc, argv, commandLineParser);
537 }
538 return 0;
539}
540
541int CodeCoverageTool::show(int argc, const char **argv,
542 CommandLineParserType commandLineParser) {
543
544 cl::OptionCategory ViewCategory("Viewing options");
545
546 cl::opt<bool> ShowLineExecutionCounts(
547 "show-line-counts", cl::Optional,
548 cl::desc("Show the execution counts for each line"), cl::init(true),
549 cl::cat(ViewCategory));
550
551 cl::opt<bool> ShowRegions(
552 "show-regions", cl::Optional,
553 cl::desc("Show the execution counts for each region"),
554 cl::cat(ViewCategory));
555
556 cl::opt<bool> ShowBestLineRegionsCounts(
557 "show-line-counts-or-regions", cl::Optional,
558 cl::desc("Show the execution counts for each line, or the execution "
559 "counts for each region on lines that have multiple regions"),
560 cl::cat(ViewCategory));
561
562 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
563 cl::desc("Show expanded source regions"),
564 cl::cat(ViewCategory));
565
566 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
567 cl::desc("Show function instantiations"),
568 cl::cat(ViewCategory));
569
Vedant Kumar7937ef32016-06-28 02:09:39 +0000570 cl::opt<std::string> ShowOutputDirectory(
571 "output-dir", cl::init(""),
572 cl::desc("Directory in which coverage information is written out"));
573 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
574 cl::aliasopt(ShowOutputDirectory));
575
Alex Lorenze82d89c2014-08-22 22:56:03 +0000576 auto Err = commandLineParser(argc, argv);
577 if (Err)
578 return Err;
579
Alex Lorenze82d89c2014-08-22 22:56:03 +0000580 ViewOpts.ShowLineNumbers = true;
581 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
582 !ShowRegions || ShowBestLineRegionsCounts;
583 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
584 ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
585 ViewOpts.ShowExpandedRegions = ShowExpansions;
586 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000587 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
588
Vedant Kumar64d8a022016-06-28 16:12:20 +0000589 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000590 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
591 error("Could not create output directory!", E.message());
592 return 1;
593 }
594 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000595
Justin Bogner953e2402014-09-20 15:31:56 +0000596 auto Coverage = load();
597 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000598 return 1;
599
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000600 auto Printer = CoveragePrinter::create(ViewOpts);
601
Alex Lorenze82d89c2014-08-22 22:56:03 +0000602 if (!Filters.empty()) {
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000603 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
604 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000605 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000606 return 1;
607 }
608 auto OS = std::move(OSOrErr.get());
609
610 // Show functions.
Justin Bogner953e2402014-09-20 15:31:56 +0000611 for (const auto &Function : Coverage->getCoveredFunctions()) {
612 if (!Filters.matches(Function))
Alex Lorenze82d89c2014-08-22 22:56:03 +0000613 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000614
615 auto mainView = createFunctionView(Function, *Coverage);
Justin Bogner5a6edad2014-09-19 19:07:17 +0000616 if (!mainView) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000617 warning("Could not read coverage for '" + Function.Name + "'.");
Justin Bogner5a6edad2014-09-19 19:07:17 +0000618 continue;
619 }
Vedant Kumar7937ef32016-06-28 02:09:39 +0000620
Vedant Kumar7937ef32016-06-28 02:09:39 +0000621 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000622 }
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000623
624 Printer->closeViewFile(std::move(OS));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000625 return 0;
626 }
627
628 // Show files
629 bool ShowFilenames = SourceFiles.size() != 1;
630
Justin Bogner116c1662014-09-19 08:13:12 +0000631 if (SourceFiles.empty())
Vedant Kumar64d8a022016-06-28 16:12:20 +0000632 // Get the source files from the function coverage mapping.
Justin Bogner953e2402014-09-20 15:31:56 +0000633 for (StringRef Filename : Coverage->getUniqueSourceFiles())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000634 SourceFiles.push_back(Filename);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000635
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000636 // Create an index out of the source files.
637 if (ViewOpts.hasOutputDirectory()) {
638 if (Error E = Printer->createIndexFile(SourceFiles)) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000639 error("Could not create index file!", toString(std::move(E)));
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000640 return 1;
641 }
642 }
643
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000644 // In -output-dir mode, it's safe to use multiple threads to print files.
645 unsigned ThreadCount = 1;
646 if (ViewOpts.hasOutputDirectory())
647 ThreadCount = std::thread::hardware_concurrency();
648 ThreadPool Pool(ThreadCount);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000649
Vedant Kumar84c452d2016-07-15 01:19:35 +0000650 for (StringRef SourceFile : SourceFiles) {
651 Pool.async([this, SourceFile, &Coverage, &Printer, ShowFilenames] {
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000652 auto View = createSourceFileView(SourceFile, *Coverage);
653 if (!View) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000654 warning("The file '" + SourceFile.str() + "' isn't covered.");
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000655 return;
656 }
657
658 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
659 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000660 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000661 return;
662 }
663 auto OS = std::move(OSOrErr.get());
664
665 View->print(*OS.get(), /*Wholefile=*/true,
666 /*ShowSourceName=*/ShowFilenames);
667 Printer->closeViewFile(std::move(OS));
668 });
Alex Lorenze82d89c2014-08-22 22:56:03 +0000669 }
670
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000671 Pool.wait();
672
Alex Lorenze82d89c2014-08-22 22:56:03 +0000673 return 0;
674}
675
676int CodeCoverageTool::report(int argc, const char **argv,
677 CommandLineParserType commandLineParser) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000678 auto Err = commandLineParser(argc, argv);
679 if (Err)
680 return Err;
681
Vedant Kumar4c010922016-07-06 21:44:05 +0000682 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
683 error("HTML output for summary reports is not yet supported.");
684
Justin Bogner953e2402014-09-20 15:31:56 +0000685 auto Coverage = load();
686 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000687 return 1;
688
Justin Bognerf91bc6c2015-02-14 02:01:24 +0000689 CoverageReport Report(ViewOpts, std::move(Coverage));
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000690 if (SourceFiles.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000691 Report.renderFileReports(llvm::outs());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000692 else
693 Report.renderFunctionReports(SourceFiles, llvm::outs());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000694 return 0;
695}
696
Justin Bognerd249a3b2014-10-30 20:57:49 +0000697int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000698 CodeCoverageTool Tool;
699 return Tool.run(CodeCoverageTool::Show, argc, argv);
700}
701
Justin Bognerd249a3b2014-10-30 20:57:49 +0000702int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000703 CodeCoverageTool Tool;
704 return Tool.run(CodeCoverageTool::Report, argc, argv);
705}