1 //===- CoverageMapping.cpp - Code coverage mapping support ----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains support for clang's and llvm's instrumentation based
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallBitVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23 #include "llvm/ProfileData/InstrProfReader.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/Errc.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
38 #include <system_error>
43 using namespace coverage
;
45 #define DEBUG_TYPE "coverage-mapping"
47 Counter
CounterExpressionBuilder::get(const CounterExpression
&E
) {
48 auto It
= ExpressionIndices
.find(E
);
49 if (It
!= ExpressionIndices
.end())
50 return Counter::getExpression(It
->second
);
51 unsigned I
= Expressions
.size();
52 Expressions
.push_back(E
);
53 ExpressionIndices
[E
] = I
;
54 return Counter::getExpression(I
);
57 void CounterExpressionBuilder::extractTerms(Counter C
, int Factor
,
58 SmallVectorImpl
<Term
> &Terms
) {
59 switch (C
.getKind()) {
62 case Counter::CounterValueReference
:
63 Terms
.emplace_back(C
.getCounterID(), Factor
);
65 case Counter::Expression
:
66 const auto &E
= Expressions
[C
.getExpressionID()];
67 extractTerms(E
.LHS
, Factor
, Terms
);
69 E
.RHS
, E
.Kind
== CounterExpression::Subtract
? -Factor
: Factor
, Terms
);
74 Counter
CounterExpressionBuilder::simplify(Counter ExpressionTree
) {
75 // Gather constant terms.
76 SmallVector
<Term
, 32> Terms
;
77 extractTerms(ExpressionTree
, +1, Terms
);
79 // If there are no terms, this is just a zero. The algorithm below assumes at
81 if (Terms
.size() == 0)
82 return Counter::getZero();
84 // Group the terms by counter ID.
85 llvm::sort(Terms
, [](const Term
&LHS
, const Term
&RHS
) {
86 return LHS
.CounterID
< RHS
.CounterID
;
89 // Combine terms by counter ID to eliminate counters that sum to zero.
90 auto Prev
= Terms
.begin();
91 for (auto I
= Prev
+ 1, E
= Terms
.end(); I
!= E
; ++I
) {
92 if (I
->CounterID
== Prev
->CounterID
) {
93 Prev
->Factor
+= I
->Factor
;
99 Terms
.erase(++Prev
, Terms
.end());
102 // Create additions. We do this before subtractions to avoid constructs like
103 // ((0 - X) + Y), as opposed to (Y - X).
104 for (auto T
: Terms
) {
107 for (int I
= 0; I
< T
.Factor
; ++I
)
109 C
= Counter::getCounter(T
.CounterID
);
111 C
= get(CounterExpression(CounterExpression::Add
, C
,
112 Counter::getCounter(T
.CounterID
)));
115 // Create subtractions.
116 for (auto T
: Terms
) {
119 for (int I
= 0; I
< -T
.Factor
; ++I
)
120 C
= get(CounterExpression(CounterExpression::Subtract
, C
,
121 Counter::getCounter(T
.CounterID
)));
126 Counter
CounterExpressionBuilder::add(Counter LHS
, Counter RHS
) {
127 return simplify(get(CounterExpression(CounterExpression::Add
, LHS
, RHS
)));
130 Counter
CounterExpressionBuilder::subtract(Counter LHS
, Counter RHS
) {
132 get(CounterExpression(CounterExpression::Subtract
, LHS
, RHS
)));
135 void CounterMappingContext::dump(const Counter
&C
, raw_ostream
&OS
) const {
136 switch (C
.getKind()) {
140 case Counter::CounterValueReference
:
141 OS
<< '#' << C
.getCounterID();
143 case Counter::Expression
: {
144 if (C
.getExpressionID() >= Expressions
.size())
146 const auto &E
= Expressions
[C
.getExpressionID()];
149 OS
<< (E
.Kind
== CounterExpression::Subtract
? " - " : " + ");
155 if (CounterValues
.empty())
157 Expected
<int64_t> Value
= evaluate(C
);
158 if (auto E
= Value
.takeError()) {
159 consumeError(std::move(E
));
162 OS
<< '[' << *Value
<< ']';
165 Expected
<int64_t> CounterMappingContext::evaluate(const Counter
&C
) const {
166 switch (C
.getKind()) {
169 case Counter::CounterValueReference
:
170 if (C
.getCounterID() >= CounterValues
.size())
171 return errorCodeToError(errc::argument_out_of_domain
);
172 return CounterValues
[C
.getCounterID()];
173 case Counter::Expression
: {
174 if (C
.getExpressionID() >= Expressions
.size())
175 return errorCodeToError(errc::argument_out_of_domain
);
176 const auto &E
= Expressions
[C
.getExpressionID()];
177 Expected
<int64_t> LHS
= evaluate(E
.LHS
);
180 Expected
<int64_t> RHS
= evaluate(E
.RHS
);
183 return E
.Kind
== CounterExpression::Subtract
? *LHS
- *RHS
: *LHS
+ *RHS
;
186 llvm_unreachable("Unhandled CounterKind");
189 void FunctionRecordIterator::skipOtherFiles() {
190 while (Current
!= Records
.end() && !Filename
.empty() &&
191 Filename
!= Current
->Filenames
[0])
193 if (Current
== Records
.end())
194 *this = FunctionRecordIterator();
197 Error
CoverageMapping::loadFunctionRecord(
198 const CoverageMappingRecord
&Record
,
199 IndexedInstrProfReader
&ProfileReader
) {
200 StringRef OrigFuncName
= Record
.FunctionName
;
201 if (OrigFuncName
.empty())
202 return make_error
<CoverageMapError
>(coveragemap_error::malformed
);
204 if (Record
.Filenames
.empty())
205 OrigFuncName
= getFuncNameWithoutPrefix(OrigFuncName
);
207 OrigFuncName
= getFuncNameWithoutPrefix(OrigFuncName
, Record
.Filenames
[0]);
209 CounterMappingContext
Ctx(Record
.Expressions
);
211 std::vector
<uint64_t> Counts
;
212 if (Error E
= ProfileReader
.getFunctionCounts(Record
.FunctionName
,
213 Record
.FunctionHash
, Counts
)) {
214 instrprof_error IPE
= InstrProfError::take(std::move(E
));
215 if (IPE
== instrprof_error::hash_mismatch
) {
216 FuncHashMismatches
.emplace_back(Record
.FunctionName
, Record
.FunctionHash
);
217 return Error::success();
218 } else if (IPE
!= instrprof_error::unknown_function
)
219 return make_error
<InstrProfError
>(IPE
);
220 Counts
.assign(Record
.MappingRegions
.size(), 0);
222 Ctx
.setCounts(Counts
);
224 assert(!Record
.MappingRegions
.empty() && "Function has no regions");
226 // This coverage record is a zero region for a function that's unused in
227 // some TU, but used in a different TU. Ignore it. The coverage maps from the
228 // the other TU will either be loaded (providing full region counts) or they
229 // won't (in which case we don't unintuitively report functions as uncovered
230 // when they have non-zero counts in the profile).
231 if (Record
.MappingRegions
.size() == 1 &&
232 Record
.MappingRegions
[0].Count
.isZero() && Counts
[0] > 0)
233 return Error::success();
235 FunctionRecord
Function(OrigFuncName
, Record
.Filenames
);
236 for (const auto &Region
: Record
.MappingRegions
) {
237 Expected
<int64_t> ExecutionCount
= Ctx
.evaluate(Region
.Count
);
238 if (auto E
= ExecutionCount
.takeError()) {
239 consumeError(std::move(E
));
240 return Error::success();
242 Function
.pushRegion(Region
, *ExecutionCount
);
245 // Don't create records for (filenames, function) pairs we've already seen.
246 auto FilenamesHash
= hash_combine_range(Record
.Filenames
.begin(),
247 Record
.Filenames
.end());
248 if (!RecordProvenance
[FilenamesHash
].insert(hash_value(OrigFuncName
)).second
)
249 return Error::success();
251 Functions
.push_back(std::move(Function
));
252 return Error::success();
255 Expected
<std::unique_ptr
<CoverageMapping
>> CoverageMapping::load(
256 ArrayRef
<std::unique_ptr
<CoverageMappingReader
>> CoverageReaders
,
257 IndexedInstrProfReader
&ProfileReader
) {
258 auto Coverage
= std::unique_ptr
<CoverageMapping
>(new CoverageMapping());
260 for (const auto &CoverageReader
: CoverageReaders
) {
261 for (auto RecordOrErr
: *CoverageReader
) {
262 if (Error E
= RecordOrErr
.takeError())
264 const auto &Record
= *RecordOrErr
;
265 if (Error E
= Coverage
->loadFunctionRecord(Record
, ProfileReader
))
270 return std::move(Coverage
);
273 // If E is a no_data_found error, returns success. Otherwise returns E.
274 static Error
handleMaybeNoDataFoundError(Error E
) {
276 std::move(E
), [](const CoverageMapError
&CME
) {
277 if (CME
.get() == coveragemap_error::no_data_found
)
278 return static_cast<Error
>(Error::success());
279 return make_error
<CoverageMapError
>(CME
.get());
283 Expected
<std::unique_ptr
<CoverageMapping
>>
284 CoverageMapping::load(ArrayRef
<StringRef
> ObjectFilenames
,
285 StringRef ProfileFilename
, ArrayRef
<StringRef
> Arches
) {
286 auto ProfileReaderOrErr
= IndexedInstrProfReader::create(ProfileFilename
);
287 if (Error E
= ProfileReaderOrErr
.takeError())
289 auto ProfileReader
= std::move(ProfileReaderOrErr
.get());
291 SmallVector
<std::unique_ptr
<CoverageMappingReader
>, 4> Readers
;
292 SmallVector
<std::unique_ptr
<MemoryBuffer
>, 4> Buffers
;
293 for (const auto &File
: llvm::enumerate(ObjectFilenames
)) {
294 auto CovMappingBufOrErr
= MemoryBuffer::getFileOrSTDIN(File
.value());
295 if (std::error_code EC
= CovMappingBufOrErr
.getError())
296 return errorCodeToError(EC
);
297 StringRef Arch
= Arches
.empty() ? StringRef() : Arches
[File
.index()];
298 MemoryBufferRef CovMappingBufRef
=
299 CovMappingBufOrErr
.get()->getMemBufferRef();
300 auto CoverageReadersOrErr
=
301 BinaryCoverageReader::create(CovMappingBufRef
, Arch
, Buffers
);
302 if (Error E
= CoverageReadersOrErr
.takeError()) {
303 E
= handleMaybeNoDataFoundError(std::move(E
));
306 // E == success (originally a no_data_found error).
309 for (auto &Reader
: CoverageReadersOrErr
.get())
310 Readers
.push_back(std::move(Reader
));
311 Buffers
.push_back(std::move(CovMappingBufOrErr
.get()));
313 // If no readers were created, either no objects were provided or none of them
314 // had coverage data. Return an error in the latter case.
315 if (Readers
.empty() && !ObjectFilenames
.empty())
316 return make_error
<CoverageMapError
>(coveragemap_error::no_data_found
);
317 return load(Readers
, *ProfileReader
);
322 /// Distributes functions into instantiation sets.
324 /// An instantiation set is a collection of functions that have the same source
325 /// code, ie, template functions specializations.
326 class FunctionInstantiationSetCollector
{
327 using MapT
= std::map
<LineColPair
, std::vector
<const FunctionRecord
*>>;
328 MapT InstantiatedFunctions
;
331 void insert(const FunctionRecord
&Function
, unsigned FileID
) {
332 auto I
= Function
.CountedRegions
.begin(), E
= Function
.CountedRegions
.end();
333 while (I
!= E
&& I
->FileID
!= FileID
)
335 assert(I
!= E
&& "function does not cover the given file");
336 auto &Functions
= InstantiatedFunctions
[I
->startLoc()];
337 Functions
.push_back(&Function
);
340 MapT::iterator
begin() { return InstantiatedFunctions
.begin(); }
341 MapT::iterator
end() { return InstantiatedFunctions
.end(); }
344 class SegmentBuilder
{
345 std::vector
<CoverageSegment
> &Segments
;
346 SmallVector
<const CountedRegion
*, 8> ActiveRegions
;
348 SegmentBuilder(std::vector
<CoverageSegment
> &Segments
) : Segments(Segments
) {}
350 /// Emit a segment with the count from \p Region starting at \p StartLoc.
352 /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
353 /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
354 void startSegment(const CountedRegion
&Region
, LineColPair StartLoc
,
355 bool IsRegionEntry
, bool EmitSkippedRegion
= false) {
356 bool HasCount
= !EmitSkippedRegion
&&
357 (Region
.Kind
!= CounterMappingRegion::SkippedRegion
);
359 // If the new segment wouldn't affect coverage rendering, skip it.
360 if (!Segments
.empty() && !IsRegionEntry
&& !EmitSkippedRegion
) {
361 const auto &Last
= Segments
.back();
362 if (Last
.HasCount
== HasCount
&& Last
.Count
== Region
.ExecutionCount
&&
368 Segments
.emplace_back(StartLoc
.first
, StartLoc
.second
,
369 Region
.ExecutionCount
, IsRegionEntry
,
370 Region
.Kind
== CounterMappingRegion::GapRegion
);
372 Segments
.emplace_back(StartLoc
.first
, StartLoc
.second
, IsRegionEntry
);
375 const auto &Last
= Segments
.back();
376 dbgs() << "Segment at " << Last
.Line
<< ":" << Last
.Col
377 << " (count = " << Last
.Count
<< ")"
378 << (Last
.IsRegionEntry
? ", RegionEntry" : "")
379 << (!Last
.HasCount
? ", Skipped" : "")
380 << (Last
.IsGapRegion
? ", Gap" : "") << "\n";
384 /// Emit segments for active regions which end before \p Loc.
386 /// \p Loc: The start location of the next region. If None, all active
387 /// regions are completed.
388 /// \p FirstCompletedRegion: Index of the first completed region.
389 void completeRegionsUntil(Optional
<LineColPair
> Loc
,
390 unsigned FirstCompletedRegion
) {
391 // Sort the completed regions by end location. This makes it simple to
392 // emit closing segments in sorted order.
393 auto CompletedRegionsIt
= ActiveRegions
.begin() + FirstCompletedRegion
;
394 std::stable_sort(CompletedRegionsIt
, ActiveRegions
.end(),
395 [](const CountedRegion
*L
, const CountedRegion
*R
) {
396 return L
->endLoc() < R
->endLoc();
399 // Emit segments for all completed regions.
400 for (unsigned I
= FirstCompletedRegion
+ 1, E
= ActiveRegions
.size(); I
< E
;
402 const auto *CompletedRegion
= ActiveRegions
[I
];
403 assert((!Loc
|| CompletedRegion
->endLoc() <= *Loc
) &&
404 "Completed region ends after start of new region");
406 const auto *PrevCompletedRegion
= ActiveRegions
[I
- 1];
407 auto CompletedSegmentLoc
= PrevCompletedRegion
->endLoc();
409 // Don't emit any more segments if they start where the new region begins.
410 if (Loc
&& CompletedSegmentLoc
== *Loc
)
413 // Don't emit a segment if the next completed region ends at the same
414 // location as this one.
415 if (CompletedSegmentLoc
== CompletedRegion
->endLoc())
418 // Use the count from the last completed region which ends at this loc.
419 for (unsigned J
= I
+ 1; J
< E
; ++J
)
420 if (CompletedRegion
->endLoc() == ActiveRegions
[J
]->endLoc())
421 CompletedRegion
= ActiveRegions
[J
];
423 startSegment(*CompletedRegion
, CompletedSegmentLoc
, false);
426 auto Last
= ActiveRegions
.back();
427 if (FirstCompletedRegion
&& Last
->endLoc() != *Loc
) {
428 // If there's a gap after the end of the last completed region and the
429 // start of the new region, use the last active region to fill the gap.
430 startSegment(*ActiveRegions
[FirstCompletedRegion
- 1], Last
->endLoc(),
432 } else if (!FirstCompletedRegion
&& (!Loc
|| *Loc
!= Last
->endLoc())) {
433 // Emit a skipped segment if there are no more active regions. This
434 // ensures that gaps between functions are marked correctly.
435 startSegment(*Last
, Last
->endLoc(), false, true);
438 // Pop the completed regions.
439 ActiveRegions
.erase(CompletedRegionsIt
, ActiveRegions
.end());
442 void buildSegmentsImpl(ArrayRef
<CountedRegion
> Regions
) {
443 for (const auto &CR
: enumerate(Regions
)) {
444 auto CurStartLoc
= CR
.value().startLoc();
446 // Active regions which end before the current region need to be popped.
447 auto CompletedRegions
=
448 std::stable_partition(ActiveRegions
.begin(), ActiveRegions
.end(),
449 [&](const CountedRegion
*Region
) {
450 return !(Region
->endLoc() <= CurStartLoc
);
452 if (CompletedRegions
!= ActiveRegions
.end()) {
453 unsigned FirstCompletedRegion
=
454 std::distance(ActiveRegions
.begin(), CompletedRegions
);
455 completeRegionsUntil(CurStartLoc
, FirstCompletedRegion
);
458 bool GapRegion
= CR
.value().Kind
== CounterMappingRegion::GapRegion
;
460 // Try to emit a segment for the current region.
461 if (CurStartLoc
== CR
.value().endLoc()) {
462 // Avoid making zero-length regions active. If it's the last region,
463 // emit a skipped segment. Otherwise use its predecessor's count.
464 const bool Skipped
= (CR
.index() + 1) == Regions
.size();
465 startSegment(ActiveRegions
.empty() ? CR
.value() : *ActiveRegions
.back(),
466 CurStartLoc
, !GapRegion
, Skipped
);
469 if (CR
.index() + 1 == Regions
.size() ||
470 CurStartLoc
!= Regions
[CR
.index() + 1].startLoc()) {
471 // Emit a segment if the next region doesn't start at the same location
473 startSegment(CR
.value(), CurStartLoc
, !GapRegion
);
476 // This region is active (i.e not completed).
477 ActiveRegions
.push_back(&CR
.value());
480 // Complete any remaining active regions.
481 if (!ActiveRegions
.empty())
482 completeRegionsUntil(None
, 0);
485 /// Sort a nested sequence of regions from a single file.
486 static void sortNestedRegions(MutableArrayRef
<CountedRegion
> Regions
) {
487 llvm::sort(Regions
, [](const CountedRegion
&LHS
, const CountedRegion
&RHS
) {
488 if (LHS
.startLoc() != RHS
.startLoc())
489 return LHS
.startLoc() < RHS
.startLoc();
490 if (LHS
.endLoc() != RHS
.endLoc())
491 // When LHS completely contains RHS, we sort LHS first.
492 return RHS
.endLoc() < LHS
.endLoc();
493 // If LHS and RHS cover the same area, we need to sort them according
494 // to their kinds so that the most suitable region will become "active"
495 // in combineRegions(). Because we accumulate counter values only from
496 // regions of the same kind as the first region of the area, prefer
497 // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
498 static_assert(CounterMappingRegion::CodeRegion
<
499 CounterMappingRegion::ExpansionRegion
&&
500 CounterMappingRegion::ExpansionRegion
<
501 CounterMappingRegion::SkippedRegion
,
502 "Unexpected order of region kind values");
503 return LHS
.Kind
< RHS
.Kind
;
507 /// Combine counts of regions which cover the same area.
508 static ArrayRef
<CountedRegion
>
509 combineRegions(MutableArrayRef
<CountedRegion
> Regions
) {
512 auto Active
= Regions
.begin();
513 auto End
= Regions
.end();
514 for (auto I
= Regions
.begin() + 1; I
!= End
; ++I
) {
515 if (Active
->startLoc() != I
->startLoc() ||
516 Active
->endLoc() != I
->endLoc()) {
517 // Shift to the next region.
523 // Merge duplicate region.
524 // If CodeRegions and ExpansionRegions cover the same area, it's probably
525 // a macro which is fully expanded to another macro. In that case, we need
526 // to accumulate counts only from CodeRegions, or else the area will be
528 // On the other hand, a macro may have a nested macro in its body. If the
529 // outer macro is used several times, the ExpansionRegion for the nested
530 // macro will also be added several times. These ExpansionRegions cover
531 // the same source locations and have to be combined to reach the correct
532 // value for that area.
533 // We add counts of the regions of the same kind as the active region
534 // to handle the both situations.
535 if (I
->Kind
== Active
->Kind
)
536 Active
->ExecutionCount
+= I
->ExecutionCount
;
538 return Regions
.drop_back(std::distance(++Active
, End
));
542 /// Build a sorted list of CoverageSegments from a list of Regions.
543 static std::vector
<CoverageSegment
>
544 buildSegments(MutableArrayRef
<CountedRegion
> Regions
) {
545 std::vector
<CoverageSegment
> Segments
;
546 SegmentBuilder
Builder(Segments
);
548 sortNestedRegions(Regions
);
549 ArrayRef
<CountedRegion
> CombinedRegions
= combineRegions(Regions
);
552 dbgs() << "Combined regions:\n";
553 for (const auto &CR
: CombinedRegions
)
554 dbgs() << " " << CR
.LineStart
<< ":" << CR
.ColumnStart
<< " -> "
555 << CR
.LineEnd
<< ":" << CR
.ColumnEnd
556 << " (count=" << CR
.ExecutionCount
<< ")\n";
559 Builder
.buildSegmentsImpl(CombinedRegions
);
562 for (unsigned I
= 1, E
= Segments
.size(); I
< E
; ++I
) {
563 const auto &L
= Segments
[I
- 1];
564 const auto &R
= Segments
[I
];
565 if (!(L
.Line
< R
.Line
) && !(L
.Line
== R
.Line
&& L
.Col
< R
.Col
)) {
566 LLVM_DEBUG(dbgs() << " ! Segment " << L
.Line
<< ":" << L
.Col
567 << " followed by " << R
.Line
<< ":" << R
.Col
<< "\n");
568 assert(false && "Coverage segments not unique or sorted");
577 } // end anonymous namespace
579 std::vector
<StringRef
> CoverageMapping::getUniqueSourceFiles() const {
580 std::vector
<StringRef
> Filenames
;
581 for (const auto &Function
: getCoveredFunctions())
582 Filenames
.insert(Filenames
.end(), Function
.Filenames
.begin(),
583 Function
.Filenames
.end());
584 llvm::sort(Filenames
);
585 auto Last
= std::unique(Filenames
.begin(), Filenames
.end());
586 Filenames
.erase(Last
, Filenames
.end());
590 static SmallBitVector
gatherFileIDs(StringRef SourceFile
,
591 const FunctionRecord
&Function
) {
592 SmallBitVector
FilenameEquivalence(Function
.Filenames
.size(), false);
593 for (unsigned I
= 0, E
= Function
.Filenames
.size(); I
< E
; ++I
)
594 if (SourceFile
== Function
.Filenames
[I
])
595 FilenameEquivalence
[I
] = true;
596 return FilenameEquivalence
;
599 /// Return the ID of the file where the definition of the function is located.
600 static Optional
<unsigned> findMainViewFileID(const FunctionRecord
&Function
) {
601 SmallBitVector
IsNotExpandedFile(Function
.Filenames
.size(), true);
602 for (const auto &CR
: Function
.CountedRegions
)
603 if (CR
.Kind
== CounterMappingRegion::ExpansionRegion
)
604 IsNotExpandedFile
[CR
.ExpandedFileID
] = false;
605 int I
= IsNotExpandedFile
.find_first();
611 /// Check if SourceFile is the file that contains the definition of
612 /// the Function. Return the ID of the file in that case or None otherwise.
613 static Optional
<unsigned> findMainViewFileID(StringRef SourceFile
,
614 const FunctionRecord
&Function
) {
615 Optional
<unsigned> I
= findMainViewFileID(Function
);
616 if (I
&& SourceFile
== Function
.Filenames
[*I
])
621 static bool isExpansion(const CountedRegion
&R
, unsigned FileID
) {
622 return R
.Kind
== CounterMappingRegion::ExpansionRegion
&& R
.FileID
== FileID
;
625 CoverageData
CoverageMapping::getCoverageForFile(StringRef Filename
) const {
626 CoverageData
FileCoverage(Filename
);
627 std::vector
<CountedRegion
> Regions
;
629 for (const auto &Function
: Functions
) {
630 auto MainFileID
= findMainViewFileID(Filename
, Function
);
631 auto FileIDs
= gatherFileIDs(Filename
, Function
);
632 for (const auto &CR
: Function
.CountedRegions
)
633 if (FileIDs
.test(CR
.FileID
)) {
634 Regions
.push_back(CR
);
635 if (MainFileID
&& isExpansion(CR
, *MainFileID
))
636 FileCoverage
.Expansions
.emplace_back(CR
, Function
);
640 LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename
<< "\n");
641 FileCoverage
.Segments
= SegmentBuilder::buildSegments(Regions
);
646 std::vector
<InstantiationGroup
>
647 CoverageMapping::getInstantiationGroups(StringRef Filename
) const {
648 FunctionInstantiationSetCollector InstantiationSetCollector
;
649 for (const auto &Function
: Functions
) {
650 auto MainFileID
= findMainViewFileID(Filename
, Function
);
653 InstantiationSetCollector
.insert(Function
, *MainFileID
);
656 std::vector
<InstantiationGroup
> Result
;
657 for (auto &InstantiationSet
: InstantiationSetCollector
) {
658 InstantiationGroup IG
{InstantiationSet
.first
.first
,
659 InstantiationSet
.first
.second
,
660 std::move(InstantiationSet
.second
)};
661 Result
.emplace_back(std::move(IG
));
667 CoverageMapping::getCoverageForFunction(const FunctionRecord
&Function
) const {
668 auto MainFileID
= findMainViewFileID(Function
);
670 return CoverageData();
672 CoverageData
FunctionCoverage(Function
.Filenames
[*MainFileID
]);
673 std::vector
<CountedRegion
> Regions
;
674 for (const auto &CR
: Function
.CountedRegions
)
675 if (CR
.FileID
== *MainFileID
) {
676 Regions
.push_back(CR
);
677 if (isExpansion(CR
, *MainFileID
))
678 FunctionCoverage
.Expansions
.emplace_back(CR
, Function
);
681 LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function
.Name
683 FunctionCoverage
.Segments
= SegmentBuilder::buildSegments(Regions
);
685 return FunctionCoverage
;
688 CoverageData
CoverageMapping::getCoverageForExpansion(
689 const ExpansionRecord
&Expansion
) const {
690 CoverageData
ExpansionCoverage(
691 Expansion
.Function
.Filenames
[Expansion
.FileID
]);
692 std::vector
<CountedRegion
> Regions
;
693 for (const auto &CR
: Expansion
.Function
.CountedRegions
)
694 if (CR
.FileID
== Expansion
.FileID
) {
695 Regions
.push_back(CR
);
696 if (isExpansion(CR
, Expansion
.FileID
))
697 ExpansionCoverage
.Expansions
.emplace_back(CR
, Expansion
.Function
);
700 LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
701 << Expansion
.FileID
<< "\n");
702 ExpansionCoverage
.Segments
= SegmentBuilder::buildSegments(Regions
);
704 return ExpansionCoverage
;
707 LineCoverageStats::LineCoverageStats(
708 ArrayRef
<const CoverageSegment
*> LineSegments
,
709 const CoverageSegment
*WrappedSegment
, unsigned Line
)
710 : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line
),
711 LineSegments(LineSegments
), WrappedSegment(WrappedSegment
) {
712 // Find the minimum number of regions which start in this line.
713 unsigned MinRegionCount
= 0;
714 auto isStartOfRegion
= [](const CoverageSegment
*S
) {
715 return !S
->IsGapRegion
&& S
->HasCount
&& S
->IsRegionEntry
;
717 for (unsigned I
= 0; I
< LineSegments
.size() && MinRegionCount
< 2; ++I
)
718 if (isStartOfRegion(LineSegments
[I
]))
721 bool StartOfSkippedRegion
= !LineSegments
.empty() &&
722 !LineSegments
.front()->HasCount
&&
723 LineSegments
.front()->IsRegionEntry
;
725 HasMultipleRegions
= MinRegionCount
> 1;
727 !StartOfSkippedRegion
&&
728 ((WrappedSegment
&& WrappedSegment
->HasCount
) || (MinRegionCount
> 0));
733 // Pick the max count from the non-gap, region entry segments and the
736 ExecutionCount
= WrappedSegment
->Count
;
739 for (const auto *LS
: LineSegments
)
740 if (isStartOfRegion(LS
))
741 ExecutionCount
= std::max(ExecutionCount
, LS
->Count
);
744 LineCoverageIterator
&LineCoverageIterator::operator++() {
745 if (Next
== CD
.end()) {
746 Stats
= LineCoverageStats();
751 WrappedSegment
= Segments
.back();
753 while (Next
!= CD
.end() && Next
->Line
== Line
)
754 Segments
.push_back(&*Next
++);
755 Stats
= LineCoverageStats(Segments
, WrappedSegment
, Line
);
760 static std::string
getCoverageMapErrString(coveragemap_error Err
) {
762 case coveragemap_error::success
:
764 case coveragemap_error::eof
:
765 return "End of File";
766 case coveragemap_error::no_data_found
:
767 return "No coverage data found";
768 case coveragemap_error::unsupported_version
:
769 return "Unsupported coverage format version";
770 case coveragemap_error::truncated
:
771 return "Truncated coverage data";
772 case coveragemap_error::malformed
:
773 return "Malformed coverage data";
775 llvm_unreachable("A value of coveragemap_error has no message.");
780 // FIXME: This class is only here to support the transition to llvm::Error. It
781 // will be removed once this transition is complete. Clients should prefer to
782 // deal with the Error value directly, rather than converting to error_code.
783 class CoverageMappingErrorCategoryType
: public std::error_category
{
784 const char *name() const noexcept override
{ return "llvm.coveragemap"; }
785 std::string
message(int IE
) const override
{
786 return getCoverageMapErrString(static_cast<coveragemap_error
>(IE
));
790 } // end anonymous namespace
792 std::string
CoverageMapError::message() const {
793 return getCoverageMapErrString(Err
);
796 static ManagedStatic
<CoverageMappingErrorCategoryType
> ErrorCategory
;
798 const std::error_category
&llvm::coverage::coveragemap_category() {
799 return *ErrorCategory
;
802 char CoverageMapError::ID
= 0;