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