1 //=-- CoverageMapping.h - Code coverage mapping support ---------*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Code coverage mapping data is generated by clang and read by
11 // llvm-cov to show code coverage statistics for a file.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_PROFILEDATA_COVERAGEMAPPING_H_
16 #define LLVM_PROFILEDATA_COVERAGEMAPPING_H_
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/Hashing.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/iterator.h"
23 #include "llvm/ProfileData/InstrProfData.inc"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorOr.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <system_error>
31 class IndexedInstrProfReader;
34 class CoverageMappingReader;
36 class CoverageMapping;
37 struct CounterExpressions;
39 /// \brief A Counter is an abstract value that describes how to compute the
40 /// execution count for a region of code using the collected profile count data.
42 enum CounterKind { Zero, CounterValueReference, Expression };
43 static const unsigned EncodingTagBits = 2;
44 static const unsigned EncodingTagMask = 0x3;
45 static const unsigned EncodingCounterTagAndExpansionRegionTagBits =
52 Counter(CounterKind Kind, unsigned ID) : Kind(Kind), ID(ID) {}
55 Counter() : Kind(Zero), ID(0) {}
57 CounterKind getKind() const { return Kind; }
59 bool isZero() const { return Kind == Zero; }
61 bool isExpression() const { return Kind == Expression; }
63 unsigned getCounterID() const { return ID; }
65 unsigned getExpressionID() const { return ID; }
67 friend bool operator==(const Counter &LHS, const Counter &RHS) {
68 return LHS.Kind == RHS.Kind && LHS.ID == RHS.ID;
71 friend bool operator!=(const Counter &LHS, const Counter &RHS) {
75 friend bool operator<(const Counter &LHS, const Counter &RHS) {
76 return std::tie(LHS.Kind, LHS.ID) < std::tie(RHS.Kind, RHS.ID);
79 /// \brief Return the counter that represents the number zero.
80 static Counter getZero() { return Counter(); }
82 /// \brief Return the counter that corresponds to a specific profile counter.
83 static Counter getCounter(unsigned CounterId) {
84 return Counter(CounterValueReference, CounterId);
87 /// \brief Return the counter that corresponds to a specific
88 /// addition counter expression.
89 static Counter getExpression(unsigned ExpressionId) {
90 return Counter(Expression, ExpressionId);
94 /// \brief A Counter expression is a value that represents an arithmetic
95 /// operation with two counters.
96 struct CounterExpression {
97 enum ExprKind { Subtract, Add };
101 CounterExpression(ExprKind Kind, Counter LHS, Counter RHS)
102 : Kind(Kind), LHS(LHS), RHS(RHS) {}
105 /// \brief A Counter expression builder is used to construct the
106 /// counter expressions. It avoids unnecessary duplication
107 /// and simplifies algebraic expressions.
108 class CounterExpressionBuilder {
109 /// \brief A list of all the counter expressions
110 std::vector<CounterExpression> Expressions;
111 /// \brief A lookup table for the index of a given expression.
112 llvm::DenseMap<CounterExpression, unsigned> ExpressionIndices;
114 /// \brief Return the counter which corresponds to the given expression.
116 /// If the given expression is already stored in the builder, a counter
117 /// that references that expression is returned. Otherwise, the given
118 /// expression is added to the builder's collection of expressions.
119 Counter get(const CounterExpression &E);
121 /// \brief Gather the terms of the expression tree for processing.
123 /// This collects each addition and subtraction referenced by the counter into
124 /// a sequence that can be sorted and combined to build a simplified counter
126 void extractTerms(Counter C, int Sign,
127 SmallVectorImpl<std::pair<unsigned, int>> &Terms);
129 /// \brief Simplifies the given expression tree
130 /// by getting rid of algebraically redundant operations.
131 Counter simplify(Counter ExpressionTree);
134 ArrayRef<CounterExpression> getExpressions() const { return Expressions; }
136 /// \brief Return a counter that represents the expression
137 /// that adds LHS and RHS.
138 Counter add(Counter LHS, Counter RHS);
140 /// \brief Return a counter that represents the expression
141 /// that subtracts RHS from LHS.
142 Counter subtract(Counter LHS, Counter RHS);
145 /// \brief A Counter mapping region associates a source range with
146 /// a specific counter.
147 struct CounterMappingRegion {
149 /// \brief A CodeRegion associates some code with a counter
152 /// \brief An ExpansionRegion represents a file expansion region that
153 /// associates a source range with the expansion of a virtual source file,
154 /// such as for a macro instantiation or #include file.
157 /// \brief A SkippedRegion represents a source range with code that
158 /// was skipped by a preprocessor or similar means.
163 unsigned FileID, ExpandedFileID;
164 unsigned LineStart, ColumnStart, LineEnd, ColumnEnd;
167 CounterMappingRegion(Counter Count, unsigned FileID, unsigned ExpandedFileID,
168 unsigned LineStart, unsigned ColumnStart,
169 unsigned LineEnd, unsigned ColumnEnd, RegionKind Kind)
170 : Count(Count), FileID(FileID), ExpandedFileID(ExpandedFileID),
171 LineStart(LineStart), ColumnStart(ColumnStart), LineEnd(LineEnd),
172 ColumnEnd(ColumnEnd), Kind(Kind) {}
174 static CounterMappingRegion
175 makeRegion(Counter Count, unsigned FileID, unsigned LineStart,
176 unsigned ColumnStart, unsigned LineEnd, unsigned ColumnEnd) {
177 return CounterMappingRegion(Count, FileID, 0, LineStart, ColumnStart,
178 LineEnd, ColumnEnd, CodeRegion);
181 static CounterMappingRegion
182 makeExpansion(unsigned FileID, unsigned ExpandedFileID, unsigned LineStart,
183 unsigned ColumnStart, unsigned LineEnd, unsigned ColumnEnd) {
184 return CounterMappingRegion(Counter(), FileID, ExpandedFileID, LineStart,
185 ColumnStart, LineEnd, ColumnEnd,
189 static CounterMappingRegion
190 makeSkipped(unsigned FileID, unsigned LineStart, unsigned ColumnStart,
191 unsigned LineEnd, unsigned ColumnEnd) {
192 return CounterMappingRegion(Counter(), FileID, 0, LineStart, ColumnStart,
193 LineEnd, ColumnEnd, SkippedRegion);
197 inline std::pair<unsigned, unsigned> startLoc() const {
198 return std::pair<unsigned, unsigned>(LineStart, ColumnStart);
201 inline std::pair<unsigned, unsigned> endLoc() const {
202 return std::pair<unsigned, unsigned>(LineEnd, ColumnEnd);
205 bool operator<(const CounterMappingRegion &Other) const {
206 if (FileID != Other.FileID)
207 return FileID < Other.FileID;
208 return startLoc() < Other.startLoc();
211 bool contains(const CounterMappingRegion &Other) const {
212 if (FileID != Other.FileID)
214 if (startLoc() > Other.startLoc())
216 if (endLoc() < Other.endLoc())
222 /// \brief Associates a source range with an execution count.
223 struct CountedRegion : public CounterMappingRegion {
224 uint64_t ExecutionCount;
226 CountedRegion(const CounterMappingRegion &R, uint64_t ExecutionCount)
227 : CounterMappingRegion(R), ExecutionCount(ExecutionCount) {}
230 /// \brief A Counter mapping context is used to connect the counters,
231 /// expressions and the obtained counter values.
232 class CounterMappingContext {
233 ArrayRef<CounterExpression> Expressions;
234 ArrayRef<uint64_t> CounterValues;
237 CounterMappingContext(ArrayRef<CounterExpression> Expressions,
238 ArrayRef<uint64_t> CounterValues = None)
239 : Expressions(Expressions), CounterValues(CounterValues) {}
241 void setCounts(ArrayRef<uint64_t> Counts) { CounterValues = Counts; }
243 void dump(const Counter &C, llvm::raw_ostream &OS) const;
244 void dump(const Counter &C) const { dump(C, dbgs()); }
246 /// \brief Return the number of times that a region of code associated with
247 /// this counter was executed.
248 ErrorOr<int64_t> evaluate(const Counter &C) const;
251 /// \brief Code coverage information for a single function.
252 struct FunctionRecord {
253 /// \brief Raw function name.
255 /// \brief Associated files.
256 std::vector<std::string> Filenames;
257 /// \brief Regions in the function along with their counts.
258 std::vector<CountedRegion> CountedRegions;
259 /// \brief The number of times this function was executed.
260 uint64_t ExecutionCount;
262 FunctionRecord(StringRef Name, ArrayRef<StringRef> Filenames)
263 : Name(Name), Filenames(Filenames.begin(), Filenames.end()) {}
265 void pushRegion(CounterMappingRegion Region, uint64_t Count) {
266 if (CountedRegions.empty())
267 ExecutionCount = Count;
268 CountedRegions.emplace_back(Region, Count);
272 /// \brief Iterator over Functions, optionally filtered to a single file.
273 class FunctionRecordIterator
274 : public iterator_facade_base<FunctionRecordIterator,
275 std::forward_iterator_tag, FunctionRecord> {
276 ArrayRef<FunctionRecord> Records;
277 ArrayRef<FunctionRecord>::iterator Current;
280 /// \brief Skip records whose primary file is not \c Filename.
281 void skipOtherFiles();
284 FunctionRecordIterator(ArrayRef<FunctionRecord> Records_,
285 StringRef Filename = "")
286 : Records(Records_), Current(Records.begin()), Filename(Filename) {
290 FunctionRecordIterator() : Current(Records.begin()) {}
292 bool operator==(const FunctionRecordIterator &RHS) const {
293 return Current == RHS.Current && Filename == RHS.Filename;
296 const FunctionRecord &operator*() const { return *Current; }
298 FunctionRecordIterator &operator++() {
299 assert(Current != Records.end() && "incremented past end");
306 /// \brief Coverage information for a macro expansion or #included file.
308 /// When covered code has pieces that can be expanded for more detail, such as a
309 /// preprocessor macro use and its definition, these are represented as
310 /// expansions whose coverage can be looked up independently.
311 struct ExpansionRecord {
312 /// \brief The abstract file this expansion covers.
314 /// \brief The region that expands to this record.
315 const CountedRegion &Region;
316 /// \brief Coverage for the expansion.
317 const FunctionRecord &Function;
319 ExpansionRecord(const CountedRegion &Region,
320 const FunctionRecord &Function)
321 : FileID(Region.ExpandedFileID), Region(Region), Function(Function) {}
324 /// \brief The execution count information starting at a point in a file.
326 /// A sequence of CoverageSegments gives execution counts for a file in format
327 /// that's simple to iterate through for processing.
328 struct CoverageSegment {
329 /// \brief The line where this segment begins.
331 /// \brief The column where this segment begins.
333 /// \brief The execution count, or zero if no count was recorded.
335 /// \brief When false, the segment was uninstrumented or skipped.
337 /// \brief Whether this enters a new region or returns to a previous count.
340 CoverageSegment(unsigned Line, unsigned Col, bool IsRegionEntry)
341 : Line(Line), Col(Col), Count(0), HasCount(false),
342 IsRegionEntry(IsRegionEntry) {}
344 CoverageSegment(unsigned Line, unsigned Col, uint64_t Count,
346 : Line(Line), Col(Col), Count(Count), HasCount(true),
347 IsRegionEntry(IsRegionEntry) {}
349 friend bool operator==(const CoverageSegment &L, const CoverageSegment &R) {
350 return std::tie(L.Line, L.Col, L.Count, L.HasCount, L.IsRegionEntry) ==
351 std::tie(R.Line, R.Col, R.Count, R.HasCount, R.IsRegionEntry);
354 void setCount(uint64_t NewCount) {
359 void addCount(uint64_t NewCount) { setCount(Count + NewCount); }
362 /// \brief Coverage information to be processed or displayed.
364 /// This represents the coverage of an entire file, expansion, or function. It
365 /// provides a sequence of CoverageSegments to iterate through, as well as the
366 /// list of expansions that can be further processed.
368 std::string Filename;
369 std::vector<CoverageSegment> Segments;
370 std::vector<ExpansionRecord> Expansions;
371 friend class CoverageMapping;
376 CoverageData(StringRef Filename) : Filename(Filename) {}
378 CoverageData(CoverageData &&RHS)
379 : Filename(std::move(RHS.Filename)), Segments(std::move(RHS.Segments)),
380 Expansions(std::move(RHS.Expansions)) {}
382 /// \brief Get the name of the file this data covers.
383 StringRef getFilename() { return Filename; }
385 std::vector<CoverageSegment>::iterator begin() { return Segments.begin(); }
386 std::vector<CoverageSegment>::iterator end() { return Segments.end(); }
387 bool empty() { return Segments.empty(); }
389 /// \brief Expansions that can be further processed.
390 std::vector<ExpansionRecord> getExpansions() { return Expansions; }
393 /// \brief The mapping of profile information to coverage data.
395 /// This is the main interface to get coverage information, using a profile to
396 /// fill out execution counts.
397 class CoverageMapping {
398 std::vector<FunctionRecord> Functions;
399 unsigned MismatchedFunctionCount;
401 CoverageMapping() : MismatchedFunctionCount(0) {}
404 /// \brief Load the coverage mapping using the given readers.
405 static ErrorOr<std::unique_ptr<CoverageMapping>>
406 load(CoverageMappingReader &CoverageReader,
407 IndexedInstrProfReader &ProfileReader);
409 /// \brief Load the coverage mapping from the given files.
410 static ErrorOr<std::unique_ptr<CoverageMapping>>
411 load(StringRef ObjectFilename, StringRef ProfileFilename,
412 StringRef Arch = StringRef());
414 /// \brief The number of functions that couldn't have their profiles mapped.
416 /// This is a count of functions whose profile is out of date or otherwise
417 /// can't be associated with any coverage information.
418 unsigned getMismatchedCount() { return MismatchedFunctionCount; }
420 /// \brief Returns the list of files that are covered.
421 std::vector<StringRef> getUniqueSourceFiles() const;
423 /// \brief Get the coverage for a particular file.
425 /// The given filename must be the name as recorded in the coverage
426 /// information. That is, only names returned from getUniqueSourceFiles will
428 CoverageData getCoverageForFile(StringRef Filename);
430 /// \brief Gets all of the functions covered by this profile.
431 iterator_range<FunctionRecordIterator> getCoveredFunctions() const {
432 return make_range(FunctionRecordIterator(Functions),
433 FunctionRecordIterator());
436 /// \brief Gets all of the functions in a particular file.
437 iterator_range<FunctionRecordIterator>
438 getCoveredFunctions(StringRef Filename) const {
439 return make_range(FunctionRecordIterator(Functions, Filename),
440 FunctionRecordIterator());
443 /// \brief Get the list of function instantiations in the file.
445 /// Functions that are instantiated more than once, such as C++ template
446 /// specializations, have distinct coverage records for each instantiation.
447 std::vector<const FunctionRecord *> getInstantiations(StringRef Filename);
449 /// \brief Get the coverage for a particular function.
450 CoverageData getCoverageForFunction(const FunctionRecord &Function);
452 /// \brief Get the coverage for an expansion within a coverage set.
453 CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion);
456 const std::error_category &coveragemap_category();
458 enum class coveragemap_error {
467 inline std::error_code make_error_code(coveragemap_error E) {
468 return std::error_code(static_cast<int>(E), coveragemap_category());
472 // Profile coverage map has the following layout:
473 // [CoverageMapFileHeader]
475 // [CovMapFunctionRecord]
476 // [CovMapFunctionRecord]
479 // [Encoded Region Mapping Data]
481 template <class IntPtrT> struct CovMapFunctionRecord {
482 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
483 #include "llvm/ProfileData/InstrProfData.inc"
485 // Per module coverage mapping data header, i.e. CoverageMapFileHeader
487 struct CovMapHeader {
488 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Type Name;
489 #include "llvm/ProfileData/InstrProfData.inc"
494 enum CoverageMappingVersion {
495 CoverageMappingVersion1 = 0,
496 // The current versin is Version1
497 CoverageMappingCurrentVersion = INSTR_PROF_COVMAP_VERSION
500 } // end namespace coverage
502 /// \brief Provide DenseMapInfo for CounterExpression
503 template<> struct DenseMapInfo<coverage::CounterExpression> {
504 static inline coverage::CounterExpression getEmptyKey() {
505 using namespace coverage;
506 return CounterExpression(CounterExpression::ExprKind::Subtract,
507 Counter::getCounter(~0U),
508 Counter::getCounter(~0U));
511 static inline coverage::CounterExpression getTombstoneKey() {
512 using namespace coverage;
513 return CounterExpression(CounterExpression::ExprKind::Add,
514 Counter::getCounter(~0U),
515 Counter::getCounter(~0U));
518 static unsigned getHashValue(const coverage::CounterExpression &V) {
519 return static_cast<unsigned>(
520 hash_combine(V.Kind, V.LHS.getKind(), V.LHS.getCounterID(),
521 V.RHS.getKind(), V.RHS.getCounterID()));
524 static bool isEqual(const coverage::CounterExpression &LHS,
525 const coverage::CounterExpression &RHS) {
526 return LHS.Kind == RHS.Kind && LHS.LHS == RHS.LHS && LHS.RHS == RHS.RHS;
530 } // end namespace llvm
534 struct is_error_code_enum<llvm::coverage::coveragemap_error> : std::true_type {};
538 #endif // LLVM_PROFILEDATA_COVERAGEMAPPING_H_