blob: 9eacbcad5ce889e6b1b5a67cd72bbaca63b9e839 [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
Vedant Kumar7101d732016-07-26 22:50:58 +000041void exportCoverageDataToJson(StringRef ObjectFilename,
42 const coverage::CoverageMapping &CoverageMapping,
43 raw_ostream &OS);
44
Alex Lorenze82d89c2014-08-22 22:56:03 +000045namespace {
Alex Lorenze82d89c2014-08-22 22:56:03 +000046/// \brief The implementation of the coverage tool.
47class CodeCoverageTool {
48public:
49 enum Command {
50 /// \brief The show command.
51 Show,
52 /// \brief The report command.
Vedant Kumar7101d732016-07-26 22:50:58 +000053 Report,
54 /// \brief The export command.
55 Export
Alex Lorenze82d89c2014-08-22 22:56:03 +000056 };
57
58 /// \brief Print the error message to the error output stream.
59 void error(const Twine &Message, StringRef Whence = "");
60
Vedant Kumarb3020632016-07-18 17:53:12 +000061 /// \brief Print the warning message to the error output stream.
62 void warning(const Twine &Message, StringRef Whence = "");
Vedant Kumar86b2ac632016-07-13 21:38:36 +000063
Vedant Kumar2ab08da2016-07-18 18:02:54 +000064 /// \brief Copy \p Path into the list of input source files.
Vedant Kumarcef440f2016-06-28 16:12:18 +000065 void addCollectedPath(const std::string &Path);
66
Alex Lorenze82d89c2014-08-22 22:56:03 +000067 /// \brief Return a memory buffer for the given source file.
68 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
69
Justin Bogner953e2402014-09-20 15:31:56 +000070 /// \brief Create source views for the expansions of the view.
71 void attachExpansionSubViews(SourceCoverageView &View,
72 ArrayRef<ExpansionRecord> Expansions,
Vedant Kumarf681e2e2016-07-15 01:19:33 +000073 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000074
Justin Bogner953e2402014-09-20 15:31:56 +000075 /// \brief Create the source view of a particular function.
Justin Bogner5a6edad2014-09-19 19:07:17 +000076 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000077 createFunctionView(const FunctionRecord &Function,
78 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000079
80 /// \brief Create the main source view of a particular source file.
Justin Bogner5a6edad2014-09-19 19:07:17 +000081 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000082 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000083
Vedant Kumarf681e2e2016-07-15 01:19:33 +000084 /// \brief Load the coverage mapping data. Return nullptr if an error occured.
Justin Bogner953e2402014-09-20 15:31:56 +000085 std::unique_ptr<CoverageMapping> load();
Alex Lorenze82d89c2014-08-22 22:56:03 +000086
Vedant Kumar424f51b2016-07-15 22:44:57 +000087 /// \brief If a demangler is available, demangle all symbol names.
88 void demangleSymbols(const CoverageMapping &Coverage);
89
90 /// \brief Demangle \p Sym if possible. Otherwise, just return \p Sym.
91 StringRef getSymbolForHumans(StringRef Sym) const;
92
Alex Lorenze82d89c2014-08-22 22:56:03 +000093 int run(Command Cmd, int argc, const char **argv);
94
Benjamin Kramerc321e532016-06-08 19:09:22 +000095 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
Alex Lorenze82d89c2014-08-22 22:56:03 +000096
97 int show(int argc, const char **argv,
98 CommandLineParserType commandLineParser);
99
100 int report(int argc, const char **argv,
101 CommandLineParserType commandLineParser);
102
Vedant Kumar7101d732016-07-26 22:50:58 +0000103 int export_(int argc, const char **argv,
104 CommandLineParserType commandLineParser);
105
Justin Bognerf6c50552014-10-30 20:51:24 +0000106 std::string ObjectFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000107 CoverageViewOptions ViewOpts;
Justin Bogner953e2402014-09-20 15:31:56 +0000108 std::string PGOFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000109 CoverageFiltersMatchAll Filters;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000110 std::vector<StringRef> SourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000111 bool CompareFilenamesOnly;
Justin Bogner116c1662014-09-19 08:13:12 +0000112 StringMap<std::string> RemappedFilenames;
Frederic Rissebc162a2015-06-22 21:33:24 +0000113 std::string CoverageArch;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000114
115private:
Vedant Kumar424f51b2016-07-15 22:44:57 +0000116 /// A cache for demangled symbol names.
117 StringMap<std::string> DemangledNames;
118
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000119 /// File paths (absolute, or otherwise) to input source files.
Vedant Kumarcef440f2016-06-28 16:12:18 +0000120 std::vector<std::string> CollectedPaths;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000121
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000122 /// Errors and warnings which have not been printed.
Vedant Kumarb3020632016-07-18 17:53:12 +0000123 std::mutex ErrsLock;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000124
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000125 /// A container for input source file buffers.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000126 std::mutex LoadedSourceFilesLock;
127 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
128 LoadedSourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000129};
130}
131
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000132static std::string getErrorString(const Twine &Message, StringRef Whence,
133 bool Warning) {
134 std::string Str = (Warning ? "warning" : "error");
135 Str += ": ";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000136 if (!Whence.empty())
Vedant Kumarb95dc462016-07-15 01:53:39 +0000137 Str += Whence.str() + ": ";
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000138 Str += Message.str() + "\n";
139 return Str;
140}
141
142void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000143 std::unique_lock<std::mutex> Guard{ErrsLock};
144 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
145 << getErrorString(Message, Whence, false);
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000146}
147
Vedant Kumarb3020632016-07-18 17:53:12 +0000148void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
149 std::unique_lock<std::mutex> Guard{ErrsLock};
150 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
151 << getErrorString(Message, Whence, true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000152}
153
Vedant Kumarcef440f2016-06-28 16:12:18 +0000154void CodeCoverageTool::addCollectedPath(const std::string &Path) {
155 CollectedPaths.push_back(Path);
156 SourceFiles.emplace_back(CollectedPaths.back());
157}
158
Alex Lorenze82d89c2014-08-22 22:56:03 +0000159ErrorOr<const MemoryBuffer &>
160CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bogner116c1662014-09-19 08:13:12 +0000161 // If we've remapped filenames, look up the real location for this file.
Vedant Kumar615b85d2016-07-15 01:19:36 +0000162 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Justin Bogner116c1662014-09-19 08:13:12 +0000163 if (!RemappedFilenames.empty()) {
164 auto Loc = RemappedFilenames.find(SourceFile);
165 if (Loc != RemappedFilenames.end())
166 SourceFile = Loc->second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000167 }
Justin Bogner116c1662014-09-19 08:13:12 +0000168 for (const auto &Files : LoadedSourceFiles)
169 if (sys::fs::equivalent(SourceFile, Files.first))
170 return *Files.second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000171 auto Buffer = MemoryBuffer::getFile(SourceFile);
172 if (auto EC = Buffer.getError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000173 error(EC.message(), SourceFile);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000174 return EC;
175 }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000176 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000177 return *LoadedSourceFiles.back().second;
178}
179
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000180void CodeCoverageTool::attachExpansionSubViews(
181 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
182 const CoverageMapping &Coverage) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000183 if (!ViewOpts.ShowExpandedRegions)
184 return;
Justin Bogner953e2402014-09-20 15:31:56 +0000185 for (const auto &Expansion : Expansions) {
186 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
187 if (ExpansionCoverage.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000188 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000189 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
190 if (!SourceBuffer)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000191 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000192
193 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000194 auto SubView =
195 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
196 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000197 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
198 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000199 }
200}
201
Justin Bogner5a6edad2014-09-19 19:07:17 +0000202std::unique_ptr<SourceCoverageView>
Justin Bogner953e2402014-09-20 15:31:56 +0000203CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000204 const CoverageMapping &Coverage) {
Justin Bogner953e2402014-09-20 15:31:56 +0000205 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
206 if (FunctionCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000207 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000208 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner5a6edad2014-09-19 19:07:17 +0000209 if (!SourceBuffer)
210 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000211
212 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumar0053c0b2016-09-08 00:56:48 +0000213 auto View = SourceCoverageView::create(getSymbolForHumans(Function.Name),
214 SourceBuffer.get(), ViewOpts,
215 std::move(FunctionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000216 attachExpansionSubViews(*View, Expansions, Coverage);
217
218 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000219}
220
Justin Bogner953e2402014-09-20 15:31:56 +0000221std::unique_ptr<SourceCoverageView>
222CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000223 const CoverageMapping &Coverage) {
Justin Bogner5a6edad2014-09-19 19:07:17 +0000224 auto SourceBuffer = getSourceFile(SourceFile);
225 if (!SourceBuffer)
226 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000227 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
228 if (FileCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000229 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000230
231 auto Expansions = FileCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000232 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
233 ViewOpts, std::move(FileCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000234 attachExpansionSubViews(*View, Expansions, Coverage);
235
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000236 for (const auto *Function : Coverage.getInstantiations(SourceFile)) {
Vedant Kumara8c396d2016-09-15 06:44:51 +0000237 std::unique_ptr<SourceCoverageView> SubView{nullptr};
Justin Bogner953e2402014-09-20 15:31:56 +0000238
Vedant Kumara8c396d2016-09-15 06:44:51 +0000239 if (Function->ExecutionCount > 0) {
240 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
241 auto SubViewExpansions = SubViewCoverage.getExpansions();
242 SubView = SourceCoverageView::create(
243 getSymbolForHumans(Function->Name), SourceBuffer.get(), ViewOpts,
244 std::move(SubViewCoverage));
245 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000246 }
Vedant Kumara8c396d2016-09-15 06:44:51 +0000247
248 unsigned FileID = Function->CountedRegions.front().FileID;
249 unsigned Line = 0;
250 for (const auto &CR : Function->CountedRegions)
251 if (CR.FileID == FileID)
252 Line = std::max(CR.LineEnd, Line);
253 View->addInstantiation(Function->Name, Line, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000254 }
Justin Bogner5a6edad2014-09-19 19:07:17 +0000255 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000256}
257
Justin Bogner65337d12015-05-04 04:09:38 +0000258static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
259 sys::fs::file_status Status;
260 if (sys::fs::status(LHS, Status))
261 return false;
262 auto LHSTime = Status.getLastModificationTime();
263 if (sys::fs::status(RHS, Status))
264 return false;
265 auto RHSTime = Status.getLastModificationTime();
266 return LHSTime > RHSTime;
267}
268
Justin Bogner953e2402014-09-20 15:31:56 +0000269std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Justin Bogner65337d12015-05-04 04:09:38 +0000270 if (modifiedTimeGT(ObjectFilename, PGOFilename))
Vedant Kumarb3020632016-07-18 17:53:12 +0000271 warning("profile data may be out of date - object is newer",
272 ObjectFilename);
273 auto CoverageOrErr =
274 CoverageMapping::load(ObjectFilename, PGOFilename, CoverageArch);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000275 if (Error E = CoverageOrErr.takeError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000276 error("Failed to load coverage: " + toString(std::move(E)), ObjectFilename);
Justin Bogner953e2402014-09-20 15:31:56 +0000277 return nullptr;
278 }
279 auto Coverage = std::move(CoverageOrErr.get());
280 unsigned Mismatched = Coverage->getMismatchedCount();
Vedant Kumarb3020632016-07-18 17:53:12 +0000281 if (Mismatched)
282 warning(utostr(Mismatched) + " functions have mismatched data");
Justin Bogner116c1662014-09-19 08:13:12 +0000283
284 if (CompareFilenamesOnly) {
Justin Bogner953e2402014-09-20 15:31:56 +0000285 auto CoveredFiles = Coverage.get()->getUniqueSourceFiles();
Justin Bogner116c1662014-09-19 08:13:12 +0000286 for (auto &SF : SourceFiles) {
287 StringRef SFBase = sys::path::filename(SF);
288 for (const auto &CF : CoveredFiles)
289 if (SFBase == sys::path::filename(CF)) {
290 RemappedFilenames[CF] = SF;
291 SF = CF;
292 break;
293 }
294 }
295 }
296
Vedant Kumar424f51b2016-07-15 22:44:57 +0000297 demangleSymbols(*Coverage);
298
Justin Bogner953e2402014-09-20 15:31:56 +0000299 return Coverage;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000300}
301
Vedant Kumar424f51b2016-07-15 22:44:57 +0000302void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
303 if (!ViewOpts.hasDemangler())
304 return;
305
306 // Pass function names to the demangler in a temporary file.
307 int InputFD;
308 SmallString<256> InputPath;
309 std::error_code EC =
310 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
311 if (EC) {
312 error(InputPath, EC.message());
313 return;
314 }
315 tool_output_file InputTOF{InputPath, InputFD};
316
317 unsigned NumSymbols = 0;
318 for (const auto &Function : Coverage.getCoveredFunctions()) {
319 InputTOF.os() << Function.Name << '\n';
320 ++NumSymbols;
321 }
Vedant Kumar554357b2016-07-15 23:08:22 +0000322 InputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000323
324 // Use another temporary file to store the demangler's output.
325 int OutputFD;
326 SmallString<256> OutputPath;
327 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
328 OutputPath);
329 if (EC) {
330 error(OutputPath, EC.message());
331 return;
332 }
333 tool_output_file OutputTOF{OutputPath, OutputFD};
Vedant Kumar554357b2016-07-15 23:08:22 +0000334 OutputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000335
336 // Invoke the demangler.
337 std::vector<const char *> ArgsV;
338 for (const std::string &Arg : ViewOpts.DemanglerOpts)
339 ArgsV.push_back(Arg.c_str());
340 ArgsV.push_back(nullptr);
Vedant Kumar38202c02016-07-15 23:15:35 +0000341 StringRef InputPathRef = InputPath.str();
342 StringRef OutputPathRef = OutputPath.str();
343 StringRef StderrRef;
Vedant Kumar424f51b2016-07-15 22:44:57 +0000344 const StringRef *Redirects[] = {&InputPathRef, &OutputPathRef, &StderrRef};
345 std::string ErrMsg;
346 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
347 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
348 /*memoryLimit=*/0, &ErrMsg);
349 if (RC) {
350 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
351 return;
352 }
353
354 // Parse the demangler's output.
355 auto BufOrError = MemoryBuffer::getFile(OutputPath);
356 if (!BufOrError) {
357 error(OutputPath, BufOrError.getError().message());
358 return;
359 }
360
361 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
362
363 SmallVector<StringRef, 8> Symbols;
364 StringRef DemanglerData = DemanglerBuf->getBuffer();
365 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
366 /*KeepEmpty=*/false);
367 if (Symbols.size() != NumSymbols) {
368 error("Demangler did not provide expected number of symbols");
369 return;
370 }
371
372 // Cache the demangled names.
373 unsigned I = 0;
374 for (const auto &Function : Coverage.getCoveredFunctions())
375 DemangledNames[Function.Name] = Symbols[I++];
376}
377
378StringRef CodeCoverageTool::getSymbolForHumans(StringRef Sym) const {
379 const auto DemangledName = DemangledNames.find(Sym);
380 if (DemangledName == DemangledNames.end())
381 return Sym;
382 return DemangledName->getValue();
383}
384
Alex Lorenze82d89c2014-08-22 22:56:03 +0000385int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Justin Bognerf6c50552014-10-30 20:51:24 +0000386 cl::opt<std::string, true> ObjectFilename(
387 cl::Positional, cl::Required, cl::location(this->ObjectFilename),
388 cl::desc("Covered executable or object file."));
389
Alex Lorenze82d89c2014-08-22 22:56:03 +0000390 cl::list<std::string> InputSourceFiles(
391 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
392
Justin Bogner953e2402014-09-20 15:31:56 +0000393 cl::opt<std::string, true> PGOFilename(
394 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000395 cl::desc(
396 "File with the profile data obtained after an instrumented run"));
397
Justin Bogner43795352015-03-11 02:30:51 +0000398 cl::opt<std::string> Arch(
399 "arch", cl::desc("architecture of the coverage mapping binary"));
400
Alex Lorenze82d89c2014-08-22 22:56:03 +0000401 cl::opt<bool> DebugDump("dump", cl::Optional,
402 cl::desc("Show internal debug dump"));
403
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000404 cl::opt<CoverageViewOptions::OutputFormat> Format(
405 "format", cl::desc("Output format for line-based coverage reports"),
406 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
407 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000408 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
409 "HTML output"),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000410 clEnumValEnd),
411 cl::init(CoverageViewOptions::OutputFormat::Text));
412
Alex Lorenze82d89c2014-08-22 22:56:03 +0000413 cl::opt<bool> FilenameEquivalence(
414 "filename-equivalence", cl::Optional,
Justin Bogner116c1662014-09-19 08:13:12 +0000415 cl::desc("Treat source files as equivalent to paths in the coverage data "
416 "when the file names match, even if the full paths do not"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000417
418 cl::OptionCategory FilteringCategory("Function filtering options");
419
420 cl::list<std::string> NameFilters(
421 "name", cl::Optional,
422 cl::desc("Show code coverage only for functions with the given name"),
423 cl::ZeroOrMore, cl::cat(FilteringCategory));
424
425 cl::list<std::string> NameRegexFilters(
426 "name-regex", cl::Optional,
427 cl::desc("Show code coverage only for functions that match the given "
428 "regular expression"),
429 cl::ZeroOrMore, cl::cat(FilteringCategory));
430
431 cl::opt<double> RegionCoverageLtFilter(
432 "region-coverage-lt", cl::Optional,
433 cl::desc("Show code coverage only for functions with region coverage "
434 "less than the given threshold"),
435 cl::cat(FilteringCategory));
436
437 cl::opt<double> RegionCoverageGtFilter(
438 "region-coverage-gt", cl::Optional,
439 cl::desc("Show code coverage only for functions with region coverage "
440 "greater than the given threshold"),
441 cl::cat(FilteringCategory));
442
443 cl::opt<double> LineCoverageLtFilter(
444 "line-coverage-lt", cl::Optional,
445 cl::desc("Show code coverage only for functions with line coverage less "
446 "than the given threshold"),
447 cl::cat(FilteringCategory));
448
449 cl::opt<double> LineCoverageGtFilter(
450 "line-coverage-gt", cl::Optional,
451 cl::desc("Show code coverage only for functions with line coverage "
452 "greater than the given threshold"),
453 cl::cat(FilteringCategory));
454
Justin Bogner9deb1d42015-03-19 04:45:16 +0000455 cl::opt<cl::boolOrDefault> UseColor(
456 "use-color", cl::desc("Emit colored output (default=autodetect)"),
457 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000458
Vedant Kumar424f51b2016-07-15 22:44:57 +0000459 cl::list<std::string> DemanglerOpts(
460 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
461
Alex Lorenze82d89c2014-08-22 22:56:03 +0000462 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
463 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
464 ViewOpts.Debug = DebugDump;
465 CompareFilenamesOnly = FilenameEquivalence;
466
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000467 ViewOpts.Format = Format;
Ying Yi84dc9712016-08-24 14:27:23 +0000468 SmallString<128> ObjectFilePath(this->ObjectFilename);
469 if (std::error_code EC = sys::fs::make_absolute(ObjectFilePath)) {
470 error(EC.message(), this->ObjectFilename);
471 return 1;
472 }
Ying Yi76eb2192016-08-30 07:01:37 +0000473 sys::path::native(ObjectFilePath);
Ying Yi84dc9712016-08-24 14:27:23 +0000474 ViewOpts.ObjectFilename = ObjectFilePath.c_str();
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000475 switch (ViewOpts.Format) {
476 case CoverageViewOptions::OutputFormat::Text:
477 ViewOpts.Colors = UseColor == cl::BOU_UNSET
478 ? sys::Process::StandardOutHasColors()
479 : UseColor == cl::BOU_TRUE;
480 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000481 case CoverageViewOptions::OutputFormat::HTML:
482 if (UseColor == cl::BOU_FALSE)
483 error("Color output cannot be disabled when generating html.");
484 ViewOpts.Colors = true;
485 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000486 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000487
Vedant Kumar424f51b2016-07-15 22:44:57 +0000488 // If a demangler is supplied, check if it exists and register it.
489 if (DemanglerOpts.size()) {
490 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
491 if (!DemanglerPathOrErr) {
492 error("Could not find the demangler!",
493 DemanglerPathOrErr.getError().message());
494 return 1;
495 }
496 DemanglerOpts[0] = *DemanglerPathOrErr;
497 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
498 }
499
Alex Lorenze82d89c2014-08-22 22:56:03 +0000500 // Create the function filters
501 if (!NameFilters.empty() || !NameRegexFilters.empty()) {
502 auto NameFilterer = new CoverageFilters;
503 for (const auto &Name : NameFilters)
504 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
505 for (const auto &Regex : NameRegexFilters)
506 NameFilterer->push_back(
507 llvm::make_unique<NameRegexCoverageFilter>(Regex));
508 Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
509 }
510 if (RegionCoverageLtFilter.getNumOccurrences() ||
511 RegionCoverageGtFilter.getNumOccurrences() ||
512 LineCoverageLtFilter.getNumOccurrences() ||
513 LineCoverageGtFilter.getNumOccurrences()) {
514 auto StatFilterer = new CoverageFilters;
515 if (RegionCoverageLtFilter.getNumOccurrences())
516 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
517 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
518 if (RegionCoverageGtFilter.getNumOccurrences())
519 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
520 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
521 if (LineCoverageLtFilter.getNumOccurrences())
522 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
523 LineCoverageFilter::LessThan, LineCoverageLtFilter));
524 if (LineCoverageGtFilter.getNumOccurrences())
525 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
526 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
527 Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
528 }
529
Frederic Rissebc162a2015-06-22 21:33:24 +0000530 if (!Arch.empty() &&
531 Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000532 error("Unknown architecture: " + Arch);
Frederic Rissebc162a2015-06-22 21:33:24 +0000533 return 1;
Justin Bogner43795352015-03-11 02:30:51 +0000534 }
Frederic Rissebc162a2015-06-22 21:33:24 +0000535 CoverageArch = Arch;
Justin Bogner43795352015-03-11 02:30:51 +0000536
Justin Bogner116c1662014-09-19 08:13:12 +0000537 for (const auto &File : InputSourceFiles) {
538 SmallString<128> Path(File);
Vedant Kumarb3020632016-07-18 17:53:12 +0000539 if (!CompareFilenamesOnly) {
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000540 if (std::error_code EC = sys::fs::make_absolute(Path)) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000541 error(EC.message(), File);
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000542 return 1;
543 }
Vedant Kumarb3020632016-07-18 17:53:12 +0000544 }
Vedant Kumarcef440f2016-06-28 16:12:18 +0000545 addCollectedPath(Path.str());
Justin Bogner116c1662014-09-19 08:13:12 +0000546 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000547 return 0;
548 };
549
Alex Lorenze82d89c2014-08-22 22:56:03 +0000550 switch (Cmd) {
551 case Show:
552 return show(argc, argv, commandLineParser);
553 case Report:
554 return report(argc, argv, commandLineParser);
Vedant Kumar7101d732016-07-26 22:50:58 +0000555 case Export:
556 return export_(argc, argv, commandLineParser);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000557 }
558 return 0;
559}
560
561int CodeCoverageTool::show(int argc, const char **argv,
562 CommandLineParserType commandLineParser) {
563
564 cl::OptionCategory ViewCategory("Viewing options");
565
566 cl::opt<bool> ShowLineExecutionCounts(
567 "show-line-counts", cl::Optional,
568 cl::desc("Show the execution counts for each line"), cl::init(true),
569 cl::cat(ViewCategory));
570
571 cl::opt<bool> ShowRegions(
572 "show-regions", cl::Optional,
573 cl::desc("Show the execution counts for each region"),
574 cl::cat(ViewCategory));
575
576 cl::opt<bool> ShowBestLineRegionsCounts(
577 "show-line-counts-or-regions", cl::Optional,
578 cl::desc("Show the execution counts for each line, or the execution "
579 "counts for each region on lines that have multiple regions"),
580 cl::cat(ViewCategory));
581
582 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
583 cl::desc("Show expanded source regions"),
584 cl::cat(ViewCategory));
585
586 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
587 cl::desc("Show function instantiations"),
588 cl::cat(ViewCategory));
589
Vedant Kumar7937ef32016-06-28 02:09:39 +0000590 cl::opt<std::string> ShowOutputDirectory(
591 "output-dir", cl::init(""),
592 cl::desc("Directory in which coverage information is written out"));
593 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
594 cl::aliasopt(ShowOutputDirectory));
595
Ying Yi0ef31b72016-08-04 10:39:43 +0000596 cl::opt<uint32_t> TabSize(
Vedant Kumarad547d32016-08-04 18:00:42 +0000597 "tab-size", cl::init(2),
598 cl::desc(
599 "Set tab expansion size for html coverage reports (default = 2)"));
Ying Yi0ef31b72016-08-04 10:39:43 +0000600
Ying Yi84dc9712016-08-24 14:27:23 +0000601 cl::opt<std::string> ProjectTitle(
602 "project-title", cl::Optional,
603 cl::desc("Set project title for the coverage report"));
604
Alex Lorenze82d89c2014-08-22 22:56:03 +0000605 auto Err = commandLineParser(argc, argv);
606 if (Err)
607 return Err;
608
Alex Lorenze82d89c2014-08-22 22:56:03 +0000609 ViewOpts.ShowLineNumbers = true;
610 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
611 !ShowRegions || ShowBestLineRegionsCounts;
612 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
613 ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
614 ViewOpts.ShowExpandedRegions = ShowExpansions;
615 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000616 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
Ying Yi0ef31b72016-08-04 10:39:43 +0000617 ViewOpts.TabSize = TabSize;
Ying Yi84dc9712016-08-24 14:27:23 +0000618 ViewOpts.ProjectTitle = ProjectTitle;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000619
Vedant Kumar64d8a022016-06-28 16:12:20 +0000620 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000621 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
622 error("Could not create output directory!", E.message());
623 return 1;
624 }
625 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000626
Ying Yi84dc9712016-08-24 14:27:23 +0000627 sys::fs::file_status Status;
628 if (sys::fs::status(PGOFilename, Status)) {
629 error("profdata file error: can not get the file status. \n");
630 return 1;
631 }
632
633 auto ModifiedTime = Status.getLastModificationTime();
634 std::string ModifiedTimeStr = ModifiedTime.str();
635 size_t found = ModifiedTimeStr.rfind(":");
636 ViewOpts.CreatedTimeStr = (found != std::string::npos)
637 ? "Created: " + ModifiedTimeStr.substr(0, found)
638 : "Created: " + ModifiedTimeStr;
639
Justin Bogner953e2402014-09-20 15:31:56 +0000640 auto Coverage = load();
641 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000642 return 1;
643
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000644 auto Printer = CoveragePrinter::create(ViewOpts);
645
Alex Lorenze82d89c2014-08-22 22:56:03 +0000646 if (!Filters.empty()) {
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000647 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
648 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000649 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000650 return 1;
651 }
652 auto OS = std::move(OSOrErr.get());
653
654 // Show functions.
Justin Bogner953e2402014-09-20 15:31:56 +0000655 for (const auto &Function : Coverage->getCoveredFunctions()) {
656 if (!Filters.matches(Function))
Alex Lorenze82d89c2014-08-22 22:56:03 +0000657 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000658
659 auto mainView = createFunctionView(Function, *Coverage);
Justin Bogner5a6edad2014-09-19 19:07:17 +0000660 if (!mainView) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000661 warning("Could not read coverage for '" + Function.Name + "'.");
Justin Bogner5a6edad2014-09-19 19:07:17 +0000662 continue;
663 }
Vedant Kumar7937ef32016-06-28 02:09:39 +0000664
Vedant Kumar7937ef32016-06-28 02:09:39 +0000665 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000666 }
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000667
668 Printer->closeViewFile(std::move(OS));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000669 return 0;
670 }
671
672 // Show files
Ying Yi84dc9712016-08-24 14:27:23 +0000673 bool ShowFilenames =
Ying Yi24e91bd2016-09-06 21:41:38 +0000674 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
Ying Yi84dc9712016-08-24 14:27:23 +0000675 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000676
Justin Bogner116c1662014-09-19 08:13:12 +0000677 if (SourceFiles.empty())
Vedant Kumar64d8a022016-06-28 16:12:20 +0000678 // Get the source files from the function coverage mapping.
Justin Bogner953e2402014-09-20 15:31:56 +0000679 for (StringRef Filename : Coverage->getUniqueSourceFiles())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000680 SourceFiles.push_back(Filename);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000681
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000682 // Create an index out of the source files.
683 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumara59334d2016-09-09 01:32:55 +0000684 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000685 error("Could not create index file!", toString(std::move(E)));
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000686 return 1;
687 }
688 }
689
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000690 // In -output-dir mode, it's safe to use multiple threads to print files.
691 unsigned ThreadCount = 1;
692 if (ViewOpts.hasOutputDirectory())
693 ThreadCount = std::thread::hardware_concurrency();
694 ThreadPool Pool(ThreadCount);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000695
Vedant Kumar84c452d2016-07-15 01:19:35 +0000696 for (StringRef SourceFile : SourceFiles) {
697 Pool.async([this, SourceFile, &Coverage, &Printer, ShowFilenames] {
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000698 auto View = createSourceFileView(SourceFile, *Coverage);
699 if (!View) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000700 warning("The file '" + SourceFile.str() + "' isn't covered.");
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000701 return;
702 }
703
704 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
705 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000706 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000707 return;
708 }
709 auto OS = std::move(OSOrErr.get());
710
711 View->print(*OS.get(), /*Wholefile=*/true,
712 /*ShowSourceName=*/ShowFilenames);
713 Printer->closeViewFile(std::move(OS));
714 });
Alex Lorenze82d89c2014-08-22 22:56:03 +0000715 }
716
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000717 Pool.wait();
718
Alex Lorenze82d89c2014-08-22 22:56:03 +0000719 return 0;
720}
721
722int CodeCoverageTool::report(int argc, const char **argv,
723 CommandLineParserType commandLineParser) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000724 auto Err = commandLineParser(argc, argv);
725 if (Err)
726 return Err;
727
Vedant Kumar4c010922016-07-06 21:44:05 +0000728 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
729 error("HTML output for summary reports is not yet supported.");
730
Justin Bogner953e2402014-09-20 15:31:56 +0000731 auto Coverage = load();
732 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000733 return 1;
734
Vedant Kumar702bb9d2016-09-06 22:45:57 +0000735 CoverageReport Report(ViewOpts, *Coverage.get());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000736 if (SourceFiles.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000737 Report.renderFileReports(llvm::outs());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000738 else
739 Report.renderFunctionReports(SourceFiles, llvm::outs());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000740 return 0;
741}
742
Vedant Kumar7101d732016-07-26 22:50:58 +0000743int CodeCoverageTool::export_(int argc, const char **argv,
744 CommandLineParserType commandLineParser) {
745
746 auto Err = commandLineParser(argc, argv);
747 if (Err)
748 return Err;
749
750 auto Coverage = load();
751 if (!Coverage) {
752 error("Could not load coverage information");
753 return 1;
754 }
755
756 exportCoverageDataToJson(ObjectFilename, *Coverage.get(), outs());
757
758 return 0;
759}
760
Justin Bognerd249a3b2014-10-30 20:57:49 +0000761int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000762 CodeCoverageTool Tool;
763 return Tool.run(CodeCoverageTool::Show, argc, argv);
764}
765
Justin Bognerd249a3b2014-10-30 20:57:49 +0000766int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000767 CodeCoverageTool Tool;
768 return Tool.run(CodeCoverageTool::Report, argc, argv);
769}
Vedant Kumar7101d732016-07-26 22:50:58 +0000770
771int exportMain(int argc, const char *argv[]) {
772 CodeCoverageTool Tool;
773 return Tool.run(CodeCoverageTool::Export, argc, argv);
774}