llvm-cov: Disentangle the coverage data logic from the display (NFC)
[oota-llvm.git] / include / llvm / ProfileData / CoverageMapping.h
1 //=-- CoverageMapping.h - Code coverage mapping support ---------*- C++ -*-=//
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 // Code coverage mapping data is generated by clang and read by
11 // llvm-cov to show code coverage statistics for a file.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_PROFILEDATA_COVERAGEMAPPING_H_
16 #define LLVM_PROFILEDATA_COVERAGEMAPPING_H_
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/Support/ErrorOr.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <system_error>
22
23 namespace llvm {
24 class IndexedInstrProfReader;
25 namespace coverage {
26
27 class ObjectFileCoverageMappingReader;
28
29 class CoverageMapping;
30 struct CounterExpressions;
31
32 enum CoverageMappingVersion { CoverageMappingVersion1 };
33
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.
36 struct Counter {
37   enum CounterKind { Zero, CounterValueReference, Expression };
38   static const unsigned EncodingTagBits = 2;
39   static const unsigned EncodingTagMask = 0x3;
40   static const unsigned EncodingCounterTagAndExpansionRegionTagBits =
41       EncodingTagBits + 1;
42
43 private:
44   CounterKind Kind;
45   unsigned ID;
46
47   Counter(CounterKind Kind, unsigned ID) : Kind(Kind), ID(ID) {}
48
49 public:
50   Counter() : Kind(Zero), ID(0) {}
51
52   CounterKind getKind() const { return Kind; }
53
54   bool isZero() const { return Kind == Zero; }
55
56   bool isExpression() const { return Kind == Expression; }
57
58   unsigned getCounterID() const { return ID; }
59
60   unsigned getExpressionID() const { return ID; }
61
62   bool operator==(const Counter &Other) const {
63     return Kind == Other.Kind && ID == Other.ID;
64   }
65
66   /// \brief Return the counter that represents the number zero.
67   static Counter getZero() { return Counter(); }
68
69   /// \brief Return the counter that corresponds to a specific profile counter.
70   static Counter getCounter(unsigned CounterId) {
71     return Counter(CounterValueReference, CounterId);
72   }
73
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);
78   }
79 };
80
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 };
85   ExprKind Kind;
86   Counter LHS, RHS;
87
88   CounterExpression(ExprKind Kind, Counter LHS, Counter RHS)
89       : Kind(Kind), LHS(LHS), RHS(RHS) {}
90
91   bool operator==(const CounterExpression &Other) const {
92     return Kind == Other.Kind && LHS == Other.LHS && RHS == Other.RHS;
93   }
94 };
95
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;
104
105   /// \brief Return the counter which corresponds to the given expression.
106   ///
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);
111
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);
116
117   /// \brief Simplifies the given expression tree
118   /// by getting rid of algebraically redundant operations.
119   Counter simplify(Counter ExpressionTree);
120
121 public:
122   CounterExpressionBuilder(unsigned NumCounterValues);
123
124   ArrayRef<CounterExpression> getExpressions() const { return Expressions; }
125
126   /// \brief Return a counter that represents the expression
127   /// that adds LHS and RHS.
128   Counter add(Counter LHS, Counter RHS);
129
130   /// \brief Return a counter that represents the expression
131   /// that subtracts RHS from LHS.
132   Counter subtract(Counter LHS, Counter RHS);
133 };
134
135 /// \brief A Counter mapping region associates a source range with
136 /// a specific counter.
137 struct CounterMappingRegion {
138   enum RegionKind {
139     /// \brief A CodeRegion associates some code with a counter
140     CodeRegion,
141
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.
145     ExpansionRegion,
146
147     /// \brief A SkippedRegion represents a source range with code that
148     /// was skipped by a preprocessor or similar means.
149     SkippedRegion
150   };
151
152   static const unsigned EncodingHasCodeBeforeBits = 1;
153
154   Counter Count;
155   unsigned FileID, ExpandedFileID;
156   unsigned LineStart, ColumnStart, LineEnd, ColumnEnd;
157   RegionKind Kind;
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.
161   bool HasCodeBefore;
162
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) {}
170
171   inline std::pair<unsigned, unsigned> startLoc() const {
172     return std::pair<unsigned, unsigned>(LineStart, ColumnStart);
173   }
174
175   inline std::pair<unsigned, unsigned> endLoc() const {
176     return std::pair<unsigned, unsigned>(LineEnd, ColumnEnd);
177   }
178
179   bool operator<(const CounterMappingRegion &Other) const {
180     if (FileID != Other.FileID)
181       return FileID < Other.FileID;
182     return startLoc() < Other.startLoc();
183   }
184
185   bool contains(const CounterMappingRegion &Other) const {
186     if (FileID != Other.FileID)
187       return false;
188     if (startLoc() > Other.startLoc())
189       return false;
190     if (endLoc() < Other.endLoc())
191       return false;
192     return true;
193   }
194 };
195
196 /// \brief Associates a source range with an execution count.
197 struct CountedRegion : public CounterMappingRegion {
198   uint64_t ExecutionCount;
199
200   CountedRegion(const CounterMappingRegion &R, uint64_t ExecutionCount)
201       : CounterMappingRegion(R), ExecutionCount(ExecutionCount) {}
202 };
203
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;
209
210 public:
211   CounterMappingContext(ArrayRef<CounterExpression> Expressions,
212                         ArrayRef<uint64_t> CounterValues = ArrayRef<uint64_t>())
213       : Expressions(Expressions), CounterValues(CounterValues) {}
214
215   void dump(const Counter &C, llvm::raw_ostream &OS) const;
216   void dump(const Counter &C) const { dump(C, llvm::outs()); }
217
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;
221 };
222
223 /// \brief Code coverage information for a single function.
224 struct FunctionRecord {
225   /// \brief Raw function name.
226   std::string 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;
231
232   FunctionRecord(StringRef Name, ArrayRef<StringRef> Filenames)
233       : Name(Name), Filenames(Filenames.begin(), Filenames.end()) {}
234 };
235
236 /// \brief Coverage information for a macro expansion or #included file.
237 ///
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.
243   unsigned FileID;
244   /// \brief The region that expands to this record.
245   const CountedRegion &Region;
246   /// \brief Coverage for the expansion.
247   const FunctionRecord &Function;
248
249   ExpansionRecord(const CountedRegion &Region,
250                   const FunctionRecord &Function)
251       : FileID(Region.ExpandedFileID), Region(Region), Function(Function) {}
252 };
253
254 /// \brief The execution count information starting at a point in a file.
255 ///
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.
260   unsigned Line;
261   /// \brief The column where this segment begins.
262   unsigned Col;
263   /// \brief The execution count, or zero if no count was recorded.
264   uint64_t Count;
265   /// \brief When false, the segment was uninstrumented or skipped.
266   bool HasCount;
267   /// \brief Whether this enters a new region or returns to a previous count.
268   bool IsRegionEntry;
269
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) {
274     Count = NewCount;
275     HasCount = true;
276   }
277 };
278
279 /// \brief Coverage information to be processed or displayed.
280 ///
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.
284 class CoverageData {
285   std::string Filename;
286   std::vector<CoverageSegment> Segments;
287   std::vector<ExpansionRecord> Expansions;
288   friend class CoverageMapping;
289
290 public:
291   CoverageData() {}
292
293   CoverageData(StringRef Filename) : Filename(Filename) {}
294
295   CoverageData(CoverageData &&RHS)
296       : Filename(std::move(RHS.Filename)), Segments(std::move(RHS.Segments)),
297         Expansions(std::move(RHS.Expansions)) {}
298
299   /// \brief Get the name of the file this data covers.
300   StringRef getFilename() { return Filename; }
301
302   std::vector<CoverageSegment>::iterator begin() { return Segments.begin(); }
303   std::vector<CoverageSegment>::iterator end() { return Segments.end(); }
304   bool empty() { return Segments.empty(); }
305
306   /// \brief Expansions that can be further processed.
307   std::vector<ExpansionRecord> getExpansions() { return Expansions; }
308 };
309
310 /// \brief The mapping of profile information to coverage data.
311 ///
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;
317
318   CoverageMapping() : MismatchedFunctionCount(0) {}
319
320 public:
321   /// Load the coverage mapping using the given readers.
322   static ErrorOr<std::unique_ptr<CoverageMapping>>
323   load(ObjectFileCoverageMappingReader &CoverageReader,
324        IndexedInstrProfReader &ProfileReader);
325
326   /// \brief The number of functions that couldn't have their profiles mapped.
327   ///
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; }
331
332   /// \brief Returns the list of files that are covered.
333   std::vector<StringRef> getUniqueSourceFiles();
334
335   /// \brief Get the coverage for a particular file.
336   ///
337   /// The given filename must be the name as recorded in the coverage
338   /// information. That is, only names returned from getUniqueSourceFiles will
339   /// yield a result.
340   CoverageData getCoverageForFile(StringRef Filename);
341
342   /// \brief Gets all of the functions covered by this profile.
343   ArrayRef<FunctionRecord> getCoveredFunctions() {
344     return ArrayRef<FunctionRecord>(Functions.data(), Functions.size());
345   }
346
347   /// \brief Get the list of function instantiations in the file.
348   ///
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);
352
353   /// \brief Get the coverage for a particular function.
354   CoverageData getCoverageForFunction(const FunctionRecord &Function);
355
356   /// \brief Get the coverage for an expansion within a coverage set.
357   CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion);
358 };
359
360 } // end namespace coverage
361 } // end namespace llvm
362
363 #endif // LLVM_PROFILEDATA_COVERAGEMAPPING_H_