blob: 8d9f4d022cafb88bb91eec124865c298e32f4be2 [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"
Vedant Kumar6e28bcd2017-02-05 20:10:58 +000018#include "CoverageSummaryInfo.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000019#include "CoverageViewOptions.h"
Easwaran Ramandc707122016-04-29 18:53:05 +000020#include "RenderingSupport.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000021#include "SourceCoverageView.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000022#include "llvm/ADT/SmallString.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000023#include "llvm/ADT/StringRef.h"
Justin Bogner43795352015-03-11 02:30:51 +000024#include "llvm/ADT/Triple.h"
Easwaran Ramandc707122016-04-29 18:53:05 +000025#include "llvm/ProfileData/Coverage/CoverageMapping.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000026#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FileSystem.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000029#include "llvm/Support/Format.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000030#include "llvm/Support/MemoryBuffer.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000031#include "llvm/Support/Path.h"
Justin Bognercfb53e42015-03-19 00:02:23 +000032#include "llvm/Support/Process.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000033#include "llvm/Support/Program.h"
Pavel Labath757ca882016-10-24 10:59:17 +000034#include "llvm/Support/ScopedPrinter.h"
Vedant Kumar7fa75102017-07-11 01:23:29 +000035#include "llvm/Support/Threading.h"
Vedant Kumar86b2ac632016-07-13 21:38:36 +000036#include "llvm/Support/ThreadPool.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000037#include "llvm/Support/ToolOutputFile.h"
Sean Evesonfa8ef352017-09-28 10:07:30 +000038
Alex Lorenze82d89c2014-08-22 22:56:03 +000039#include <functional>
Sean Evesonfa8ef352017-09-28 10:07:30 +000040#include <map>
Justin Bognere53be062014-09-09 05:32:18 +000041#include <system_error>
Alex Lorenze82d89c2014-08-22 22:56:03 +000042
43using namespace llvm;
44using namespace coverage;
45
Vedant Kumar5c61c702016-10-25 00:08:33 +000046void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping,
Vedant Kumar72c3a112017-09-08 18:44:49 +000047 const CoverageViewOptions &Options,
Vedant Kumar7101d732016-07-26 22:50:58 +000048 raw_ostream &OS);
49
Alex Lorenze82d89c2014-08-22 22:56:03 +000050namespace {
Alex Lorenze82d89c2014-08-22 22:56:03 +000051/// \brief The implementation of the coverage tool.
52class CodeCoverageTool {
53public:
54 enum Command {
55 /// \brief The show command.
56 Show,
57 /// \brief The report command.
Vedant Kumar7101d732016-07-26 22:50:58 +000058 Report,
59 /// \brief The export command.
60 Export
Alex Lorenze82d89c2014-08-22 22:56:03 +000061 };
62
Vedant Kumar46103672016-09-22 21:49:47 +000063 int run(Command Cmd, int argc, const char **argv);
64
65private:
Alex Lorenze82d89c2014-08-22 22:56:03 +000066 /// \brief Print the error message to the error output stream.
67 void error(const Twine &Message, StringRef Whence = "");
68
Vedant Kumarb3020632016-07-18 17:53:12 +000069 /// \brief Print the warning message to the error output stream.
70 void warning(const Twine &Message, StringRef Whence = "");
Vedant Kumar86b2ac632016-07-13 21:38:36 +000071
Vedant Kumarbc647982016-09-23 18:57:32 +000072 /// \brief Convert \p Path into an absolute path and append it to the list
73 /// of collected paths.
Vedant Kumarcef440f2016-06-28 16:12:18 +000074 void addCollectedPath(const std::string &Path);
75
Vedant Kumar1ce90d82016-09-22 21:49:43 +000076 /// \brief If \p Path is a regular file, collect the path. If it's a
77 /// directory, recursively collect all of the paths within the directory.
78 void collectPaths(const std::string &Path);
79
Alex Lorenze82d89c2014-08-22 22:56:03 +000080 /// \brief Return a memory buffer for the given source file.
81 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
82
Justin Bogner953e2402014-09-20 15:31:56 +000083 /// \brief Create source views for the expansions of the view.
84 void attachExpansionSubViews(SourceCoverageView &View,
85 ArrayRef<ExpansionRecord> Expansions,
Vedant Kumarf681e2e2016-07-15 01:19:33 +000086 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000087
Justin Bogner953e2402014-09-20 15:31:56 +000088 /// \brief Create the source view of a particular function.
Justin Bogner5a6edad2014-09-19 19:07:17 +000089 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000090 createFunctionView(const FunctionRecord &Function,
91 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000092
93 /// \brief Create the main source view of a particular source file.
Justin Bogner5a6edad2014-09-19 19:07:17 +000094 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000095 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000096
Simon Pilgrimdae11f72016-11-20 13:31:13 +000097 /// \brief Load the coverage mapping data. Return nullptr if an error occurred.
Justin Bogner953e2402014-09-20 15:31:56 +000098 std::unique_ptr<CoverageMapping> load();
Alex Lorenze82d89c2014-08-22 22:56:03 +000099
Sean Eveson9edfeac2017-08-14 10:20:12 +0000100 /// \brief Create a mapping from files in the Coverage data to local copies
101 /// (path-equivalence).
102 void remapPathNames(const CoverageMapping &Coverage);
103
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000104 /// \brief Remove input source files which aren't mapped by \p Coverage.
105 void removeUnmappedInputs(const CoverageMapping &Coverage);
106
Vedant Kumar424f51b2016-07-15 22:44:57 +0000107 /// \brief If a demangler is available, demangle all symbol names.
108 void demangleSymbols(const CoverageMapping &Coverage);
109
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000110 /// \brief Write out a source file view to the filesystem.
111 void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
112 CoveragePrinter *Printer, bool ShowFilenames);
113
Benjamin Kramerc321e532016-06-08 19:09:22 +0000114 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000115
116 int show(int argc, const char **argv,
117 CommandLineParserType commandLineParser);
118
119 int report(int argc, const char **argv,
120 CommandLineParserType commandLineParser);
121
Vedant Kumar7101d732016-07-26 22:50:58 +0000122 int export_(int argc, const char **argv,
123 CommandLineParserType commandLineParser);
124
Vedant Kumara3661ef2016-10-25 17:40:55 +0000125 std::vector<StringRef> ObjectFilenames;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000126 CoverageViewOptions ViewOpts;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000127 CoverageFiltersMatchAll Filters;
Vedant Kumar46103672016-09-22 21:49:47 +0000128
129 /// The path to the indexed profile.
130 std::string PGOFilename;
131
132 /// A list of input source files.
Vedant Kumarbc647982016-09-23 18:57:32 +0000133 std::vector<std::string> SourceFiles;
Vedant Kumar46103672016-09-22 21:49:47 +0000134
Sean Eveson9edfeac2017-08-14 10:20:12 +0000135 /// In -path-equivalence mode, this maps the absolute paths from the coverage
136 /// mapping data to the input source files.
Justin Bogner116c1662014-09-19 08:13:12 +0000137 StringMap<std::string> RemappedFilenames;
Vedant Kumar46103672016-09-22 21:49:47 +0000138
Sean Eveson9edfeac2017-08-14 10:20:12 +0000139 /// The coverage data path to be remapped from, and the source path to be
140 /// remapped to, when using -path-equivalence.
141 Optional<std::pair<std::string, std::string>> PathRemapping;
142
Vedant Kumar46103672016-09-22 21:49:47 +0000143 /// The architecture the coverage mapping data targets.
Vedant Kumar4b102c32017-08-01 21:23:26 +0000144 std::vector<StringRef> CoverageArches;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000145
Vedant Kumar6e28bcd2017-02-05 20:10:58 +0000146 /// A cache for demangled symbols.
147 DemangleCache DC;
Vedant Kumar424f51b2016-07-15 22:44:57 +0000148
Vedant Kumarb6bfd472017-02-05 20:10:55 +0000149 /// A lock which guards printing to stderr.
Vedant Kumarb3020632016-07-18 17:53:12 +0000150 std::mutex ErrsLock;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000151
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000152 /// A container for input source file buffers.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000153 std::mutex LoadedSourceFilesLock;
154 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
155 LoadedSourceFiles;
Sean Evesone15300e2017-08-31 09:11:31 +0000156
157 /// Whitelist from -name-whitelist to be used for filtering.
158 std::unique_ptr<SpecialCaseList> NameWhitelist;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000159};
160}
161
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000162static std::string getErrorString(const Twine &Message, StringRef Whence,
163 bool Warning) {
164 std::string Str = (Warning ? "warning" : "error");
165 Str += ": ";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000166 if (!Whence.empty())
Vedant Kumarb95dc462016-07-15 01:53:39 +0000167 Str += Whence.str() + ": ";
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000168 Str += Message.str() + "\n";
169 return Str;
170}
171
172void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000173 std::unique_lock<std::mutex> Guard{ErrsLock};
174 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
175 << getErrorString(Message, Whence, false);
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000176}
177
Vedant Kumarb3020632016-07-18 17:53:12 +0000178void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
179 std::unique_lock<std::mutex> Guard{ErrsLock};
180 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
181 << getErrorString(Message, Whence, true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000182}
183
Vedant Kumarcef440f2016-06-28 16:12:18 +0000184void CodeCoverageTool::addCollectedPath(const std::string &Path) {
Sean Eveson9edfeac2017-08-14 10:20:12 +0000185 SmallString<128> EffectivePath(Path);
186 if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
187 error(EC.message(), Path);
188 return;
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000189 }
Sean Eveson9edfeac2017-08-14 10:20:12 +0000190 sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true);
191 SourceFiles.emplace_back(EffectivePath.str());
Vedant Kumarcef440f2016-06-28 16:12:18 +0000192}
193
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000194void CodeCoverageTool::collectPaths(const std::string &Path) {
195 llvm::sys::fs::file_status Status;
196 llvm::sys::fs::status(Path, Status);
197 if (!llvm::sys::fs::exists(Status)) {
Sean Eveson9edfeac2017-08-14 10:20:12 +0000198 if (PathRemapping)
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000199 addCollectedPath(Path);
200 else
201 error("Missing source file", Path);
202 return;
203 }
204
205 if (llvm::sys::fs::is_regular_file(Status)) {
206 addCollectedPath(Path);
207 return;
208 }
209
210 if (llvm::sys::fs::is_directory(Status)) {
211 std::error_code EC;
212 for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
213 F != E && !EC; F.increment(EC)) {
214 if (llvm::sys::fs::is_regular_file(F->path()))
215 addCollectedPath(F->path());
216 }
217 if (EC)
218 warning(EC.message(), Path);
219 }
220}
221
Alex Lorenze82d89c2014-08-22 22:56:03 +0000222ErrorOr<const MemoryBuffer &>
223CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bogner116c1662014-09-19 08:13:12 +0000224 // If we've remapped filenames, look up the real location for this file.
Vedant Kumar615b85d2016-07-15 01:19:36 +0000225 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Justin Bogner116c1662014-09-19 08:13:12 +0000226 if (!RemappedFilenames.empty()) {
227 auto Loc = RemappedFilenames.find(SourceFile);
228 if (Loc != RemappedFilenames.end())
229 SourceFile = Loc->second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000230 }
Justin Bogner116c1662014-09-19 08:13:12 +0000231 for (const auto &Files : LoadedSourceFiles)
232 if (sys::fs::equivalent(SourceFile, Files.first))
233 return *Files.second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000234 auto Buffer = MemoryBuffer::getFile(SourceFile);
235 if (auto EC = Buffer.getError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000236 error(EC.message(), SourceFile);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000237 return EC;
238 }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000239 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000240 return *LoadedSourceFiles.back().second;
241}
242
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000243void CodeCoverageTool::attachExpansionSubViews(
244 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
245 const CoverageMapping &Coverage) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000246 if (!ViewOpts.ShowExpandedRegions)
247 return;
Justin Bogner953e2402014-09-20 15:31:56 +0000248 for (const auto &Expansion : Expansions) {
249 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
250 if (ExpansionCoverage.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000251 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000252 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
253 if (!SourceBuffer)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000254 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000255
256 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000257 auto SubView =
258 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
259 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000260 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
261 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000262 }
263}
264
Justin Bogner5a6edad2014-09-19 19:07:17 +0000265std::unique_ptr<SourceCoverageView>
Justin Bogner953e2402014-09-20 15:31:56 +0000266CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000267 const CoverageMapping &Coverage) {
Justin Bogner953e2402014-09-20 15:31:56 +0000268 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
269 if (FunctionCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000270 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000271 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner5a6edad2014-09-19 19:07:17 +0000272 if (!SourceBuffer)
273 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000274
275 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumar6e28bcd2017-02-05 20:10:58 +0000276 auto View = SourceCoverageView::create(DC.demangle(Function.Name),
Vedant Kumar0053c0b2016-09-08 00:56:48 +0000277 SourceBuffer.get(), ViewOpts,
278 std::move(FunctionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000279 attachExpansionSubViews(*View, Expansions, Coverage);
280
281 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000282}
283
Justin Bogner953e2402014-09-20 15:31:56 +0000284std::unique_ptr<SourceCoverageView>
285CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000286 const CoverageMapping &Coverage) {
Justin Bogner5a6edad2014-09-19 19:07:17 +0000287 auto SourceBuffer = getSourceFile(SourceFile);
288 if (!SourceBuffer)
289 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000290 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
291 if (FileCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000292 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000293
294 auto Expansions = FileCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000295 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
296 ViewOpts, std::move(FileCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000297 attachExpansionSubViews(*View, Expansions, Coverage);
Vedant Kumar79554e42017-08-02 23:35:24 +0000298 if (!ViewOpts.ShowFunctionInstantiations)
299 return View;
Justin Bogner953e2402014-09-20 15:31:56 +0000300
Vedant Kumardde19c52017-08-02 23:35:25 +0000301 for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) {
302 // Skip functions which have a single instantiation.
303 if (Group.size() < 2)
304 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000305
Vedant Kumardde19c52017-08-02 23:35:25 +0000306 for (const FunctionRecord *Function : Group.getInstantiations()) {
307 std::unique_ptr<SourceCoverageView> SubView{nullptr};
Vedant Kumare9079772016-09-20 21:27:48 +0000308
Vedant Kumardde19c52017-08-02 23:35:25 +0000309 StringRef Funcname = DC.demangle(Function->Name);
310
311 if (Function->ExecutionCount > 0) {
312 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
313 auto SubViewExpansions = SubViewCoverage.getExpansions();
314 SubView = SourceCoverageView::create(
315 Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
316 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
317 }
318
319 unsigned FileID = Function->CountedRegions.front().FileID;
320 unsigned Line = 0;
321 for (const auto &CR : Function->CountedRegions)
322 if (CR.FileID == FileID)
323 Line = std::max(CR.LineEnd, Line);
324 View->addInstantiation(Funcname, Line, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000325 }
326 }
Justin Bogner5a6edad2014-09-19 19:07:17 +0000327 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000328}
329
Justin Bogner65337d12015-05-04 04:09:38 +0000330static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
331 sys::fs::file_status Status;
332 if (sys::fs::status(LHS, Status))
333 return false;
334 auto LHSTime = Status.getLastModificationTime();
335 if (sys::fs::status(RHS, Status))
336 return false;
337 auto RHSTime = Status.getLastModificationTime();
338 return LHSTime > RHSTime;
339}
340
Justin Bogner953e2402014-09-20 15:31:56 +0000341std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000342 for (StringRef ObjectFilename : ObjectFilenames)
343 if (modifiedTimeGT(ObjectFilename, PGOFilename))
344 warning("profile data may be out of date - object is newer",
345 ObjectFilename);
Vedant Kumarb3020632016-07-18 17:53:12 +0000346 auto CoverageOrErr =
Vedant Kumar4b102c32017-08-01 21:23:26 +0000347 CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000348 if (Error E = CoverageOrErr.takeError()) {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000349 error("Failed to load coverage: " + toString(std::move(E)),
350 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "));
Justin Bogner953e2402014-09-20 15:31:56 +0000351 return nullptr;
352 }
353 auto Coverage = std::move(CoverageOrErr.get());
354 unsigned Mismatched = Coverage->getMismatchedCount();
Vedant Kumar18dd9e82017-09-21 01:11:30 +0000355 if (Mismatched) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000356 warning(utostr(Mismatched) + " functions have mismatched data");
Justin Bogner116c1662014-09-19 08:13:12 +0000357
Vedant Kumar18dd9e82017-09-21 01:11:30 +0000358 if (ViewOpts.Debug) {
359 for (const auto &HashMismatch : Coverage->getHashMismatches())
360 errs() << "hash-mismatch: "
361 << "No profile record found for '" << HashMismatch.first << "'"
362 << " with hash = 0x" << utohexstr(HashMismatch.second) << "\n";
363
364 for (const auto &CounterMismatch : Coverage->getCounterMismatches())
365 errs() << "counter-mismatch: "
366 << "Coverage mapping for " << CounterMismatch.first
367 << " only has " << CounterMismatch.second
368 << " valid counter expressions\n";
369 }
370 }
371
Sean Eveson9edfeac2017-08-14 10:20:12 +0000372 remapPathNames(*Coverage);
373
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000374 if (!SourceFiles.empty())
375 removeUnmappedInputs(*Coverage);
376
377 demangleSymbols(*Coverage);
378
379 return Coverage;
380}
381
Sean Eveson9edfeac2017-08-14 10:20:12 +0000382void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
383 if (!PathRemapping)
384 return;
385
386 // Convert remapping paths to native paths with trailing seperators.
387 auto nativeWithTrailing = [](StringRef Path) -> std::string {
388 if (Path.empty())
389 return "";
390 SmallString<128> NativePath;
391 sys::path::native(Path, NativePath);
392 if (!sys::path::is_separator(NativePath.back()))
393 NativePath += sys::path::get_separator();
394 return NativePath.c_str();
395 };
396 std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
397 std::string RemapTo = nativeWithTrailing(PathRemapping->second);
398
399 // Create a mapping from coverage data file paths to local paths.
400 for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
401 SmallString<128> NativeFilename;
402 sys::path::native(Filename, NativeFilename);
403 if (NativeFilename.startswith(RemapFrom)) {
404 RemappedFilenames[Filename] =
405 RemapTo + NativeFilename.substr(RemapFrom.size()).str();
406 }
407 }
408
409 // Convert input files from local paths to coverage data file paths.
410 StringMap<std::string> InvRemappedFilenames;
411 for (const auto &RemappedFilename : RemappedFilenames)
412 InvRemappedFilenames[RemappedFilename.getValue()] = RemappedFilename.getKey();
413
414 for (std::string &Filename : SourceFiles) {
415 SmallString<128> NativeFilename;
416 sys::path::native(Filename, NativeFilename);
417 auto CovFileName = InvRemappedFilenames.find(NativeFilename);
418 if (CovFileName != InvRemappedFilenames.end())
419 Filename = CovFileName->second;
420 }
421}
422
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000423void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
424 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
Vedant Kumar458808802016-09-23 18:57:35 +0000425
426 auto UncoveredFilesIt = SourceFiles.end();
Sean Eveson9edfeac2017-08-14 10:20:12 +0000427 // The user may have specified source files which aren't in the coverage
428 // mapping. Filter these files away.
429 UncoveredFilesIt = std::remove_if(
430 SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
431 return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
432 SF);
433 });
Justin Bogner116c1662014-09-19 08:13:12 +0000434
Vedant Kumar458808802016-09-23 18:57:35 +0000435 SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000436}
437
Vedant Kumar424f51b2016-07-15 22:44:57 +0000438void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
439 if (!ViewOpts.hasDemangler())
440 return;
441
442 // Pass function names to the demangler in a temporary file.
443 int InputFD;
444 SmallString<256> InputPath;
445 std::error_code EC =
446 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
447 if (EC) {
448 error(InputPath, EC.message());
449 return;
450 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000451 ToolOutputFile InputTOF{InputPath, InputFD};
Vedant Kumar424f51b2016-07-15 22:44:57 +0000452
453 unsigned NumSymbols = 0;
454 for (const auto &Function : Coverage.getCoveredFunctions()) {
455 InputTOF.os() << Function.Name << '\n';
456 ++NumSymbols;
457 }
Vedant Kumar554357b2016-07-15 23:08:22 +0000458 InputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000459
460 // Use another temporary file to store the demangler's output.
461 int OutputFD;
462 SmallString<256> OutputPath;
463 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
464 OutputPath);
465 if (EC) {
466 error(OutputPath, EC.message());
467 return;
468 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000469 ToolOutputFile OutputTOF{OutputPath, OutputFD};
Vedant Kumar554357b2016-07-15 23:08:22 +0000470 OutputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000471
472 // Invoke the demangler.
473 std::vector<const char *> ArgsV;
474 for (const std::string &Arg : ViewOpts.DemanglerOpts)
475 ArgsV.push_back(Arg.c_str());
476 ArgsV.push_back(nullptr);
Alexander Kornienko208eecd2017-09-13 17:03:37 +0000477 Optional<StringRef> Redirects[] = {InputPath.str(), OutputPath.str(), {""}};
Vedant Kumar424f51b2016-07-15 22:44:57 +0000478 std::string ErrMsg;
479 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
480 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
481 /*memoryLimit=*/0, &ErrMsg);
482 if (RC) {
483 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
484 return;
485 }
486
487 // Parse the demangler's output.
488 auto BufOrError = MemoryBuffer::getFile(OutputPath);
489 if (!BufOrError) {
490 error(OutputPath, BufOrError.getError().message());
491 return;
492 }
493
494 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
495
496 SmallVector<StringRef, 8> Symbols;
497 StringRef DemanglerData = DemanglerBuf->getBuffer();
498 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
499 /*KeepEmpty=*/false);
500 if (Symbols.size() != NumSymbols) {
501 error("Demangler did not provide expected number of symbols");
502 return;
503 }
504
505 // Cache the demangled names.
506 unsigned I = 0;
507 for (const auto &Function : Coverage.getCoveredFunctions())
Igor Kudrin9e015da2017-02-19 14:26:52 +0000508 // On Windows, lines in the demangler's output file end with "\r\n".
509 // Splitting by '\n' keeps '\r's, so cut them now.
510 DC.DemangledNames[Function.Name] = Symbols[I++].rtrim();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000511}
512
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000513void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
514 CoverageMapping *Coverage,
515 CoveragePrinter *Printer,
516 bool ShowFilenames) {
517 auto View = createSourceFileView(SourceFile, *Coverage);
518 if (!View) {
519 warning("The file '" + SourceFile + "' isn't covered.");
520 return;
521 }
522
523 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
524 if (Error E = OSOrErr.takeError()) {
525 error("Could not create view file!", toString(std::move(E)));
526 return;
527 }
528 auto OS = std::move(OSOrErr.get());
529
530 View->print(*OS.get(), /*Wholefile=*/true,
Sean Evesonfa8ef352017-09-28 10:07:30 +0000531 /*ShowSourceName=*/ShowFilenames,
532 /*ShowTitle=*/ViewOpts.hasOutputDirectory());
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000533 Printer->closeViewFile(std::move(OS));
534}
535
Alex Lorenze82d89c2014-08-22 22:56:03 +0000536int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000537 cl::opt<std::string> CovFilename(
538 cl::Positional, cl::desc("Covered executable or object file."));
539
540 cl::list<std::string> CovFilenames(
541 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
542 cl::CommaSeparated);
Justin Bognerf6c50552014-10-30 20:51:24 +0000543
Alex Lorenze82d89c2014-08-22 22:56:03 +0000544 cl::list<std::string> InputSourceFiles(
545 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
546
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000547 cl::opt<bool> DebugDumpCollectedPaths(
548 "dump-collected-paths", cl::Optional, cl::Hidden,
549 cl::desc("Show the collected paths to source files"));
550
Justin Bogner953e2402014-09-20 15:31:56 +0000551 cl::opt<std::string, true> PGOFilename(
552 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000553 cl::desc(
554 "File with the profile data obtained after an instrumented run"));
555
Vedant Kumar4b102c32017-08-01 21:23:26 +0000556 cl::list<std::string> Arches(
557 "arch", cl::desc("architectures of the coverage mapping binaries"));
Justin Bogner43795352015-03-11 02:30:51 +0000558
Alex Lorenze82d89c2014-08-22 22:56:03 +0000559 cl::opt<bool> DebugDump("dump", cl::Optional,
560 cl::desc("Show internal debug dump"));
561
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000562 cl::opt<CoverageViewOptions::OutputFormat> Format(
563 "format", cl::desc("Output format for line-based coverage reports"),
564 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
565 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000566 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000567 "HTML output")),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000568 cl::init(CoverageViewOptions::OutputFormat::Text));
569
Sean Eveson9edfeac2017-08-14 10:20:12 +0000570 cl::opt<std::string> PathRemap(
571 "path-equivalence", cl::Optional,
572 cl::desc("<from>,<to> Map coverage data paths to local source file "
573 "paths"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000574
575 cl::OptionCategory FilteringCategory("Function filtering options");
576
577 cl::list<std::string> NameFilters(
578 "name", cl::Optional,
579 cl::desc("Show code coverage only for functions with the given name"),
580 cl::ZeroOrMore, cl::cat(FilteringCategory));
581
Sean Evesone15300e2017-08-31 09:11:31 +0000582 cl::list<std::string> NameFilterFiles(
583 "name-whitelist", cl::Optional,
584 cl::desc("Show code coverage only for functions listed in the given "
585 "file"),
586 cl::ZeroOrMore, cl::cat(FilteringCategory));
587
Alex Lorenze82d89c2014-08-22 22:56:03 +0000588 cl::list<std::string> NameRegexFilters(
589 "name-regex", cl::Optional,
590 cl::desc("Show code coverage only for functions that match the given "
591 "regular expression"),
592 cl::ZeroOrMore, cl::cat(FilteringCategory));
593
594 cl::opt<double> RegionCoverageLtFilter(
595 "region-coverage-lt", cl::Optional,
596 cl::desc("Show code coverage only for functions with region coverage "
597 "less than the given threshold"),
598 cl::cat(FilteringCategory));
599
600 cl::opt<double> RegionCoverageGtFilter(
601 "region-coverage-gt", cl::Optional,
602 cl::desc("Show code coverage only for functions with region coverage "
603 "greater than the given threshold"),
604 cl::cat(FilteringCategory));
605
606 cl::opt<double> LineCoverageLtFilter(
607 "line-coverage-lt", cl::Optional,
608 cl::desc("Show code coverage only for functions with line coverage less "
609 "than the given threshold"),
610 cl::cat(FilteringCategory));
611
612 cl::opt<double> LineCoverageGtFilter(
613 "line-coverage-gt", cl::Optional,
614 cl::desc("Show code coverage only for functions with line coverage "
615 "greater than the given threshold"),
616 cl::cat(FilteringCategory));
617
Justin Bogner9deb1d42015-03-19 04:45:16 +0000618 cl::opt<cl::boolOrDefault> UseColor(
619 "use-color", cl::desc("Emit colored output (default=autodetect)"),
620 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000621
Vedant Kumar424f51b2016-07-15 22:44:57 +0000622 cl::list<std::string> DemanglerOpts(
623 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
624
Eli Friedman50479f62017-09-11 22:56:20 +0000625 cl::opt<bool> RegionSummary(
626 "show-region-summary", cl::Optional,
627 cl::desc("Show region statistics in summary table"),
628 cl::init(true));
629
630 cl::opt<bool> InstantiationSummary(
631 "show-instantiation-summary", cl::Optional,
632 cl::desc("Show instantiation statistics in summary table"));
633
Alex Lorenze82d89c2014-08-22 22:56:03 +0000634 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
635 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
636 ViewOpts.Debug = DebugDump;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000637
Vedant Kumara3661ef2016-10-25 17:40:55 +0000638 if (!CovFilename.empty())
639 ObjectFilenames.emplace_back(CovFilename);
640 for (const std::string &Filename : CovFilenames)
641 ObjectFilenames.emplace_back(Filename);
642 if (ObjectFilenames.empty()) {
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000643 errs() << "No filenames specified!\n";
Vedant Kumara3661ef2016-10-25 17:40:55 +0000644 ::exit(1);
645 }
646
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000647 ViewOpts.Format = Format;
648 switch (ViewOpts.Format) {
649 case CoverageViewOptions::OutputFormat::Text:
650 ViewOpts.Colors = UseColor == cl::BOU_UNSET
651 ? sys::Process::StandardOutHasColors()
652 : UseColor == cl::BOU_TRUE;
653 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000654 case CoverageViewOptions::OutputFormat::HTML:
655 if (UseColor == cl::BOU_FALSE)
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000656 errs() << "Color output cannot be disabled when generating html.\n";
Vedant Kumar4c010922016-07-06 21:44:05 +0000657 ViewOpts.Colors = true;
658 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000659 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000660
Sean Eveson9edfeac2017-08-14 10:20:12 +0000661 // If path-equivalence was given and is a comma seperated pair then set
662 // PathRemapping.
663 auto EquivPair = StringRef(PathRemap).split(',');
664 if (!(EquivPair.first.empty() && EquivPair.second.empty()))
665 PathRemapping = EquivPair;
666
Vedant Kumar424f51b2016-07-15 22:44:57 +0000667 // If a demangler is supplied, check if it exists and register it.
668 if (DemanglerOpts.size()) {
669 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
670 if (!DemanglerPathOrErr) {
671 error("Could not find the demangler!",
672 DemanglerPathOrErr.getError().message());
673 return 1;
674 }
675 DemanglerOpts[0] = *DemanglerPathOrErr;
676 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
677 }
678
Sean Evesone15300e2017-08-31 09:11:31 +0000679 // Read in -name-whitelist files.
680 if (!NameFilterFiles.empty()) {
681 std::string SpecialCaseListErr;
682 NameWhitelist =
683 SpecialCaseList::create(NameFilterFiles, SpecialCaseListErr);
684 if (!NameWhitelist)
685 error(SpecialCaseListErr);
686 }
687
Alex Lorenze82d89c2014-08-22 22:56:03 +0000688 // Create the function filters
Sean Evesone15300e2017-08-31 09:11:31 +0000689 if (!NameFilters.empty() || NameWhitelist || !NameRegexFilters.empty()) {
Vedant Kumar8a622382017-08-04 00:36:24 +0000690 auto NameFilterer = llvm::make_unique<CoverageFilters>();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000691 for (const auto &Name : NameFilters)
692 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
Sean Evesone15300e2017-08-31 09:11:31 +0000693 if (NameWhitelist)
694 NameFilterer->push_back(
695 llvm::make_unique<NameWhitelistCoverageFilter>(*NameWhitelist));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000696 for (const auto &Regex : NameRegexFilters)
697 NameFilterer->push_back(
698 llvm::make_unique<NameRegexCoverageFilter>(Regex));
Vedant Kumar8a622382017-08-04 00:36:24 +0000699 Filters.push_back(std::move(NameFilterer));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000700 }
701 if (RegionCoverageLtFilter.getNumOccurrences() ||
702 RegionCoverageGtFilter.getNumOccurrences() ||
703 LineCoverageLtFilter.getNumOccurrences() ||
704 LineCoverageGtFilter.getNumOccurrences()) {
Vedant Kumar8a622382017-08-04 00:36:24 +0000705 auto StatFilterer = llvm::make_unique<CoverageFilters>();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000706 if (RegionCoverageLtFilter.getNumOccurrences())
707 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
708 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
709 if (RegionCoverageGtFilter.getNumOccurrences())
710 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
711 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
712 if (LineCoverageLtFilter.getNumOccurrences())
713 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
714 LineCoverageFilter::LessThan, LineCoverageLtFilter));
715 if (LineCoverageGtFilter.getNumOccurrences())
716 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
717 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
Vedant Kumar8a622382017-08-04 00:36:24 +0000718 Filters.push_back(std::move(StatFilterer));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000719 }
720
Vedant Kumar4b102c32017-08-01 21:23:26 +0000721 if (!Arches.empty()) {
722 for (const std::string &Arch : Arches) {
723 if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
724 error("Unknown architecture: " + Arch);
725 return 1;
726 }
727 CoverageArches.emplace_back(Arch);
728 }
729 if (CoverageArches.size() != ObjectFilenames.size()) {
730 error("Number of architectures doesn't match the number of objects");
731 return 1;
732 }
Justin Bogner43795352015-03-11 02:30:51 +0000733 }
734
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000735 for (const std::string &File : InputSourceFiles)
736 collectPaths(File);
737
738 if (DebugDumpCollectedPaths) {
Vedant Kumarbc647982016-09-23 18:57:32 +0000739 for (const std::string &SF : SourceFiles)
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000740 outs() << SF << '\n';
741 ::exit(0);
Justin Bogner116c1662014-09-19 08:13:12 +0000742 }
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000743
Eli Friedman50479f62017-09-11 22:56:20 +0000744 ViewOpts.ShowRegionSummary = RegionSummary;
745 ViewOpts.ShowInstantiationSummary = InstantiationSummary;
746
Alex Lorenze82d89c2014-08-22 22:56:03 +0000747 return 0;
748 };
749
Alex Lorenze82d89c2014-08-22 22:56:03 +0000750 switch (Cmd) {
751 case Show:
752 return show(argc, argv, commandLineParser);
753 case Report:
754 return report(argc, argv, commandLineParser);
Vedant Kumar7101d732016-07-26 22:50:58 +0000755 case Export:
756 return export_(argc, argv, commandLineParser);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000757 }
758 return 0;
759}
760
761int CodeCoverageTool::show(int argc, const char **argv,
762 CommandLineParserType commandLineParser) {
763
764 cl::OptionCategory ViewCategory("Viewing options");
765
766 cl::opt<bool> ShowLineExecutionCounts(
767 "show-line-counts", cl::Optional,
768 cl::desc("Show the execution counts for each line"), cl::init(true),
769 cl::cat(ViewCategory));
770
771 cl::opt<bool> ShowRegions(
772 "show-regions", cl::Optional,
773 cl::desc("Show the execution counts for each region"),
774 cl::cat(ViewCategory));
775
776 cl::opt<bool> ShowBestLineRegionsCounts(
777 "show-line-counts-or-regions", cl::Optional,
778 cl::desc("Show the execution counts for each line, or the execution "
779 "counts for each region on lines that have multiple regions"),
780 cl::cat(ViewCategory));
781
782 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
783 cl::desc("Show expanded source regions"),
784 cl::cat(ViewCategory));
785
786 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
787 cl::desc("Show function instantiations"),
Vedant Kumar79554e42017-08-02 23:35:24 +0000788 cl::init(true), cl::cat(ViewCategory));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000789
Vedant Kumar7937ef32016-06-28 02:09:39 +0000790 cl::opt<std::string> ShowOutputDirectory(
791 "output-dir", cl::init(""),
792 cl::desc("Directory in which coverage information is written out"));
793 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
794 cl::aliasopt(ShowOutputDirectory));
795
Ying Yi0ef31b72016-08-04 10:39:43 +0000796 cl::opt<uint32_t> TabSize(
Vedant Kumarad547d32016-08-04 18:00:42 +0000797 "tab-size", cl::init(2),
798 cl::desc(
799 "Set tab expansion size for html coverage reports (default = 2)"));
Ying Yi0ef31b72016-08-04 10:39:43 +0000800
Ying Yi84dc9712016-08-24 14:27:23 +0000801 cl::opt<std::string> ProjectTitle(
802 "project-title", cl::Optional,
803 cl::desc("Set project title for the coverage report"));
804
Vedant Kumar7fa75102017-07-11 01:23:29 +0000805 cl::opt<unsigned> NumThreads(
806 "num-threads", cl::init(0),
807 cl::desc("Number of merge threads to use (default: autodetect)"));
808 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
809 cl::aliasopt(NumThreads));
810
Alex Lorenze82d89c2014-08-22 22:56:03 +0000811 auto Err = commandLineParser(argc, argv);
812 if (Err)
813 return Err;
814
Alex Lorenze82d89c2014-08-22 22:56:03 +0000815 ViewOpts.ShowLineNumbers = true;
816 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
817 !ShowRegions || ShowBestLineRegionsCounts;
818 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000819 ViewOpts.ShowExpandedRegions = ShowExpansions;
820 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000821 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
Ying Yi0ef31b72016-08-04 10:39:43 +0000822 ViewOpts.TabSize = TabSize;
Ying Yi84dc9712016-08-24 14:27:23 +0000823 ViewOpts.ProjectTitle = ProjectTitle;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000824
Vedant Kumar64d8a022016-06-28 16:12:20 +0000825 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000826 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
827 error("Could not create output directory!", E.message());
828 return 1;
829 }
830 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000831
Ying Yi84dc9712016-08-24 14:27:23 +0000832 sys::fs::file_status Status;
833 if (sys::fs::status(PGOFilename, Status)) {
834 error("profdata file error: can not get the file status. \n");
835 return 1;
836 }
837
838 auto ModifiedTime = Status.getLastModificationTime();
Pavel Labath757ca882016-10-24 10:59:17 +0000839 std::string ModifiedTimeStr = to_string(ModifiedTime);
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000840 size_t found = ModifiedTimeStr.rfind(':');
Ying Yi84dc9712016-08-24 14:27:23 +0000841 ViewOpts.CreatedTimeStr = (found != std::string::npos)
842 ? "Created: " + ModifiedTimeStr.substr(0, found)
843 : "Created: " + ModifiedTimeStr;
844
Justin Bogner953e2402014-09-20 15:31:56 +0000845 auto Coverage = load();
846 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000847 return 1;
848
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000849 auto Printer = CoveragePrinter::create(ViewOpts);
850
Sean Eveson1439fa62017-09-27 16:20:07 +0000851 if (SourceFiles.empty())
852 // Get the source files from the function coverage mapping.
853 for (StringRef Filename : Coverage->getUniqueSourceFiles())
854 SourceFiles.push_back(Filename);
855
856 // Create an index out of the source files.
857 if (ViewOpts.hasOutputDirectory()) {
Sean Evesonfa8ef352017-09-28 10:07:30 +0000858 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage, Filters)) {
Sean Eveson1439fa62017-09-27 16:20:07 +0000859 error("Could not create index file!", toString(std::move(E)));
860 return 1;
861 }
862 }
863
Sean Evesonfa8ef352017-09-28 10:07:30 +0000864 if (!Filters.empty()) {
865 // Build the map of filenames to functions.
866 std::map<llvm::StringRef, std::vector<const FunctionRecord *>>
867 FilenameFunctionMap;
868 for (const auto &SourceFile : SourceFiles)
869 for (const auto &Function : Coverage->getCoveredFunctions(SourceFile))
870 if (Filters.matches(*Coverage.get(), Function))
871 FilenameFunctionMap[SourceFile].push_back(&Function);
872
873 // Only print filter matching functions for each file.
874 for (const auto &FileFunc : FilenameFunctionMap) {
875 StringRef File = FileFunc.first;
876 const auto &Functions = FileFunc.second;
877
878 auto OSOrErr = Printer->createViewFile(File, /*InToplevel=*/false);
879 if (Error E = OSOrErr.takeError()) {
880 error("Could not create view file!", toString(std::move(E)));
881 return 1;
882 }
883 auto OS = std::move(OSOrErr.get());
884
Sean Evesonea9dcee2017-10-04 08:54:37 +0000885 bool ShowTitle = ViewOpts.hasOutputDirectory();
Sean Evesonfa8ef352017-09-28 10:07:30 +0000886 for (const auto *Function : Functions) {
887 auto FunctionView = createFunctionView(*Function, *Coverage);
888 if (!FunctionView) {
889 warning("Could not read coverage for '" + Function->Name + "'.");
890 continue;
891 }
892 FunctionView->print(*OS.get(), /*WholeFile=*/false,
893 /*ShowSourceName=*/true, ShowTitle);
894 ShowTitle = false;
895 }
896
897 Printer->closeViewFile(std::move(OS));
898 }
899 return 0;
900 }
901
902 // Show files
903 bool ShowFilenames =
904 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
905 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
906
Vedant Kumar7fa75102017-07-11 01:23:29 +0000907 // If NumThreads is not specified, auto-detect a good default.
908 if (NumThreads == 0)
909 NumThreads =
910 std::max(1U, std::min(llvm::heavyweight_hardware_concurrency(),
911 unsigned(SourceFiles.size())));
912
913 if (!ViewOpts.hasOutputDirectory() || NumThreads == 1) {
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000914 for (const std::string &SourceFile : SourceFiles)
915 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
916 ShowFilenames);
917 } else {
918 // In -output-dir mode, it's safe to use multiple threads to print files.
Vedant Kumar7fa75102017-07-11 01:23:29 +0000919 ThreadPool Pool(NumThreads);
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000920 for (const std::string &SourceFile : SourceFiles)
921 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
922 Coverage.get(), Printer.get(), ShowFilenames);
923 Pool.wait();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000924 }
925
926 return 0;
927}
928
929int CodeCoverageTool::report(int argc, const char **argv,
930 CommandLineParserType commandLineParser) {
Vedant Kumar62eb0fd2017-02-05 20:11:08 +0000931 cl::opt<bool> ShowFunctionSummaries(
932 "show-functions", cl::Optional, cl::init(false),
933 cl::desc("Show coverage summaries for each function"));
934
Alex Lorenze82d89c2014-08-22 22:56:03 +0000935 auto Err = commandLineParser(argc, argv);
936 if (Err)
937 return Err;
938
Vedant Kumar431359a2017-02-28 16:57:28 +0000939 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
Vedant Kumar4c010922016-07-06 21:44:05 +0000940 error("HTML output for summary reports is not yet supported.");
Vedant Kumar431359a2017-02-28 16:57:28 +0000941 return 1;
942 }
Vedant Kumar4c010922016-07-06 21:44:05 +0000943
Justin Bogner953e2402014-09-20 15:31:56 +0000944 auto Coverage = load();
945 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000946 return 1;
947
Vedant Kumar702bb9d2016-09-06 22:45:57 +0000948 CoverageReport Report(ViewOpts, *Coverage.get());
Vedant Kumarfeb3f522017-09-25 23:10:03 +0000949 if (!ShowFunctionSummaries) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000950 Report.renderFileReports(llvm::outs());
Vedant Kumarfeb3f522017-09-25 23:10:03 +0000951 } else {
952 if (SourceFiles.empty()) {
953 error("Source files must be specified when -show-functions=true is "
954 "specified");
955 return 1;
956 }
957
Vedant Kumarf2b067c2017-02-05 20:11:03 +0000958 Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
Vedant Kumarfeb3f522017-09-25 23:10:03 +0000959 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000960 return 0;
961}
962
Vedant Kumar7101d732016-07-26 22:50:58 +0000963int CodeCoverageTool::export_(int argc, const char **argv,
964 CommandLineParserType commandLineParser) {
965
966 auto Err = commandLineParser(argc, argv);
967 if (Err)
968 return Err;
969
Vedant Kumar431359a2017-02-28 16:57:28 +0000970 if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text) {
971 error("Coverage data can only be exported as textual JSON.");
972 return 1;
973 }
974
Vedant Kumar7101d732016-07-26 22:50:58 +0000975 auto Coverage = load();
976 if (!Coverage) {
977 error("Could not load coverage information");
978 return 1;
979 }
980
Vedant Kumar72c3a112017-09-08 18:44:49 +0000981 exportCoverageDataToJson(*Coverage.get(), ViewOpts, outs());
Vedant Kumar7101d732016-07-26 22:50:58 +0000982
983 return 0;
984}
985
Justin Bognerd249a3b2014-10-30 20:57:49 +0000986int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000987 CodeCoverageTool Tool;
988 return Tool.run(CodeCoverageTool::Show, argc, argv);
989}
990
Justin Bognerd249a3b2014-10-30 20:57:49 +0000991int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000992 CodeCoverageTool Tool;
993 return Tool.run(CodeCoverageTool::Report, argc, argv);
994}
Vedant Kumar7101d732016-07-26 22:50:58 +0000995
996int exportMain(int argc, const char *argv[]) {
997 CodeCoverageTool Tool;
998 return Tool.run(CodeCoverageTool::Export, argc, argv);
999}