38 #include <system_error>
43 using namespace coverage;
45 #define DEBUG_TYPE "coverage-mapping"
48 auto It = ExpressionIndices.find(E);
49 if (It != ExpressionIndices.end())
51 unsigned I = Expressions.size();
52 Expressions.push_back(E);
53 ExpressionIndices[
E] =
I;
57 void CounterExpressionBuilder::extractTerms(
Counter C,
int Factor,
67 extractTerms(
E.LHS, Factor, Terms);
74 Counter CounterExpressionBuilder::simplify(
Counter ExpressionTree) {
77 extractTerms(ExpressionTree, +1, Terms);
81 if (Terms.
size() == 0)
86 return LHS.CounterID < RHS.CounterID;
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;
104 for (
auto T : Terms) {
107 for (
int I = 0;
I <
T.Factor; ++
I)
116 for (
auto T : Terms) {
119 for (
int I = 0;
I < -
T.Factor; ++
I)
155 if (CounterValues.
empty())
162 OS <<
'[' << *Value <<
']';
189 void FunctionRecordIterator::skipOtherFiles() {
190 while (Current != Records.end() && !Filename.
empty() &&
191 Filename != Current->Filenames[0])
193 if (Current == Records.end())
197 Error CoverageMapping::loadFunctionRecord(
201 if (OrigFuncName.
empty())
210 if (!FunctionNames.
insert(OrigFuncName).second)
215 std::vector<uint64_t> Counts;
220 MismatchedFunctionCount++;
223 return make_error<InstrProfError>(IPE);
226 Ctx.setCounts(Counts);
240 MismatchedFunctionCount++;
244 Functions.push_back(std::move(
Function));
249 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
251 auto Coverage = std::unique_ptr<CoverageMapping>(
new CoverageMapping());
253 for (
const auto &CoverageReader : CoverageReaders)
254 for (
const auto &Record : *CoverageReader)
255 if (
Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
258 return std::move(Coverage);
265 if (
Error E = ProfileReaderOrErr.takeError())
267 auto ProfileReader = std::move(ProfileReaderOrErr.get());
271 for (
StringRef ObjectFilename : ObjectFilenames) {
273 if (std::error_code EC = CovMappingBufOrErr.getError())
275 auto CoverageReaderOrErr =
277 if (
Error E = CoverageReaderOrErr.takeError())
279 Readers.push_back(std::move(CoverageReaderOrErr.get()));
280 Buffers.
push_back(std::move(CovMappingBufOrErr.get()));
282 return load(Readers, *ProfileReader);
291 class FunctionInstantiationSetCollector {
293 std::vector<const FunctionRecord *>>;
294 MapT InstantiatedFunctions;
299 while (
I !=
E &&
I->FileID != FileID)
301 assert(
I !=
E &&
"function does not cover the given file");
302 auto &Functions = InstantiatedFunctions[
I->startLoc()];
303 Functions.push_back(&Function);
306 MapT::iterator
begin() {
return InstantiatedFunctions.
begin(); }
307 MapT::iterator
end() {
return InstantiatedFunctions.
end(); }
310 class SegmentBuilder {
311 std::vector<CoverageSegment> &
Segments;
314 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
317 void startSegment(
unsigned Line,
unsigned Col) {
318 DEBUG(
dbgs() <<
"Top level segment at " << Line <<
":" << Col <<
"\n");
319 Segments.emplace_back(Line, Col,
false);
323 void startSegment(
unsigned Line,
unsigned Col,
bool IsRegionEntry,
329 DEBUG(
dbgs() <<
"Segment at " << Line <<
":" << Col);
335 Segments.emplace_back(Line, Col, IsRegionEntry);
349 ActiveRegions.pop_back();
350 if (ActiveRegions.empty())
351 startSegment(Line, Col);
353 startSegment(Line, Col,
false, *ActiveRegions.back());
357 for (
const auto &Region : Regions) {
359 while (!ActiveRegions.empty() &&
360 ActiveRegions.back()->endLoc() <= Region.
startLoc())
363 ActiveRegions.push_back(&Region);
364 startSegment(Region);
367 while (!ActiveRegions.empty())
375 if (LHS.
startLoc() != RHS.startLoc())
376 return LHS.
startLoc() < RHS.startLoc();
377 if (LHS.
endLoc() != RHS.endLoc())
379 return RHS.endLoc() < LHS.
endLoc();
389 "Unexpected order of region kind values");
390 return LHS.
Kind < RHS.Kind;
399 auto Active = Regions.
begin();
401 for (
auto I = Regions.
begin() + 1;
I !=
End; ++
I) {
402 if (Active->
startLoc() !=
I->startLoc() ||
403 Active->
endLoc() !=
I->endLoc()) {
422 if (
I->Kind == Active->
Kind)
430 static std::vector<CoverageSegment>
432 std::vector<CoverageSegment>
Segments;
433 SegmentBuilder Builder(Segments);
435 sortNestedRegions(Regions);
438 Builder.buildSegmentsImpl(CombinedRegions);
446 std::vector<StringRef> Filenames;
448 Filenames.insert(Filenames.end(), Function.
Filenames.begin(),
450 std::sort(Filenames.begin(), Filenames.end());
451 auto Last = std::unique(Filenames.begin(), Filenames.end());
452 Filenames.erase(Last, Filenames.end());
461 FilenameEquivalence[
I] =
true;
462 return FilenameEquivalence;
470 IsNotExpandedFile[CR.ExpandedFileID] =
false;
471 int I = IsNotExpandedFile.find_first();
482 if (I && SourceFile == Function.
Filenames[*I])
493 std::vector<CountedRegion> Regions;
495 for (
const auto &Function : Functions) {
499 if (FileIDs.test(CR.FileID)) {
500 Regions.push_back(CR);
502 FileCoverage.Expansions.emplace_back(CR, Function);
506 DEBUG(
dbgs() <<
"Emitting segments for file: " << Filename <<
"\n");
507 FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
512 std::vector<const FunctionRecord *>
514 FunctionInstantiationSetCollector InstantiationSetCollector;
515 for (
const auto &Function : Functions) {
519 InstantiationSetCollector.insert(Function, *MainFileID);
522 std::vector<const FunctionRecord *> Result;
523 for (
const auto &InstantiationSet : InstantiationSetCollector) {
524 if (InstantiationSet.second.size() < 2)
526 Result.insert(Result.end(), InstantiationSet.second.begin(),
527 InstantiationSet.second.end());
539 std::vector<CountedRegion> Regions;
541 if (CR.FileID == *MainFileID) {
542 Regions.push_back(CR);
544 FunctionCoverage.Expansions.emplace_back(CR, Function);
547 DEBUG(
dbgs() <<
"Emitting segments for function: " << Function.
Name <<
"\n");
548 FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
550 return FunctionCoverage;
557 std::vector<CountedRegion> Regions;
559 if (CR.FileID == Expansion.
FileID) {
560 Regions.push_back(CR);
562 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.
Function);
565 DEBUG(
dbgs() <<
"Emitting segments for expansion of file " << Expansion.
FileID
567 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
569 return ExpansionCoverage;
577 return "End of File";
579 return "No coverage data found";
581 return "Unsupported coverage format version";
583 return "Truncated coverage data";
585 return "Malformed coverage data";
596 const char *
name()
const noexcept
override {
return "llvm.coveragemap"; }
597 std::string message(
int IE)
const override {
void push_back(const T &Elt)
const_iterator end(StringRef path)
Get end iterator over path.
MutableArrayRef< T > drop_back(size_t N=1) const
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 ...
static Counter getZero()
Return the counter that represents the number zero.
std::vector< const FunctionRecord * > getInstantiations(StringRef Filename) const
Get the list of function instantiations in the file.
Expected< int64_t > evaluate(const Counter &C) const
Return the number of times that a region of code associated with this counter was executed...
static instrprof_error take(Error E)
Consume an Error and return the raw enum value contained within it.
CoverageData getCoverageForFunction(const FunctionRecord &Function) const
Get the coverage for a particular function.
static SmallBitVector gatherFileIDs(StringRef SourceFile, const FunctionRecord &Function)
CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion) const
Get the coverage for an expansion within a coverage set.
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
ArrayRef< CounterExpression > Expressions
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
friend const_iterator begin(StringRef path, Style style)
Get begin iterator over path.
Tagged union holding either a T or a Error.
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name...
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)...
Counter add(Counter LHS, Counter RHS)
Return a counter that represents the expression that adds LHS and RHS.
iterator_range< FunctionRecordIterator > getCoveredFunctions() const
Gets all of the functions covered by this profile.
size_t size() const
size - Get the array size.
const std::error_category & coveragemap_category()
unsigned getExpressionID() const
ArrayRef< StringRef > Filenames
friend const_iterator end(StringRef path)
Get end iterator over path.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Coverage mapping information for a single function.
void dump(const Counter &C, raw_ostream &OS) const
CounterKind getKind() const
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
CoverageData getCoverageForFile(StringRef Filename) const
Get the coverage for a particular file.
A CodeRegion associates some code with a counter.
A Counter mapping context is used to connect the counters, expressions and the obtained counter value...
unsigned getCounterID() const
static ManagedStatic< _object_error_category > error_category
static const unsigned End
static ManagedStatic< CoverageMappingErrorCategoryType > ErrorCategory
Associates a source range with an execution count.
bool empty() const
empty - Check if the array is empty.
std::pair< unsigned, unsigned > startLoc() const
iterator erase(const_iterator CI)
void consumeError(Error Err)
Consume a Error without doing anything.
std::pair< typename base::iterator, bool > insert(StringRef Key)
Counter subtract(Counter LHS, Counter RHS)
Return a counter that represents the expression that subtracts RHS from LHS.
Code coverage information for a single function.
static ErrorSuccess success()
Create a success value.
static std::string getCoverageMapErrString(coveragemap_error Err)
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)
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.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
llvm_unreachable("Unknown RegBank!")
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 "-".
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void emplace_back(ArgTypes &&...Args)
std::string message() const override
Return the error message as a string.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
static Optional< unsigned > findMainViewFileID(const FunctionRecord &Function)
Return the ID of the file where the definition of the function is located.
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())
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.
std::pair< unsigned, unsigned > endLoc() const
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...
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
static Counter getExpression(unsigned ExpressionId)
Return the counter that corresponds to a specific addition counter expression.
std::vector< StringRef > getUniqueSourceFiles() const
Returns a lexicographically sorted, unique list of files that are covered.
A Counter is an abstract value that describes how to compute the execution count for a region of code...
static Counter getCounter(unsigned CounterId)
Return the counter that corresponds to a specific profile counter.
const FunctionRecord & Function
Coverage for the expansion.
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.