InstrProf: Remove CoverageMapping::HasCodeBefore, it isn't used
[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   Counter Count;
162   unsigned FileID, ExpandedFileID;
163   unsigned LineStart, ColumnStart, LineEnd, ColumnEnd;
164   RegionKind Kind;
165
166   CounterMappingRegion(Counter Count, unsigned FileID, unsigned LineStart,
167                        unsigned ColumnStart, unsigned LineEnd,
168                        unsigned ColumnEnd, RegionKind Kind = CodeRegion)
169       : Count(Count), FileID(FileID), ExpandedFileID(0), LineStart(LineStart),
170         ColumnStart(ColumnStart), LineEnd(LineEnd), ColumnEnd(ColumnEnd),
171         Kind(Kind) {}
172
173   inline std::pair<unsigned, unsigned> startLoc() const {
174     return std::pair<unsigned, unsigned>(LineStart, ColumnStart);
175   }
176
177   inline std::pair<unsigned, unsigned> endLoc() const {
178     return std::pair<unsigned, unsigned>(LineEnd, ColumnEnd);
179   }
180
181   bool operator<(const CounterMappingRegion &Other) const {
182     if (FileID != Other.FileID)
183       return FileID < Other.FileID;
184     return startLoc() < Other.startLoc();
185   }
186
187   bool contains(const CounterMappingRegion &Other) const {
188     if (FileID != Other.FileID)
189       return false;
190     if (startLoc() > Other.startLoc())
191       return false;
192     if (endLoc() < Other.endLoc())
193       return false;
194     return true;
195   }
196 };
197
198 /// \brief Associates a source range with an execution count.
199 struct CountedRegion : public CounterMappingRegion {
200   uint64_t ExecutionCount;
201
202   CountedRegion(const CounterMappingRegion &R, uint64_t ExecutionCount)
203       : CounterMappingRegion(R), ExecutionCount(ExecutionCount) {}
204 };
205
206 /// \brief A Counter mapping context is used to connect the counters,
207 /// expressions and the obtained counter values.
208 class CounterMappingContext {
209   ArrayRef<CounterExpression> Expressions;
210   ArrayRef<uint64_t> CounterValues;
211
212 public:
213   CounterMappingContext(ArrayRef<CounterExpression> Expressions,
214                         ArrayRef<uint64_t> CounterValues = ArrayRef<uint64_t>())
215       : Expressions(Expressions), CounterValues(CounterValues) {}
216
217   void dump(const Counter &C, llvm::raw_ostream &OS) const;
218   void dump(const Counter &C) const { dump(C, dbgs()); }
219
220   /// \brief Return the number of times that a region of code associated with
221   /// this counter was executed.
222   ErrorOr<int64_t> evaluate(const Counter &C) const;
223 };
224
225 /// \brief Code coverage information for a single function.
226 struct FunctionRecord {
227   /// \brief Raw function name.
228   std::string Name;
229   /// \brief Associated files.
230   std::vector<std::string> Filenames;
231   /// \brief Regions in the function along with their counts.
232   std::vector<CountedRegion> CountedRegions;
233   /// \brief The number of times this function was executed.
234   uint64_t ExecutionCount;
235
236   FunctionRecord(StringRef Name, ArrayRef<StringRef> Filenames,
237                  uint64_t ExecutionCount)
238       : Name(Name), Filenames(Filenames.begin(), Filenames.end()),
239         ExecutionCount(ExecutionCount) {}
240 };
241
242 /// \brief Iterator over Functions, optionally filtered to a single file.
243 class FunctionRecordIterator
244     : public iterator_facade_base<FunctionRecordIterator,
245                                   std::forward_iterator_tag, FunctionRecord> {
246   ArrayRef<FunctionRecord> Records;
247   ArrayRef<FunctionRecord>::iterator Current;
248   StringRef Filename;
249
250   /// \brief Skip records whose primary file is not \c Filename.
251   void skipOtherFiles();
252
253 public:
254   FunctionRecordIterator(ArrayRef<FunctionRecord> Records_,
255                          StringRef Filename = "")
256       : Records(Records_), Current(Records.begin()), Filename(Filename) {
257     skipOtherFiles();
258   }
259
260   FunctionRecordIterator() : Current(Records.begin()) {}
261
262   bool operator==(const FunctionRecordIterator &RHS) const {
263     return Current == RHS.Current && Filename == RHS.Filename;
264   }
265
266   const FunctionRecord &operator*() const { return *Current; }
267
268   FunctionRecordIterator &operator++() {
269     assert(Current != Records.end() && "incremented past end");
270     ++Current;
271     skipOtherFiles();
272     return *this;
273   }
274 };
275
276 /// \brief Coverage information for a macro expansion or #included file.
277 ///
278 /// When covered code has pieces that can be expanded for more detail, such as a
279 /// preprocessor macro use and its definition, these are represented as
280 /// expansions whose coverage can be looked up independently.
281 struct ExpansionRecord {
282   /// \brief The abstract file this expansion covers.
283   unsigned FileID;
284   /// \brief The region that expands to this record.
285   const CountedRegion &Region;
286   /// \brief Coverage for the expansion.
287   const FunctionRecord &Function;
288
289   ExpansionRecord(const CountedRegion &Region,
290                   const FunctionRecord &Function)
291       : FileID(Region.ExpandedFileID), Region(Region), Function(Function) {}
292 };
293
294 /// \brief The execution count information starting at a point in a file.
295 ///
296 /// A sequence of CoverageSegments gives execution counts for a file in format
297 /// that's simple to iterate through for processing.
298 struct CoverageSegment {
299   /// \brief The line where this segment begins.
300   unsigned Line;
301   /// \brief The column where this segment begins.
302   unsigned Col;
303   /// \brief The execution count, or zero if no count was recorded.
304   uint64_t Count;
305   /// \brief When false, the segment was uninstrumented or skipped.
306   bool HasCount;
307   /// \brief Whether this enters a new region or returns to a previous count.
308   bool IsRegionEntry;
309
310   CoverageSegment(unsigned Line, unsigned Col, bool IsRegionEntry)
311       : Line(Line), Col(Col), Count(0), HasCount(false),
312         IsRegionEntry(IsRegionEntry) {}
313   void setCount(uint64_t NewCount) {
314     Count = NewCount;
315     HasCount = true;
316   }
317   void addCount(uint64_t NewCount) { setCount(Count + NewCount); }
318 };
319
320 /// \brief Coverage information to be processed or displayed.
321 ///
322 /// This represents the coverage of an entire file, expansion, or function. It
323 /// provides a sequence of CoverageSegments to iterate through, as well as the
324 /// list of expansions that can be further processed.
325 class CoverageData {
326   std::string Filename;
327   std::vector<CoverageSegment> Segments;
328   std::vector<ExpansionRecord> Expansions;
329   friend class CoverageMapping;
330
331 public:
332   CoverageData() {}
333
334   CoverageData(StringRef Filename) : Filename(Filename) {}
335
336   CoverageData(CoverageData &&RHS)
337       : Filename(std::move(RHS.Filename)), Segments(std::move(RHS.Segments)),
338         Expansions(std::move(RHS.Expansions)) {}
339
340   /// \brief Get the name of the file this data covers.
341   StringRef getFilename() { return Filename; }
342
343   std::vector<CoverageSegment>::iterator begin() { return Segments.begin(); }
344   std::vector<CoverageSegment>::iterator end() { return Segments.end(); }
345   bool empty() { return Segments.empty(); }
346
347   /// \brief Expansions that can be further processed.
348   std::vector<ExpansionRecord> getExpansions() { return Expansions; }
349 };
350
351 /// \brief The mapping of profile information to coverage data.
352 ///
353 /// This is the main interface to get coverage information, using a profile to
354 /// fill out execution counts.
355 class CoverageMapping {
356   std::vector<FunctionRecord> Functions;
357   unsigned MismatchedFunctionCount;
358
359   CoverageMapping() : MismatchedFunctionCount(0) {}
360
361 public:
362   /// \brief Load the coverage mapping using the given readers.
363   static ErrorOr<std::unique_ptr<CoverageMapping>>
364   load(ObjectFileCoverageMappingReader &CoverageReader,
365        IndexedInstrProfReader &ProfileReader);
366
367   /// \brief Load the coverage mapping from the given files.
368   static ErrorOr<std::unique_ptr<CoverageMapping>>
369   load(StringRef ObjectFilename, StringRef ProfileFilename);
370
371   /// \brief The number of functions that couldn't have their profiles mapped.
372   ///
373   /// This is a count of functions whose profile is out of date or otherwise
374   /// can't be associated with any coverage information.
375   unsigned getMismatchedCount() { return MismatchedFunctionCount; }
376
377   /// \brief Returns the list of files that are covered.
378   std::vector<StringRef> getUniqueSourceFiles() const;
379
380   /// \brief Get the coverage for a particular file.
381   ///
382   /// The given filename must be the name as recorded in the coverage
383   /// information. That is, only names returned from getUniqueSourceFiles will
384   /// yield a result.
385   CoverageData getCoverageForFile(StringRef Filename);
386
387   /// \brief Gets all of the functions covered by this profile.
388   iterator_range<FunctionRecordIterator> getCoveredFunctions() const {
389     return make_range(FunctionRecordIterator(Functions),
390                       FunctionRecordIterator());
391   }
392
393   /// \brief Gets all of the functions in a particular file.
394   iterator_range<FunctionRecordIterator>
395   getCoveredFunctions(StringRef Filename) const {
396     return make_range(FunctionRecordIterator(Functions, Filename),
397                       FunctionRecordIterator());
398   }
399
400   /// \brief Get the list of function instantiations in the file.
401   ///
402   /// Fucntions that are instantiated more than once, such as C++ template
403   /// specializations, have distinct coverage records for each instantiation.
404   std::vector<const FunctionRecord *> getInstantiations(StringRef Filename);
405
406   /// \brief Get the coverage for a particular function.
407   CoverageData getCoverageForFunction(const FunctionRecord &Function);
408
409   /// \brief Get the coverage for an expansion within a coverage set.
410   CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion);
411 };
412
413 } // end namespace coverage
414
415 /// \brief Provide DenseMapInfo for CounterExpression
416 template<> struct DenseMapInfo<coverage::CounterExpression> {
417   static inline coverage::CounterExpression getEmptyKey() {
418     using namespace coverage;
419     return CounterExpression(CounterExpression::ExprKind::Subtract,
420                              Counter::getCounter(~0U),
421                              Counter::getCounter(~0U));
422   }
423
424   static inline coverage::CounterExpression getTombstoneKey() {
425     using namespace coverage;
426     return CounterExpression(CounterExpression::ExprKind::Add,
427                              Counter::getCounter(~0U),
428                              Counter::getCounter(~0U));
429   }
430
431   static unsigned getHashValue(const coverage::CounterExpression &V) {
432     return static_cast<unsigned>(
433         hash_combine(V.Kind, V.LHS.getKind(), V.LHS.getCounterID(),
434                      V.RHS.getKind(), V.RHS.getCounterID()));
435   }
436
437   static bool isEqual(const coverage::CounterExpression &LHS,
438                       const coverage::CounterExpression &RHS) {
439     return LHS.Kind == RHS.Kind && LHS.LHS == RHS.LHS && LHS.RHS == RHS.RHS;
440   }
441 };
442
443
444 } // end namespace llvm
445
446 #endif // LLVM_PROFILEDATA_COVERAGEMAPPING_H_