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/Support/ErrorOr.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <system_error>
24 class IndexedInstrProfReader;
27 class ObjectFileCoverageMappingReader;
29 class CoverageMapping;
30 struct CounterExpressions;
32 enum CoverageMappingVersion { CoverageMappingVersion1 };
34 /// \brief A Counter is an abstract value that describes how to compute the
35 /// execution count for a region of code using the collected profile count data.
37 enum CounterKind { Zero, CounterValueReference, Expression };
38 static const unsigned EncodingTagBits = 2;
39 static const unsigned EncodingTagMask = 0x3;
40 static const unsigned EncodingCounterTagAndExpansionRegionTagBits =
47 Counter(CounterKind Kind, unsigned ID) : Kind(Kind), ID(ID) {}
50 Counter() : Kind(Zero), ID(0) {}
52 CounterKind getKind() const { return Kind; }
54 bool isZero() const { return Kind == Zero; }
56 bool isExpression() const { return Kind == Expression; }
58 unsigned getCounterID() const { return ID; }
60 unsigned getExpressionID() const { return ID; }
62 bool operator==(const Counter &Other) const {
63 return Kind == Other.Kind && ID == Other.ID;
66 /// \brief Return the counter that represents the number zero.
67 static Counter getZero() { return Counter(); }
69 /// \brief Return the counter that corresponds to a specific profile counter.
70 static Counter getCounter(unsigned CounterId) {
71 return Counter(CounterValueReference, CounterId);
74 /// \brief Return the counter that corresponds to a specific
75 /// addition counter expression.
76 static Counter getExpression(unsigned ExpressionId) {
77 return Counter(Expression, ExpressionId);
81 /// \brief A Counter expression is a value that represents an arithmetic
82 /// operation with two counters.
83 struct CounterExpression {
84 enum ExprKind { Subtract, Add };
88 CounterExpression(ExprKind Kind, Counter LHS, Counter RHS)
89 : Kind(Kind), LHS(LHS), RHS(RHS) {}
91 bool operator==(const CounterExpression &Other) const {
92 return Kind == Other.Kind && LHS == Other.LHS && RHS == Other.RHS;
96 /// \brief A Counter expression builder is used to construct the
97 /// counter expressions. It avoids unecessary duplication
98 /// and simplifies algebraic expressions.
99 class CounterExpressionBuilder {
100 /// \brief A list of all the counter expressions
101 llvm::SmallVector<CounterExpression, 16> Expressions;
102 /// \brief An array of terms used in expression simplification.
103 llvm::SmallVector<int, 16> Terms;
105 /// \brief Return the counter which corresponds to the given expression.
107 /// If the given expression is already stored in the builder, a counter
108 /// that references that expression is returned. Otherwise, the given
109 /// expression is added to the builder's collection of expressions.
110 Counter get(const CounterExpression &E);
112 /// \brief Convert the expression tree represented by a counter
113 /// into a polynomial in the form of K1Counter1 + .. + KNCounterN
114 /// where K1 .. KN are integer constants that are stored in the Terms array.
115 void extractTerms(Counter C, int Sign = 1);
117 /// \brief Simplifies the given expression tree
118 /// by getting rid of algebraically redundant operations.
119 Counter simplify(Counter ExpressionTree);
122 CounterExpressionBuilder(unsigned NumCounterValues);
124 ArrayRef<CounterExpression> getExpressions() const { return Expressions; }
126 /// \brief Return a counter that represents the expression
127 /// that adds LHS and RHS.
128 Counter add(Counter LHS, Counter RHS);
130 /// \brief Return a counter that represents the expression
131 /// that subtracts RHS from LHS.
132 Counter subtract(Counter LHS, Counter RHS);
135 /// \brief A Counter mapping region associates a source range with
136 /// a specific counter.
137 struct CounterMappingRegion {
139 /// \brief A CodeRegion associates some code with a counter
142 /// \brief An ExpansionRegion represents a file expansion region that
143 /// associates a source range with the expansion of a virtual source file,
144 /// such as for a macro instantiation or #include file.
147 /// \brief A SkippedRegion represents a source range with code that
148 /// was skipped by a preprocessor or similar means.
152 static const unsigned EncodingHasCodeBeforeBits = 1;
155 unsigned FileID, ExpandedFileID;
156 unsigned LineStart, ColumnStart, LineEnd, ColumnEnd;
158 /// \brief A flag that is set to true when there is already code before
159 /// this region on the same line.
160 /// This is useful to accurately compute the execution counts for a line.
163 CounterMappingRegion(Counter Count, unsigned FileID, unsigned LineStart,
164 unsigned ColumnStart, unsigned LineEnd,
165 unsigned ColumnEnd, bool HasCodeBefore = false,
166 RegionKind Kind = CodeRegion)
167 : Count(Count), FileID(FileID), ExpandedFileID(0), LineStart(LineStart),
168 ColumnStart(ColumnStart), LineEnd(LineEnd), ColumnEnd(ColumnEnd),
169 Kind(Kind), HasCodeBefore(HasCodeBefore) {}
171 inline std::pair<unsigned, unsigned> startLoc() const {
172 return std::pair<unsigned, unsigned>(LineStart, ColumnStart);
175 inline std::pair<unsigned, unsigned> endLoc() const {
176 return std::pair<unsigned, unsigned>(LineEnd, ColumnEnd);
179 bool operator<(const CounterMappingRegion &Other) const {
180 if (FileID != Other.FileID)
181 return FileID < Other.FileID;
182 return startLoc() < Other.startLoc();
185 bool contains(const CounterMappingRegion &Other) const {
186 if (FileID != Other.FileID)
188 if (startLoc() > Other.startLoc())
190 if (endLoc() < Other.endLoc())
196 /// \brief Associates a source range with an execution count.
197 struct CountedRegion : public CounterMappingRegion {
198 uint64_t ExecutionCount;
200 CountedRegion(const CounterMappingRegion &R, uint64_t ExecutionCount)
201 : CounterMappingRegion(R), ExecutionCount(ExecutionCount) {}
204 /// \brief A Counter mapping context is used to connect the counters,
205 /// expressions and the obtained counter values.
206 class CounterMappingContext {
207 ArrayRef<CounterExpression> Expressions;
208 ArrayRef<uint64_t> CounterValues;
211 CounterMappingContext(ArrayRef<CounterExpression> Expressions,
212 ArrayRef<uint64_t> CounterValues = ArrayRef<uint64_t>())
213 : Expressions(Expressions), CounterValues(CounterValues) {}
215 void dump(const Counter &C, llvm::raw_ostream &OS) const;
216 void dump(const Counter &C) const { dump(C, llvm::outs()); }
218 /// \brief Return the number of times that a region of code associated with
219 /// this counter was executed.
220 ErrorOr<int64_t> evaluate(const Counter &C) const;
223 /// \brief Code coverage information for a single function.
224 struct FunctionRecord {
225 /// \brief Raw function name.
227 /// \brief Associated files.
228 std::vector<std::string> Filenames;
229 /// \brief Regions in the function along with their counts.
230 std::vector<CountedRegion> CountedRegions;
232 FunctionRecord(StringRef Name, ArrayRef<StringRef> Filenames)
233 : Name(Name), Filenames(Filenames.begin(), Filenames.end()) {}
236 /// \brief Coverage information for a macro expansion or #included file.
238 /// When covered code has pieces that can be expanded for more detail, such as a
239 /// preprocessor macro use and its definition, these are represented as
240 /// expansions whose coverage can be looked up independently.
241 struct ExpansionRecord {
242 /// \brief The abstract file this expansion covers.
244 /// \brief The region that expands to this record.
245 const CountedRegion &Region;
246 /// \brief Coverage for the expansion.
247 const FunctionRecord &Function;
249 ExpansionRecord(const CountedRegion &Region,
250 const FunctionRecord &Function)
251 : FileID(Region.ExpandedFileID), Region(Region), Function(Function) {}
254 /// \brief The execution count information starting at a point in a file.
256 /// A sequence of CoverageSegments gives execution counts for a file in format
257 /// that's simple to iterate through for processing.
258 struct CoverageSegment {
259 /// \brief The line where this segment begins.
261 /// \brief The column where this segment begins.
263 /// \brief The execution count, or zero if no count was recorded.
265 /// \brief When false, the segment was uninstrumented or skipped.
267 /// \brief Whether this enters a new region or returns to a previous count.
270 CoverageSegment(unsigned Line, unsigned Col, bool IsRegionEntry)
271 : Line(Line), Col(Col), Count(0), HasCount(false),
272 IsRegionEntry(IsRegionEntry) {}
273 void setCount(uint64_t NewCount) {
279 /// \brief Coverage information to be processed or displayed.
281 /// This represents the coverage of an entire file, expansion, or function. It
282 /// provides a sequence of CoverageSegments to iterate through, as well as the
283 /// list of expansions that can be further processed.
285 std::string Filename;
286 std::vector<CoverageSegment> Segments;
287 std::vector<ExpansionRecord> Expansions;
288 friend class CoverageMapping;
293 CoverageData(StringRef Filename) : Filename(Filename) {}
295 CoverageData(CoverageData &&RHS)
296 : Filename(std::move(RHS.Filename)), Segments(std::move(RHS.Segments)),
297 Expansions(std::move(RHS.Expansions)) {}
299 /// \brief Get the name of the file this data covers.
300 StringRef getFilename() { return Filename; }
302 std::vector<CoverageSegment>::iterator begin() { return Segments.begin(); }
303 std::vector<CoverageSegment>::iterator end() { return Segments.end(); }
304 bool empty() { return Segments.empty(); }
306 /// \brief Expansions that can be further processed.
307 std::vector<ExpansionRecord> getExpansions() { return Expansions; }
310 /// \brief The mapping of profile information to coverage data.
312 /// This is the main interface to get coverage information, using a profile to
313 /// fill out execution counts.
314 class CoverageMapping {
315 std::vector<FunctionRecord> Functions;
316 unsigned MismatchedFunctionCount;
318 CoverageMapping() : MismatchedFunctionCount(0) {}
321 /// Load the coverage mapping using the given readers.
322 static ErrorOr<std::unique_ptr<CoverageMapping>>
323 load(ObjectFileCoverageMappingReader &CoverageReader,
324 IndexedInstrProfReader &ProfileReader);
326 /// \brief The number of functions that couldn't have their profiles mapped.
328 /// This is a count of functions whose profile is out of date or otherwise
329 /// can't be associated with any coverage information.
330 unsigned getMismatchedCount() { return MismatchedFunctionCount; }
332 /// \brief Returns the list of files that are covered.
333 std::vector<StringRef> getUniqueSourceFiles();
335 /// \brief Get the coverage for a particular file.
337 /// The given filename must be the name as recorded in the coverage
338 /// information. That is, only names returned from getUniqueSourceFiles will
340 CoverageData getCoverageForFile(StringRef Filename);
342 /// \brief Gets all of the functions covered by this profile.
343 ArrayRef<FunctionRecord> getCoveredFunctions() {
344 return ArrayRef<FunctionRecord>(Functions.data(), Functions.size());
347 /// \brief Get the list of function instantiations in the file.
349 /// Fucntions that are instantiated more than once, such as C++ template
350 /// specializations, have distinct coverage records for each instantiation.
351 std::vector<const FunctionRecord *> getInstantiations(StringRef Filename);
353 /// \brief Get the coverage for a particular function.
354 CoverageData getCoverageForFunction(const FunctionRecord &Function);
356 /// \brief Get the coverage for an expansion within a coverage set.
357 CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion);
360 } // end namespace coverage
361 } // end namespace llvm
363 #endif // LLVM_PROFILEDATA_COVERAGEMAPPING_H_