InstrProf: Add operator!= to coverage counters
[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/ADT/DenseMap.h"
20 #include "llvm/ADT/Hashing.h"
21 #include "llvm/ADT/iterator.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorOr.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <system_error>
26
27 namespace llvm {
28 class IndexedInstrProfReader;
29 namespace coverage {
30
31 class ObjectFileCoverageMappingReader;
32
33 class CoverageMapping;
34 struct CounterExpressions;
35
36 enum CoverageMappingVersion { CoverageMappingVersion1 };
37
38 /// \brief A Counter is an abstract value that describes how to compute the
39 /// execution count for a region of code using the collected profile count data.
40 struct Counter {
41   enum CounterKind { Zero, CounterValueReference, Expression };
42   static const unsigned EncodingTagBits = 2;
43   static const unsigned EncodingTagMask = 0x3;
44   static const unsigned EncodingCounterTagAndExpansionRegionTagBits =
45       EncodingTagBits + 1;
46
47 private:
48   CounterKind Kind;
49   unsigned ID;
50
51   Counter(CounterKind Kind, unsigned ID) : Kind(Kind), ID(ID) {}
52
53 public:
54   Counter() : Kind(Zero), ID(0) {}
55
56   CounterKind getKind() const { return Kind; }
57
58   bool isZero() const { return Kind == Zero; }
59
60   bool isExpression() const { return Kind == Expression; }
61
62   unsigned getCounterID() const { return ID; }
63
64   unsigned getExpressionID() const { return ID; }
65
66   friend bool operator==(const Counter &LHS, const Counter &RHS) {
67     return LHS.Kind == RHS.Kind && LHS.ID == RHS.ID;
68   }
69
70   friend bool operator!=(const Counter &LHS, const Counter &RHS) {
71     return !(LHS == RHS);
72   }
73
74   friend bool operator<(const Counter &LHS, const Counter &RHS) {
75     return std::tie(LHS.Kind, LHS.ID) < std::tie(RHS.Kind, RHS.ID);
76   }
77
78   /// \brief Return the counter that represents the number zero.
79   static Counter getZero() { return Counter(); }
80
81   /// \brief Return the counter that corresponds to a specific profile counter.
82   static Counter getCounter(unsigned CounterId) {
83     return Counter(CounterValueReference, CounterId);
84   }
85
86   /// \brief Return the counter that corresponds to a specific
87   /// addition counter expression.
88   static Counter getExpression(unsigned ExpressionId) {
89     return Counter(Expression, ExpressionId);
90   }
91 };
92
93 /// \brief A Counter expression is a value that represents an arithmetic
94 /// operation with two counters.
95 struct CounterExpression {
96   enum ExprKind { Subtract, Add };
97   ExprKind Kind;
98   Counter LHS, RHS;
99
100   CounterExpression(ExprKind Kind, Counter LHS, Counter RHS)
101       : Kind(Kind), LHS(LHS), RHS(RHS) {}
102 };
103
104 /// \brief A Counter expression builder is used to construct the
105 /// counter expressions. It avoids unecessary duplication
106 /// and simplifies algebraic expressions.
107 class CounterExpressionBuilder {
108   /// \brief A list of all the counter expressions
109   std::vector<CounterExpression> Expressions;
110   /// \brief A lookup table for the index of a given expression.
111   llvm::DenseMap<CounterExpression, unsigned> ExpressionIndices;
112
113   /// \brief Return the counter which corresponds to the given expression.
114   ///
115   /// If the given expression is already stored in the builder, a counter
116   /// that references that expression is returned. Otherwise, the given
117   /// expression is added to the builder's collection of expressions.
118   Counter get(const CounterExpression &E);
119
120   /// \brief Gather the terms of the expression tree for processing.
121   ///
122   /// This collects each addition and subtraction referenced by the counter into
123   /// a sequence that can be sorted and combined to build a simplified counter
124   /// expression.
125   void extractTerms(Counter C, int Sign,
126                     SmallVectorImpl<std::pair<unsigned, int>> &Terms);
127
128   /// \brief Simplifies the given expression tree
129   /// by getting rid of algebraically redundant operations.
130   Counter simplify(Counter ExpressionTree);
131
132 public:
133   ArrayRef<CounterExpression> getExpressions() const { return Expressions; }
134
135   /// \brief Return a counter that represents the expression
136   /// that adds LHS and RHS.
137   Counter add(Counter LHS, Counter RHS);
138
139   /// \brief Return a counter that represents the expression
140   /// that subtracts RHS from LHS.
141   Counter subtract(Counter LHS, Counter RHS);
142 };
143
144 /// \brief A Counter mapping region associates a source range with
145 /// a specific counter.
146 struct CounterMappingRegion {
147   enum RegionKind {
148     /// \brief A CodeRegion associates some code with a counter
149     CodeRegion,
150
151     /// \brief An ExpansionRegion represents a file expansion region that
152     /// associates a source range with the expansion of a virtual source file,
153     /// such as for a macro instantiation or #include file.
154     ExpansionRegion,
155
156     /// \brief A SkippedRegion represents a source range with code that
157     /// was skipped by a preprocessor or similar means.
158     SkippedRegion
159   };
160
161   static const unsigned EncodingHasCodeBeforeBits = 1;
162
163   Counter Count;
164   unsigned FileID, ExpandedFileID;
165   unsigned LineStart, ColumnStart, LineEnd, ColumnEnd;
166   RegionKind Kind;
167   /// \brief A flag that is set to true when there is already code before
168   /// this region on the same line.
169   /// This is useful to accurately compute the execution counts for a line.
170   bool HasCodeBefore;
171
172   CounterMappingRegion(Counter Count, unsigned FileID, unsigned LineStart,
173                        unsigned ColumnStart, unsigned LineEnd,
174                        unsigned ColumnEnd, bool HasCodeBefore = false,
175                        RegionKind Kind = CodeRegion)
176       : Count(Count), FileID(FileID), ExpandedFileID(0), LineStart(LineStart),
177         ColumnStart(ColumnStart), LineEnd(LineEnd), ColumnEnd(ColumnEnd),
178         Kind(Kind), HasCodeBefore(HasCodeBefore) {}
179
180   inline std::pair<unsigned, unsigned> startLoc() const {
181     return std::pair<unsigned, unsigned>(LineStart, ColumnStart);
182   }
183
184   inline std::pair<unsigned, unsigned> endLoc() const {
185     return std::pair<unsigned, unsigned>(LineEnd, ColumnEnd);
186   }
187
188   bool operator<(const CounterMappingRegion &Other) const {
189     if (FileID != Other.FileID)
190       return FileID < Other.FileID;
191     return startLoc() < Other.startLoc();
192   }
193
194   bool contains(const CounterMappingRegion &Other) const {
195     if (FileID != Other.FileID)
196       return false;
197     if (startLoc() > Other.startLoc())
198       return false;
199     if (endLoc() < Other.endLoc())
200       return false;
201     return true;
202   }
203 };
204
205 /// \brief Associates a source range with an execution count.
206 struct CountedRegion : public CounterMappingRegion {
207   uint64_t ExecutionCount;
208
209   CountedRegion(const CounterMappingRegion &R, uint64_t ExecutionCount)
210       : CounterMappingRegion(R), ExecutionCount(ExecutionCount) {}
211 };
212
213 /// \brief A Counter mapping context is used to connect the counters,
214 /// expressions and the obtained counter values.
215 class CounterMappingContext {
216   ArrayRef<CounterExpression> Expressions;
217   ArrayRef<uint64_t> CounterValues;
218
219 public:
220   CounterMappingContext(ArrayRef<CounterExpression> Expressions,
221                         ArrayRef<uint64_t> CounterValues = ArrayRef<uint64_t>())
222       : Expressions(Expressions), CounterValues(CounterValues) {}
223
224   void dump(const Counter &C, llvm::raw_ostream &OS) const;
225   void dump(const Counter &C) const { dump(C, dbgs()); }
226
227   /// \brief Return the number of times that a region of code associated with
228   /// this counter was executed.
229   ErrorOr<int64_t> evaluate(const Counter &C) const;
230 };
231
232 /// \brief Code coverage information for a single function.
233 struct FunctionRecord {
234   /// \brief Raw function name.
235   std::string Name;
236   /// \brief Associated files.
237   std::vector<std::string> Filenames;
238   /// \brief Regions in the function along with their counts.
239   std::vector<CountedRegion> CountedRegions;
240   /// \brief The number of times this function was executed.
241   uint64_t ExecutionCount;
242
243   FunctionRecord(StringRef Name, ArrayRef<StringRef> Filenames,
244                  uint64_t ExecutionCount)
245       : Name(Name), Filenames(Filenames.begin(), Filenames.end()),
246         ExecutionCount(ExecutionCount) {}
247 };
248
249 /// \brief Iterator over Functions, optionally filtered to a single file.
250 class FunctionRecordIterator
251     : public iterator_facade_base<FunctionRecordIterator,
252                                   std::forward_iterator_tag, FunctionRecord> {
253   ArrayRef<FunctionRecord> Records;
254   ArrayRef<FunctionRecord>::iterator Current;
255   StringRef Filename;
256
257   /// \brief Skip records whose primary file is not \c Filename.
258   void skipOtherFiles();
259
260 public:
261   FunctionRecordIterator(ArrayRef<FunctionRecord> Records_,
262                          StringRef Filename = "")
263       : Records(Records_), Current(Records.begin()), Filename(Filename) {
264     skipOtherFiles();
265   }
266
267   FunctionRecordIterator() : Current(Records.begin()) {}
268
269   bool operator==(const FunctionRecordIterator &RHS) const {
270     return Current == RHS.Current && Filename == RHS.Filename;
271   }
272
273   const FunctionRecord &operator*() const { return *Current; }
274
275   FunctionRecordIterator &operator++() {
276     assert(Current != Records.end() && "incremented past end");
277     ++Current;
278     skipOtherFiles();
279     return *this;
280   }
281 };
282
283 /// \brief Coverage information for a macro expansion or #included file.
284 ///
285 /// When covered code has pieces that can be expanded for more detail, such as a
286 /// preprocessor macro use and its definition, these are represented as
287 /// expansions whose coverage can be looked up independently.
288 struct ExpansionRecord {
289   /// \brief The abstract file this expansion covers.
290   unsigned FileID;
291   /// \brief The region that expands to this record.
292   const CountedRegion &Region;
293   /// \brief Coverage for the expansion.
294   const FunctionRecord &Function;
295
296   ExpansionRecord(const CountedRegion &Region,
297                   const FunctionRecord &Function)
298       : FileID(Region.ExpandedFileID), Region(Region), Function(Function) {}
299 };
300
301 /// \brief The execution count information starting at a point in a file.
302 ///
303 /// A sequence of CoverageSegments gives execution counts for a file in format
304 /// that's simple to iterate through for processing.
305 struct CoverageSegment {
306   /// \brief The line where this segment begins.
307   unsigned Line;
308   /// \brief The column where this segment begins.
309   unsigned Col;
310   /// \brief The execution count, or zero if no count was recorded.
311   uint64_t Count;
312   /// \brief When false, the segment was uninstrumented or skipped.
313   bool HasCount;
314   /// \brief Whether this enters a new region or returns to a previous count.
315   bool IsRegionEntry;
316
317   CoverageSegment(unsigned Line, unsigned Col, bool IsRegionEntry)
318       : Line(Line), Col(Col), Count(0), HasCount(false),
319         IsRegionEntry(IsRegionEntry) {}
320   void setCount(uint64_t NewCount) {
321     Count = NewCount;
322     HasCount = true;
323   }
324   void addCount(uint64_t NewCount) { setCount(Count + NewCount); }
325 };
326
327 /// \brief Coverage information to be processed or displayed.
328 ///
329 /// This represents the coverage of an entire file, expansion, or function. It
330 /// provides a sequence of CoverageSegments to iterate through, as well as the
331 /// list of expansions that can be further processed.
332 class CoverageData {
333   std::string Filename;
334   std::vector<CoverageSegment> Segments;
335   std::vector<ExpansionRecord> Expansions;
336   friend class CoverageMapping;
337
338 public:
339   CoverageData() {}
340
341   CoverageData(StringRef Filename) : Filename(Filename) {}
342
343   CoverageData(CoverageData &&RHS)
344       : Filename(std::move(RHS.Filename)), Segments(std::move(RHS.Segments)),
345         Expansions(std::move(RHS.Expansions)) {}
346
347   /// \brief Get the name of the file this data covers.
348   StringRef getFilename() { return Filename; }
349
350   std::vector<CoverageSegment>::iterator begin() { return Segments.begin(); }
351   std::vector<CoverageSegment>::iterator end() { return Segments.end(); }
352   bool empty() { return Segments.empty(); }
353
354   /// \brief Expansions that can be further processed.
355   std::vector<ExpansionRecord> getExpansions() { return Expansions; }
356 };
357
358 /// \brief The mapping of profile information to coverage data.
359 ///
360 /// This is the main interface to get coverage information, using a profile to
361 /// fill out execution counts.
362 class CoverageMapping {
363   std::vector<FunctionRecord> Functions;
364   unsigned MismatchedFunctionCount;
365
366   CoverageMapping() : MismatchedFunctionCount(0) {}
367
368 public:
369   /// \brief Load the coverage mapping using the given readers.
370   static ErrorOr<std::unique_ptr<CoverageMapping>>
371   load(ObjectFileCoverageMappingReader &CoverageReader,
372        IndexedInstrProfReader &ProfileReader);
373
374   /// \brief Load the coverage mapping from the given files.
375   static ErrorOr<std::unique_ptr<CoverageMapping>>
376   load(StringRef ObjectFilename, StringRef ProfileFilename);
377
378   /// \brief The number of functions that couldn't have their profiles mapped.
379   ///
380   /// This is a count of functions whose profile is out of date or otherwise
381   /// can't be associated with any coverage information.
382   unsigned getMismatchedCount() { return MismatchedFunctionCount; }
383
384   /// \brief Returns the list of files that are covered.
385   std::vector<StringRef> getUniqueSourceFiles() const;
386
387   /// \brief Get the coverage for a particular file.
388   ///
389   /// The given filename must be the name as recorded in the coverage
390   /// information. That is, only names returned from getUniqueSourceFiles will
391   /// yield a result.
392   CoverageData getCoverageForFile(StringRef Filename);
393
394   /// \brief Gets all of the functions covered by this profile.
395   iterator_range<FunctionRecordIterator> getCoveredFunctions() const {
396     return make_range(FunctionRecordIterator(Functions),
397                       FunctionRecordIterator());
398   }
399
400   /// \brief Gets all of the functions in a particular file.
401   iterator_range<FunctionRecordIterator>
402   getCoveredFunctions(StringRef Filename) const {
403     return make_range(FunctionRecordIterator(Functions, Filename),
404                       FunctionRecordIterator());
405   }
406
407   /// \brief Get the list of function instantiations in the file.
408   ///
409   /// Fucntions that are instantiated more than once, such as C++ template
410   /// specializations, have distinct coverage records for each instantiation.
411   std::vector<const FunctionRecord *> getInstantiations(StringRef Filename);
412
413   /// \brief Get the coverage for a particular function.
414   CoverageData getCoverageForFunction(const FunctionRecord &Function);
415
416   /// \brief Get the coverage for an expansion within a coverage set.
417   CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion);
418 };
419
420 } // end namespace coverage
421
422 /// \brief Provide DenseMapInfo for CounterExpression
423 template<> struct DenseMapInfo<coverage::CounterExpression> {
424   static inline coverage::CounterExpression getEmptyKey() {
425     using namespace coverage;
426     return CounterExpression(CounterExpression::ExprKind::Subtract,
427                              Counter::getCounter(~0U),
428                              Counter::getCounter(~0U));
429   }
430
431   static inline coverage::CounterExpression getTombstoneKey() {
432     using namespace coverage;
433     return CounterExpression(CounterExpression::ExprKind::Add,
434                              Counter::getCounter(~0U),
435                              Counter::getCounter(~0U));
436   }
437
438   static unsigned getHashValue(const coverage::CounterExpression &V) {
439     return static_cast<unsigned>(
440         hash_combine(V.Kind, V.LHS.getKind(), V.LHS.getCounterID(),
441                      V.RHS.getKind(), V.RHS.getCounterID()));
442   }
443
444   static bool isEqual(const coverage::CounterExpression &LHS,
445                       const coverage::CounterExpression &RHS) {
446     return LHS.Kind == RHS.Kind && LHS.LHS == RHS.LHS && LHS.RHS == RHS.RHS;
447   }
448 };
449
450
451 } // end namespace llvm
452
453 #endif // LLVM_PROFILEDATA_COVERAGEMAPPING_H_