39 #include <system_error> 44 using namespace coverage;
46 #define DEBUG_TYPE "coverage-mapping" 49 auto It = ExpressionIndices.find(E);
50 if (It != ExpressionIndices.end())
52 unsigned I = Expressions.size();
53 Expressions.push_back(E);
54 ExpressionIndices[
E] =
I;
58 void CounterExpressionBuilder::extractTerms(
Counter C,
int Factor,
68 extractTerms(
E.LHS, Factor, Terms);
75 Counter CounterExpressionBuilder::simplify(
Counter ExpressionTree) {
78 extractTerms(ExpressionTree, +1, Terms);
82 if (Terms.
size() == 0)
87 return LHS.CounterID < RHS.CounterID;
91 auto Prev = Terms.
begin();
92 for (
auto I = Prev + 1,
E = Terms.
end();
I !=
E; ++
I) {
93 if (
I->CounterID == Prev->CounterID) {
94 Prev->Factor +=
I->Factor;
105 for (
auto T : Terms) {
108 for (
int I = 0;
I <
T.Factor; ++
I)
117 for (
auto T : Terms) {
120 for (
int I = 0;
I < -
T.Factor; ++
I)
156 if (CounterValues.empty())
163 OS <<
'[' << *Value <<
']';
190 void FunctionRecordIterator::skipOtherFiles() {
191 while (Current != Records.end() && !Filename.empty() &&
192 Filename != Current->Filenames[0])
194 if (Current == Records.end())
198 Error CoverageMapping::loadFunctionRecord(
202 if (OrigFuncName.
empty())
213 if (!RecordProvenance[FilenamesHash].insert(
hash_value(OrigFuncName)).second)
218 std::vector<uint64_t> Counts;
226 return make_error<InstrProfError>(IPE);
240 Function.pushRegion(
Region, *ExecutionCount);
242 if (Function.CountedRegions.size() != Record.
MappingRegions.size()) {
244 Function.CountedRegions.
size());
248 Functions.push_back(std::move(Function));
253 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
255 auto Coverage = std::unique_ptr<CoverageMapping>(
new CoverageMapping());
257 for (
const auto &CoverageReader : CoverageReaders) {
258 for (
auto RecordOrErr : *CoverageReader) {
259 if (
Error E = RecordOrErr.takeError())
261 const auto &Record = *RecordOrErr;
262 if (
Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
267 return std::move(Coverage);
274 if (
Error E = ProfileReaderOrErr.takeError())
276 auto ProfileReader = std::move(ProfileReaderOrErr.get());
282 if (std::error_code EC = CovMappingBufOrErr.getError())
285 auto CoverageReaderOrErr =
287 if (
Error E = CoverageReaderOrErr.takeError())
289 Readers.push_back(std::move(CoverageReaderOrErr.get()));
290 Buffers.
push_back(std::move(CovMappingBufOrErr.get()));
292 return load(Readers, *ProfileReader);
301 class FunctionInstantiationSetCollector {
302 using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
303 MapT InstantiatedFunctions;
308 while (
I !=
E &&
I->FileID != FileID)
310 assert(
I !=
E &&
"function does not cover the given file");
311 auto &Functions = InstantiatedFunctions[
I->startLoc()];
312 Functions.push_back(&Function);
315 MapT::iterator
begin() {
return InstantiatedFunctions.
begin(); }
316 MapT::iterator
end() {
return InstantiatedFunctions.
end(); }
319 class SegmentBuilder {
320 std::vector<CoverageSegment> &Segments;
323 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
330 bool IsRegionEntry,
bool EmitSkippedRegion =
false) {
331 bool HasCount = !EmitSkippedRegion &&
335 if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
336 const auto &Last = Segments.back();
337 if (Last.HasCount == HasCount && Last.Count == Region.
ExecutionCount &&
343 Segments.emplace_back(StartLoc.first, StartLoc.second,
347 Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
350 const auto &Last = Segments.back();
351 dbgs() <<
"Segment at " << Last.Line <<
":" << Last.Col
352 <<
" (count = " << Last.Count <<
")" 353 << (Last.IsRegionEntry ?
", RegionEntry" :
"")
354 << (!Last.HasCount ?
", Skipped" :
"")
355 << (Last.IsGapRegion ?
", Gap" :
"") <<
"\n";
365 unsigned FirstCompletedRegion) {
368 auto CompletedRegionsIt = ActiveRegions.
begin() + FirstCompletedRegion;
369 std::stable_sort(CompletedRegionsIt, ActiveRegions.
end(),
371 return L->
endLoc() < R->endLoc();
375 for (
unsigned I = FirstCompletedRegion + 1,
E = ActiveRegions.
size();
I <
E;
377 const auto *CompletedRegion = ActiveRegions[
I];
378 assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
379 "Completed region ends after start of new region");
381 const auto *PrevCompletedRegion = ActiveRegions[
I - 1];
382 auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
385 if (Loc && CompletedSegmentLoc == *Loc)
390 if (CompletedSegmentLoc == CompletedRegion->endLoc())
394 for (
unsigned J =
I + 1; J <
E; ++J)
395 if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
396 CompletedRegion = ActiveRegions[J];
398 startSegment(*CompletedRegion, CompletedSegmentLoc,
false);
401 auto Last = ActiveRegions.
back();
402 if (FirstCompletedRegion && Last->endLoc() != *Loc) {
405 startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
407 }
else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
410 startSegment(*Last, Last->endLoc(),
false,
true);
414 ActiveRegions.
erase(CompletedRegionsIt, ActiveRegions.
end());
418 for (
const auto &CR :
enumerate(Regions)) {
419 auto CurStartLoc = CR.value().startLoc();
422 auto CompletedRegions =
423 std::stable_partition(ActiveRegions.
begin(), ActiveRegions.
end(),
425 return !(Region->
endLoc() <= CurStartLoc);
427 if (CompletedRegions != ActiveRegions.
end()) {
428 unsigned FirstCompletedRegion =
429 std::distance(ActiveRegions.
begin(), CompletedRegions);
430 completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
436 if (CurStartLoc == CR.value().endLoc()) {
439 const bool Skipped = (CR.index() + 1) == Regions.
size();
440 startSegment(ActiveRegions.
empty() ? CR.value() : *ActiveRegions.
back(),
441 CurStartLoc, !GapRegion, Skipped);
444 if (CR.index() + 1 == Regions.
size() ||
445 CurStartLoc != Regions[CR.index() + 1].startLoc()) {
448 startSegment(CR.value(), CurStartLoc, !GapRegion);
456 if (!ActiveRegions.
empty())
457 completeRegionsUntil(
None, 0);
464 if (LHS.
startLoc() != RHS.startLoc())
465 return LHS.
startLoc() < RHS.startLoc();
466 if (LHS.
endLoc() != RHS.endLoc())
468 return RHS.endLoc() < LHS.
endLoc();
478 "Unexpected order of region kind values");
479 return LHS.
Kind < RHS.Kind;
488 auto Active = Regions.
begin();
489 auto End = Regions.
end();
490 for (
auto I = Regions.
begin() + 1;
I != End; ++
I) {
491 if (Active->startLoc() !=
I->startLoc() ||
492 Active->endLoc() !=
I->endLoc()) {
511 if (
I->Kind == Active->Kind)
512 Active->ExecutionCount +=
I->ExecutionCount;
514 return Regions.
drop_back(std::distance(++Active, End));
519 static std::vector<CoverageSegment>
521 std::vector<CoverageSegment> Segments;
522 SegmentBuilder Builder(Segments);
524 sortNestedRegions(Regions);
528 dbgs() <<
"Combined regions:\n";
529 for (
const auto &CR : CombinedRegions)
530 dbgs() <<
" " << CR.LineStart <<
":" << CR.ColumnStart <<
" -> " 531 << CR.LineEnd <<
":" << CR.ColumnEnd
532 <<
" (count=" << CR.ExecutionCount <<
")\n";
535 Builder.buildSegmentsImpl(CombinedRegions);
538 for (
unsigned I = 1,
E = Segments.size();
I <
E; ++
I) {
539 const auto &L = Segments[
I - 1];
540 const auto &R = Segments[
I];
541 if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
543 <<
" followed by " << R.Line <<
":" << R.Col <<
"\n");
544 assert(
false &&
"Coverage segments not unique or sorted");
556 std::vector<StringRef> Filenames;
557 for (
const auto &
Function : getCoveredFunctions())
558 Filenames.insert(Filenames.end(),
Function.Filenames.
begin(),
560 llvm::sort(Filenames.begin(), Filenames.end());
561 auto Last = std::unique(Filenames.begin(), Filenames.end());
562 Filenames.erase(Last, Filenames.end());
571 FilenameEquivalence[
I] =
true;
572 return FilenameEquivalence;
580 IsNotExpandedFile[CR.ExpandedFileID] =
false;
581 int I = IsNotExpandedFile.find_first();
592 if (I && SourceFile == Function.
Filenames[*I])
603 std::vector<CountedRegion> Regions;
605 for (
const auto &
Function : Functions) {
608 for (
const auto &CR :
Function.CountedRegions)
609 if (FileIDs.test(CR.FileID)) {
610 Regions.push_back(CR);
612 FileCoverage.Expansions.emplace_back(CR,
Function);
616 LLVM_DEBUG(
dbgs() <<
"Emitting segments for file: " << Filename <<
"\n");
617 FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
622 std::vector<InstantiationGroup>
624 FunctionInstantiationSetCollector InstantiationSetCollector;
625 for (
const auto &
Function : Functions) {
629 InstantiationSetCollector.insert(
Function, *MainFileID);
632 std::vector<InstantiationGroup>
Result;
633 for (
auto &InstantiationSet : InstantiationSetCollector) {
635 InstantiationSet.first.second,
636 std::move(InstantiationSet.second)};
637 Result.emplace_back(std::move(IG));
649 std::vector<CountedRegion> Regions;
651 if (CR.FileID == *MainFileID) {
652 Regions.push_back(CR);
654 FunctionCoverage.Expansions.emplace_back(CR, Function);
659 FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
661 return FunctionCoverage;
668 std::vector<CountedRegion> Regions;
670 if (CR.FileID == Expansion.
FileID) {
671 Regions.push_back(CR);
673 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.
Function);
677 << Expansion.
FileID <<
"\n");
678 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
680 return ExpansionCoverage;
683 LineCoverageStats::LineCoverageStats(
686 : ExecutionCount(0), HasMultipleRegions(
false), Mapped(
false), Line(Line),
687 LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
689 unsigned MinRegionCount = 0;
691 return !S->
IsGapRegion && S->HasCount && S->IsRegionEntry;
693 for (
unsigned I = 0;
I < LineSegments.
size() && MinRegionCount < 2; ++
I)
694 if (isStartOfRegion(LineSegments[
I]))
697 bool StartOfSkippedRegion = !LineSegments.
empty() &&
701 HasMultipleRegions = MinRegionCount > 1;
703 !StartOfSkippedRegion &&
704 ((WrappedSegment && WrappedSegment->
HasCount) || (MinRegionCount > 0));
712 ExecutionCount = WrappedSegment->
Count;
715 for (
const auto *
LS : LineSegments)
716 if (isStartOfRegion(
LS))
717 ExecutionCount =
std::max(ExecutionCount,
LS->Count);
721 if (Next == CD.end()) {
727 WrappedSegment = Segments.back();
729 while (Next != CD.end() && Next->Line == Line)
730 Segments.push_back(&*Next++);
741 return "End of File";
743 return "No coverage data found";
745 return "Unsupported coverage format version";
747 return "Truncated coverage data";
749 return "Malformed coverage data";
760 const char *
name()
const noexcept
override {
return "llvm.coveragemap"; }
761 std::string message(
int IE)
const override {
const T & front() const
front - Get the first element.
void push_back(const T &Elt)
const_iterator end(StringRef path)
Get end iterator over path.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
Compute iterated dominance frontiers using a linear time algorithm.
static Counter getZero()
Return the counter that represents the number zero.
void setCounts(ArrayRef< uint64_t > Counts)
static instrprof_error take(Error E)
Consume an Error and return the raw enum value contained within it.
LineColPair endLoc() const
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
static SmallBitVector gatherFileIDs(StringRef SourceFile, const FunctionRecord &Function)
A Counter expression is a value that represents an arithmetic operation with two counters.
Error takeError()
Take ownership of the stored error.
ArrayRef< CounterMappingRegion > MappingRegions
CoverageData getCoverageForFile(StringRef Filename) const
Get the coverage for a particular file.
Iterator over Functions, optionally filtered to a single file.
A GapRegion is like a CodeRegion, but its count is only set as the line execution count when its the ...
ArrayRef< CounterExpression > Expressions
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
An iterator over the LineCoverageStats objects for lines described by a CoverageData instance...
friend const_iterator begin(StringRef path, Style style)
Get begin iterator over path.
Tagged union holding either a T or a Error.
block placement Basic Block Placement Stats
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name...
std::pair< unsigned, unsigned > LineColPair
void dump(const Counter &C, raw_ostream &OS) const
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Coverage information to be processed or displayed.
static Expected< std::unique_ptr< CoverageMapping > > load(ArrayRef< std::unique_ptr< CoverageMappingReader >> CoverageReaders, IndexedInstrProfReader &ProfileReader)
Load the coverage mapping using the given readers.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Counter add(Counter LHS, Counter RHS)
Return a counter that represents the expression that adds LHS and RHS.
const std::error_category & coveragemap_category()
The execution count information starting at a point in a file.
ArrayRef< StringRef > Filenames
friend const_iterator end(StringRef path)
Get end iterator over path.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Coverage mapping information for a single function.
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
An instantiation group contains a FunctionRecord list, such that each record corresponds to a distinc...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
A CodeRegion associates some code with a counter.
A Counter mapping context is used to connect the counters, expressions and the obtained counter value...
bool IsRegionEntry
Whether this enters a new region or returns to a previous count.
static ManagedStatic< _object_error_category > error_category
LineColPair startLoc() const
static ManagedStatic< CoverageMappingErrorCategoryType > ErrorCategory
Associates a source range with an execution count.
iterator erase(const_iterator CI)
void consumeError(Error Err)
Consume a Error without doing anything.
MutableArrayRef< T > drop_back(size_t N=1) const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Counter subtract(Counter LHS, Counter RHS)
Return a counter that represents the expression that subtracts RHS from LHS.
CoverageData getCoverageForFunction(const FunctionRecord &Function) const
Get the coverage for a particular function.
void sort(IteratorTy Start, IteratorTy End)
Code coverage information for a single function.
static ErrorSuccess success()
Create a success value.
static std::string getCoverageMapErrString(coveragemap_error Err)
Coverage statistics for a single line.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static bool isExpansion(const CountedRegion &R, unsigned FileID)
uint64_t Count
The execution count, or zero if no count was recorded.
bool HasCount
When false, the segment was uninstrumented or skipped.
static Expected< std::unique_ptr< BinaryCoverageReader > > create(std::unique_ptr< MemoryBuffer > &ObjectBuffer, StringRef Arch)
An ExpansionRegion represents a file expansion region that associates a source range with the expansi...
A SkippedRegion represents a source range with code that was skipped by a preprocessor or similar mea...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
The mapping of profile information to coverage data.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
std::vector< InstantiationGroup > getInstantiationGroups(StringRef Filename) const
Get the list of function instantiation groups in a particular file.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
std::string message() const override
Return the error message as a string.
void emplace_back(ArgTypes &&... Args)
unsigned getExpressionID() const
CounterKind getKind() const
LLVM_NODISCARD bool empty() const
static Optional< unsigned > findMainViewFileID(const FunctionRecord &Function)
Return the ID of the file where the definition of the function is located.
Expected< int64_t > evaluate(const Counter &C) const
Return the number of times that a region of code associated with this counter was executed...
std::vector< CountedRegion > CountedRegions
Regions in the function along with their counts.
std::string Name
Raw function name.
unsigned FileID
The abstract file this expansion covers.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool IsGapRegion
Whether this enters a gap region.
unsigned getCounterID() const
LLVM Value Representation.
std::vector< std::string > Filenames
Associated files.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path)
Factory method to create an indexed reader.
Lightweight error class with error context and mandatory checking.
This class implements an extremely fast bulk output stream that can only output to a stream...
StringRef - Represent a constant reference to a string, i.e.
Reader for the indexed binary instrprof format.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
static Counter getExpression(unsigned ExpressionId)
Return the counter that corresponds to a specific addition counter expression.
CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion) const
Get the coverage for an expansion within a coverage set.
A Counter is an abstract value that describes how to compute the execution count for a region of code...
LineCoverageIterator & operator++()
static Counter getCounter(unsigned CounterId)
Return the counter that corresponds to a specific profile counter.
const FunctionRecord & Function
Coverage for the expansion.
bool empty() const
empty - Check if the array is empty.
std::vector< StringRef > getUniqueSourceFiles() const
Returns a lexicographically sorted, unique list of files that are covered.
detail::enumerator< R > enumerate(R &&TheRange)
Given an input range, returns a new range whose values are are pair (A,B) such that A is the 0-based ...
Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash, std::vector< uint64_t > &Counts)
Fill Counts with the profile data for the given function name.
Coverage information for a macro expansion or #included file.