41#include <system_error>
48#define DEBUG_TYPE "coverage-mapping"
51 auto [It, Inserted] = ExpressionIndices.try_emplace(
E, Expressions.size());
53 Expressions.push_back(
E);
57void CounterExpressionBuilder::extractTerms(
Counter C,
int Factor,
58 SmallVectorImpl<Term> &Terms) {
59 switch (
C.getKind()) {
66 const auto &
E = Expressions[
C.getExpressionID()];
67 extractTerms(
E.LHS, Factor, Terms);
74Counter 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)
128 return Simplify ?
simplify(Cnt) : Cnt;
134 return Simplify ?
simplify(Cnt) : Cnt;
139 if (
auto I = Map.find(
C);
I != Map.end())
142 if (!
C.isExpression())
145 auto CE = Expressions[
C.getExpressionID()];
146 auto NewLHS =
subst(CE.LHS, Map);
147 auto NewRHS =
subst(CE.RHS, Map);
152 C =
add(NewLHS, NewRHS);
163 switch (
C.getKind()) {
168 OS <<
'#' <<
C.getCounterID();
171 if (
C.getExpressionID() >= Expressions.size())
173 const auto &E = Expressions[
C.getExpressionID()];
182 if (CounterValues.empty())
185 if (
auto E =
Value.takeError()) {
189 OS <<
'[' << *
Value <<
']';
200 } VisitCount = KNeverVisited;
203 std::stack<StackElem> CounterStack;
204 CounterStack.push({
C});
206 int64_t LastPoppedValue;
208 while (!CounterStack.empty()) {
209 StackElem &Current = CounterStack.top();
211 switch (Current.ICounter.getKind()) {
217 if (Current.ICounter.getCounterID() >= CounterValues.size())
219 LastPoppedValue = CounterValues[Current.ICounter.getCounterID()];
223 if (Current.ICounter.getExpressionID() >= Expressions.size())
225 const auto &E = Expressions[Current.ICounter.getExpressionID()];
226 if (Current.VisitCount == StackElem::KNeverVisited) {
227 CounterStack.push(StackElem{E.LHS});
228 Current.VisitCount = StackElem::KVisitedOnce;
229 }
else if (Current.VisitCount == StackElem::KVisitedOnce) {
230 Current.LHS = LastPoppedValue;
231 CounterStack.push(StackElem{E.RHS});
232 Current.VisitCount = StackElem::KVisitedTwice;
234 int64_t LHS = Current.LHS;
235 int64_t RHS = LastPoppedValue;
245 return LastPoppedValue;
253 if (IndependencePairs)
256 IndependencePairs.emplace();
258 unsigned NumTVs = TV.size();
260 unsigned TVTrueIdx = std::distance(
263 [&](
auto I) { return (I.second == MCDCRecord::MCDC_True); })
266 for (
unsigned I = TVTrueIdx;
I < NumTVs; ++
I) {
267 const auto &[
A, ACond] = TV[
I];
269 for (
unsigned J = 0; J < TVTrueIdx; ++J) {
270 const auto &[
B, BCond] = TV[J];
274 auto AB =
A.getDifferences(
B);
276 IndependencePairs->insert(
277 {AB.find_first(), std::make_pair(J + 1,
I + 1)});
286 auto N = NextIDs.
size();
288 for (
unsigned ID = 0; ID <
N; ++ID) {
289 for (
unsigned C = 0;
C < 2; ++
C) {
293 auto NextID = NextIDs[ID][
C];
294 Nodes[ID].NextIDs[
C] = NextID;
296 ++Nodes[NextID].InCount;
310 assert(Nodes[0].InCount == 0);
316 auto IID = Q.
begin();
319 auto &
Node = Nodes[ID];
322 for (
unsigned I = 0;
I < 2; ++
I) {
323 auto NextID =
Node.NextIDs[
I];
324 assert(NextID != 0 &&
"NextID should not point to the top");
327 Decisions.emplace_back(-
Node.Width, Ord++, ID,
I);
328 assert(Ord == Decisions.size());
333 auto &NextNode = Nodes[NextID];
334 assert(NextNode.InCount > 0);
339 auto NextWidth = int64_t(NextNode.Width) +
Node.Width;
344 NextNode.Width = NextWidth;
348 if (--NextNode.InCount == 0)
357 for (
auto [NegWidth, Ord, ID,
C] : Decisions) {
358 int Width = -NegWidth;
359 assert(Nodes[ID].Width == Width);
360 assert(Nodes[ID].NextIDs[
C] < 0);
374 for (
const auto &Idxs :
Indices)
375 for (
auto Idx : Idxs)
385class NextIDsBuilder {
391 : NextIDs(Branches.
size()) {
395 for (
const auto *Branch : Branches) {
396 const auto &BranchParams = Branch->getBranchParams();
397 assert(SeenIDs.
insert(BranchParams.ID).second &&
"Duplicate CondID");
398 NextIDs[BranchParams.ID] = BranchParams.Conds;
420 unsigned NumConditions;
432 : MCDCCond(MCDCCond), BIdx(BIdx), Ord(Ord) {}
435 return (std::tie(this->MCDCCond, this->BIdx, this->Ord) <
436 std::tie(
RHS.MCDCCond,
RHS.BIdx,
RHS.Ord));
440 std::vector<TVIdxTuple> ExecVectorIdxs;
441 std::vector<TVIdxTuple> NotExecVectorIdxs;
450 DenseSet<unsigned> TVIdxs;
456 MCDCRecordProcessor(
const BitVector &Bitmap,
457 const CounterMappingRegion &Region,
460 : NextIDsBuilder(Branches), TVIdxBuilder(this->NextIDs), Bitmap(Bitmap),
462 Branches(Branches), NumConditions(DecisionParams.NumConditions),
463 Folded{{BitVector(NumConditions), BitVector(NumConditions)}},
464 IsVersion11(IsVersion11) {}
475 TV.
set(ID, MCDCCond);
476 auto NextID = NextIDs[
ID][MCDCCond];
477 auto NextTVIdx = TVIdx + Indices[
ID][MCDCCond];
478 assert(NextID == SavedNodes[ID].NextIDs[MCDCCond]);
480 buildTestVector(TV, NextID, NextTVIdx);
484 assert(TVIdx < SavedNodes[ID].Width);
485 assert(TVIdxs.insert(NextTVIdx).second &&
"Duplicate TVIdx");
490 : DecisionParams.
BitmapIdx - NumTestVectors + NextTVIdx];
492 ExecVectorIdxs.emplace_back(MCDCCond, NextTVIdx, ExecVectors.size());
496 ExecVectors.push_back({TV, MCDCCond});
498 NotExecVectorIdxs.emplace_back(MCDCCond, NextTVIdx,
499 NotExecVectors.size());
500 NotExecVectors.push_back({TV, MCDCCond});
511 void findTestVectors() {
516 MCDCRecord::TestVector TV(NumConditions);
517 buildTestVector(TV, 0, 0);
518 assert(TVIdxs.size() ==
unsigned(NumTestVectors) &&
519 "TVIdxs wasn't fulfilled");
523 for (
const auto &IdxTuple : ExecVectorIdxs)
524 NewExec.
push_back(std::move(ExecVectors[IdxTuple.Ord]));
525 ExecVectors = std::move(NewExec);
529 for (
const auto &IdxTuple : NotExecVectorIdxs)
530 NewNotExec.
push_back(std::move(NotExecVectors[IdxTuple.Ord]));
531 NotExecVectors = std::move(NewNotExec);
544 MCDCRecord processMCDCRecord() {
559 const auto &BranchParams =
B->getBranchParams();
560 PosToID[
I] = BranchParams.ID;
561 CondLoc[
I] =
B->startLoc();
562 Folded[
false][
I] =
B->FalseCount.isZero();
563 Folded[
true][
I] =
B->Count.isZero();
570 return MCDCRecord(Region, std::move(ExecVectors), std::move(NotExecVectors),
571 std::move(
Folded), std::move(PosToID),
582 MCDCRecordProcessor MCDCProcessor(Bitmap,
Region, Branches, IsVersion11);
583 return MCDCProcessor.processMCDCRecord();
594 } VisitCount = KNeverVisited;
597 std::stack<StackElem> CounterStack;
598 CounterStack.push({
C});
600 int64_t LastPoppedValue;
602 while (!CounterStack.empty()) {
603 StackElem &Current = CounterStack.top();
605 switch (Current.ICounter.getKind()) {
611 LastPoppedValue = Current.ICounter.getCounterID();
615 if (Current.ICounter.getExpressionID() >= Expressions.size()) {
619 const auto &E = Expressions[Current.ICounter.getExpressionID()];
620 if (Current.VisitCount == StackElem::KNeverVisited) {
621 CounterStack.push(StackElem{E.LHS});
622 Current.VisitCount = StackElem::KVisitedOnce;
623 }
else if (Current.VisitCount == StackElem::KVisitedOnce) {
624 Current.LHS = LastPoppedValue;
625 CounterStack.push(StackElem{E.RHS});
626 Current.VisitCount = StackElem::KVisitedTwice;
628 int64_t LHS = Current.LHS;
629 int64_t RHS = LastPoppedValue;
630 LastPoppedValue = std::max(LHS, RHS);
639 return LastPoppedValue;
642void FunctionRecordIterator::skipOtherFiles() {
643 while (Current != Records.
end() && !
Filename.empty() &&
646 if (Current == Records.
end())
653 auto RecordIt = FilenameHash2RecordIndices.find(FilenameHash);
654 if (RecordIt == FilenameHash2RecordIndices.end())
656 return RecordIt->second;
661 unsigned MaxCounterID = 0;
663 MaxCounterID = std::max(MaxCounterID, Ctx.getMaxCounterID(
Region.Count));
666 std::max(MaxCounterID, Ctx.getMaxCounterID(
Region.FalseCount));
674 unsigned MaxBitmapIdx = 0;
675 unsigned NumConditions = 0;
682 const auto &DecisionParams =
Region.getDecisionParams();
683 if (MaxBitmapIdx <= DecisionParams.
BitmapIdx) {
690 MaxBitmapIdx = MaxBitmapIdx * CHAR_BIT +
699struct CountedRegionEmitter {
701 struct DecisionRecord {
702 const CounterMappingRegion *DecisionRegion;
703 unsigned NumConditions;
710 DecisionRecord(
const CounterMappingRegion &Decision)
711 : DecisionRegion(&Decision),
712 NumConditions(Decision.getDecisionParams().NumConditions) {
716 bool pushBranch(
const CounterMappingRegion &
B) {
721 assert(MCDCBranches.
size() <= NumConditions &&
722 "MCDCBranch exceeds NumConds");
723 return (MCDCBranches.
size() == NumConditions);
727 const CoverageMappingRecord &
Record;
728 CounterMappingContext &Ctx;
733 std::map<Counter, uint64_t> CounterValues;
741 unsigned LastIndex = 0;
744 bool IsExpanded =
false;
748 std::vector<FileInfo>
Files;
750 DenseSet<unsigned> Visited;
753 CountedRegionEmitter(
const CoverageMappingRecord &Record,
754 CounterMappingContext &Ctx, FunctionRecord &
Function,
760 if (Region.FileID >= Files.size()) {
762 Files.resize(Region.FileID + 1);
764 Files[
Region.FileID].LastIndex =
I + 1;
766 if (Region.ExpandedFileID >= Files.size()) {
768 Files.resize(Region.ExpandedFileID + 1);
770 Files[
Region.ExpandedFileID].IsExpanded =
true;
776 Error evaluateAndCacheCounter(Counter
C) {
777 if (CounterValues.count(
C) > 0)
782 return ValueOrErr.takeError();
783 CounterValues[
C] = *ValueOrErr;
787 Error walk(
unsigned Idx) {
792 assert(Visited.
insert(Idx).second &&
"Duplicate Expansions");
793 for (
unsigned I =
B;
I !=
E; ++
I) {
799 if (
auto E = walk(
Region.ExpandedFileID))
802 if (
auto E = evaluateAndCacheCounter(
Region.Count))
809 assert(!DecisionStack.
empty() &&
"Orphan MCDCBranch");
810 auto &
D = DecisionStack.
back();
812 if (
D.pushBranch(Region)) {
815 *
D.DecisionRegion,
D.MCDCBranches, IsVersion11);
817 return RecordOrErr.takeError();
820 Function.pushMCDCRecord(std::move(*RecordOrErr));
827 if (
auto E = evaluateAndCacheCounter(
Region.FalseCount))
831 assert((Idx != 0 || DecisionStack.
empty()) &&
"Decision wasn't closed");
836 Error emitCountedRegions() {
842 if (
auto E = walk(
I))
848 for (
const auto &Region :
Record.MappingRegions) {
854 CounterValues[
Region.FalseCount]);
859 auto ByFileID = [](
const CountedRegion &
L,
const CountedRegion &
R) {
860 return L.FileID <
R.FileID;
863 "CountedRegions must be sorted by FileID");
865 "CountedBranchRegions must be sorted by FileID");
874Error CoverageMapping::loadFunctionRecord(
875 const CoverageMappingRecord &Record,
876 const std::optional<std::reference_wrapper<IndexedInstrProfReader>>
878 StringRef OrigFuncName =
Record.FunctionName;
879 if (OrigFuncName.
empty())
881 "record function name is empty");
883 if (
Record.Filenames.empty())
888 CounterMappingContext Ctx(
Record.Expressions);
890 std::vector<uint64_t> Counts;
892 if (
Error E = ProfileReader.value().get().getFunctionCounts(
896 FuncHashMismatches.emplace_back(std::string(
Record.FunctionName),
910 ProfileReader && ProfileReader.value().get().getVersion() <
915 if (
Error E = ProfileReader.value().get().getFunctionBitmap(
919 FuncHashMismatches.emplace_back(std::string(
Record.FunctionName),
932 assert(!
Record.MappingRegions.empty() &&
"Function has no regions");
939 if (
Record.MappingRegions.size() == 1 &&
940 Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
946 if (
auto E = CountedRegionEmitter(Record, Ctx,
Function, IsVersion11)
947 .emitCountedRegions()) {
948 errs() <<
"warning: " <<
Record.FunctionName <<
": ";
955 if (!RecordProvenance[FilenamesHash].insert(
hash_value(OrigFuncName)).second)
958 Functions.push_back(std::move(
Function));
963 unsigned RecordIndex = Functions.size() - 1;
969 if (RecordIndices.empty() || RecordIndices.back() != RecordIndex)
970 RecordIndices.push_back(RecordIndex);
978Error CoverageMapping::loadFromReaders(
979 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
980 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
982 CoverageMapping &Coverage) {
985 ProfileReader.value().get().hasSingleByteCoverage());
987 !ProfileReader || ProfileReader.value().get().hasSingleByteCoverage();
988 for (
const auto &CoverageReader : CoverageReaders) {
989 for (
auto RecordOrErr : *CoverageReader) {
990 if (
Error E = RecordOrErr.takeError())
992 const auto &
Record = *RecordOrErr;
1001 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
1002 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
1004 auto Coverage = std::unique_ptr<CoverageMapping>(
new CoverageMapping());
1005 if (
Error E = loadFromReaders(CoverageReaders, ProfileReader, *Coverage))
1006 return std::move(E);
1007 return std::move(Coverage);
1019Error CoverageMapping::loadFromFile(
1020 StringRef
Filename, StringRef Arch, StringRef CompilationDir,
1021 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
1023 CoverageMapping &Coverage,
bool &DataFound,
1024 SmallVectorImpl<object::BuildID> *FoundBinaryIDs) {
1027 if (std::error_code EC = CovMappingBufOrErr.getError())
1029 MemoryBufferRef CovMappingBufRef =
1030 CovMappingBufOrErr.get()->getMemBufferRef();
1035 CovMappingBufRef, Arch, Buffers, CompilationDir,
1036 FoundBinaryIDs ? &BinaryIDs :
nullptr);
1037 if (
Error E = CoverageReadersOrErr.takeError()) {
1045 for (
auto &Reader : CoverageReadersOrErr.get())
1047 if (FoundBinaryIDs && !Readers.
empty()) {
1053 DataFound |= !Readers.
empty();
1054 if (
Error E = loadFromReaders(Readers, ProfileReader, Coverage))
1064 std::unique_ptr<IndexedInstrProfReader> ProfileReader;
1065 if (ProfileFilename) {
1066 auto ProfileReaderOrErr =
1068 if (
Error E = ProfileReaderOrErr.takeError())
1070 ProfileReader = std::move(ProfileReaderOrErr.get());
1072 auto ProfileReaderRef =
1074 ? std::optional<std::reference_wrapper<IndexedInstrProfReader>>(
1077 auto Coverage = std::unique_ptr<CoverageMapping>(
new CoverageMapping());
1078 bool DataFound =
false;
1080 auto GetArch = [&](
size_t Idx) {
1083 if (Arches.
size() == 1)
1084 return Arches.
front();
1090 if (
Error E = loadFromFile(File.value(), GetArch(File.index()),
1091 CompilationDir, ProfileReaderRef, *Coverage,
1092 DataFound, &FoundBinaryIDs))
1093 return std::move(E);
1097 std::vector<object::BuildID> ProfileBinaryIDs;
1099 if (
Error E = ProfileReader->readBinaryIds(ProfileBinaryIDs))
1103 if (!ProfileBinaryIDs.empty()) {
1105 return std::lexicographical_compare(
A.begin(),
A.end(),
B.begin(),
1109 std::set_difference(
1110 ProfileBinaryIDs.begin(), ProfileBinaryIDs.end(),
1111 FoundBinaryIDs.
begin(), FoundBinaryIDs.
end(),
1112 std::inserter(BinaryIDsToFetch, BinaryIDsToFetch.
end()), Compare);
1118 if (
Error E = loadFromFile(*Path, Arch, CompilationDir,
1119 ProfileReaderRef, *Coverage, DataFound))
1120 return std::move(E);
1124 if (CheckBinaryIDs) {
1126 ProfileFilename.value(),
1128 "Missing binary ID: " +
1137 join(ObjectFilenames.
begin(), ObjectFilenames.
end(),
", "),
1139 return std::move(Coverage);
1148 [](
const CountedRegion &R,
unsigned ID) {
return R.FileID < ID; });
1149 auto End = std::upper_bound(
1150 Begin, Regions.
end(), FileID,
1151 [](
unsigned ID,
const CountedRegion &R) { return ID < R.FileID; });
1161class FunctionInstantiationSetCollector {
1162 using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
1163 MapT InstantiatedFunctions;
1166 void insert(
const FunctionRecord &
Function,
unsigned FileID) {
1169 assert(!Regions.
empty() &&
"function does not cover the given file");
1170 auto &Functions = InstantiatedFunctions[Regions.
front().startLoc()];
1174 MapT::iterator
begin() {
return InstantiatedFunctions.begin(); }
1175 MapT::iterator
end() {
return InstantiatedFunctions.end(); }
1178class SegmentBuilder {
1179 std::vector<CoverageSegment> &
Segments;
1182 SegmentBuilder(std::vector<CoverageSegment> &Segments) :
Segments(
Segments) {}
1188 void startSegment(
const CountedRegion &Region,
LineColPair StartLoc,
1189 bool IsRegionEntry,
bool EmitSkippedRegion =
false) {
1190 bool HasCount = !EmitSkippedRegion &&
1194 if (!
Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
1196 if (
Last.HasCount == HasCount &&
Last.Count ==
Region.ExecutionCount &&
1197 !
Last.IsRegionEntry)
1202 Segments.emplace_back(StartLoc.first, StartLoc.second,
1203 Region.ExecutionCount, IsRegionEntry,
1206 Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
1210 dbgs() <<
"Segment at " <<
Last.Line <<
":" <<
Last.Col
1211 <<
" (count = " <<
Last.Count <<
")"
1212 << (
Last.IsRegionEntry ?
", RegionEntry" :
"")
1213 << (!
Last.HasCount ?
", Skipped" :
"")
1214 << (
Last.IsGapRegion ?
", Gap" :
"") <<
"\n";
1223 void completeRegionsUntil(std::optional<LineColPair> Loc,
1224 unsigned FirstCompletedRegion) {
1227 auto CompletedRegionsIt = ActiveRegions.
begin() + FirstCompletedRegion;
1228 std::stable_sort(CompletedRegionsIt, ActiveRegions.
end(),
1229 [](
const CountedRegion *L,
const CountedRegion *R) {
1230 return L->endLoc() < R->endLoc();
1234 for (
unsigned I = FirstCompletedRegion + 1,
E = ActiveRegions.
size();
I <
E;
1236 const auto *CompletedRegion = ActiveRegions[
I];
1237 assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
1238 "Completed region ends after start of new region");
1240 const auto *PrevCompletedRegion = ActiveRegions[
I - 1];
1241 auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
1244 if (Loc && CompletedSegmentLoc == *Loc)
1249 if (CompletedSegmentLoc == CompletedRegion->endLoc())
1253 for (
unsigned J =
I + 1; J <
E; ++J)
1254 if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
1255 CompletedRegion = ActiveRegions[J];
1257 startSegment(*CompletedRegion, CompletedSegmentLoc,
false);
1261 if (FirstCompletedRegion &&
Last->endLoc() != *Loc) {
1264 startSegment(*ActiveRegions[FirstCompletedRegion - 1],
Last->endLoc(),
1266 }
else if (!FirstCompletedRegion && (!Loc || *Loc !=
Last->endLoc())) {
1269 startSegment(*
Last,
Last->endLoc(),
false,
true);
1273 ActiveRegions.
erase(CompletedRegionsIt, ActiveRegions.
end());
1277 for (
const auto &CR :
enumerate(Regions)) {
1278 auto CurStartLoc = CR.value().startLoc();
1281 auto CompletedRegions =
1282 std::stable_partition(ActiveRegions.
begin(), ActiveRegions.
end(),
1283 [&](
const CountedRegion *Region) {
1284 return !(Region->endLoc() <= CurStartLoc);
1286 if (CompletedRegions != ActiveRegions.
end()) {
1287 unsigned FirstCompletedRegion =
1288 std::distance(ActiveRegions.
begin(), CompletedRegions);
1289 completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
1295 if (CurStartLoc == CR.value().endLoc()) {
1299 (CR.index() + 1) == Regions.
size() ||
1301 startSegment(ActiveRegions.
empty() ? CR.value() : *ActiveRegions.
back(),
1302 CurStartLoc, !GapRegion, Skipped);
1305 if (Skipped && !ActiveRegions.
empty())
1306 startSegment(*ActiveRegions.
back(), CurStartLoc,
false);
1309 if (CR.index() + 1 == Regions.
size() ||
1310 CurStartLoc != Regions[CR.index() + 1].startLoc()) {
1313 startSegment(CR.value(), CurStartLoc, !GapRegion);
1321 if (!ActiveRegions.
empty())
1322 completeRegionsUntil(std::nullopt, 0);
1327 llvm::sort(Regions, [](
const CountedRegion &
LHS,
const CountedRegion &
RHS) {
1328 if (
LHS.startLoc() !=
RHS.startLoc())
1329 return LHS.startLoc() <
RHS.startLoc();
1330 if (
LHS.endLoc() !=
RHS.endLoc())
1332 return RHS.endLoc() <
LHS.endLoc();
1342 "Unexpected order of region kind values");
1343 return LHS.Kind <
RHS.Kind;
1350 if (Regions.
empty())
1353 auto End = Regions.
end();
1354 for (
auto I = Regions.
begin() + 1;
I !=
End; ++
I) {
1355 if (
Active->startLoc() !=
I->startLoc() ||
1356 Active->endLoc() !=
I->endLoc()) {
1376 Active->ExecutionCount +=
I->ExecutionCount;
1378 return Regions.
drop_back(std::distance(++Active,
End));
1383 static std::vector<CoverageSegment>
1385 std::vector<CoverageSegment>
Segments;
1386 SegmentBuilder Builder(Segments);
1388 sortNestedRegions(Regions);
1392 dbgs() <<
"Combined regions:\n";
1393 for (
const auto &CR : CombinedRegions)
1394 dbgs() <<
" " << CR.LineStart <<
":" << CR.ColumnStart <<
" -> "
1395 << CR.LineEnd <<
":" << CR.ColumnEnd
1396 <<
" (count=" << CR.ExecutionCount <<
")\n";
1399 Builder.buildSegmentsImpl(CombinedRegions);
1405 if (!(
L.Line <
R.Line) && !(
L.Line ==
R.Line &&
L.Col <
R.Col)) {
1406 if (
L.Line ==
R.Line &&
L.Col ==
R.Col && !
L.HasCount)
1409 <<
" followed by " <<
R.Line <<
":" <<
R.Col <<
"\n");
1410 assert(
false &&
"Coverage segments not unique or sorted");
1419struct MergeableCoverageData :
public CoverageData {
1420 std::vector<CountedRegion> CodeRegions;
1425 void addFunctionRegions(
1427 std::function<
bool(
const CounterMappingRegion &CR)> shouldProcess,
1428 std::function<
bool(
const CountedRegion &CR)> shouldExpand) {
1429 for (
const auto &CR :
Function.CountedRegions)
1430 if (shouldProcess(CR)) {
1431 CodeRegions.push_back(CR);
1432 if (shouldExpand(CR))
1433 Expansions.emplace_back(CR,
Function);
1436 for (
const auto &CR :
Function.CountedBranchRegions)
1437 if (shouldProcess(CR))
1438 BranchRegions.push_back(CR);
1440 for (
const auto &MR :
Function.MCDCRecords)
1441 if (shouldProcess(MR.getDecisionRegion()))
1442 MCDCRecords.push_back(MR);
1445 CoverageData buildSegments() {
1446 Segments = SegmentBuilder::buildSegments(CodeRegions);
1447 return CoverageData(std::move(*
this));
1453 std::vector<StringRef> Filenames;
1458 Filenames.erase(
Last, Filenames.end());
1466 if (SourceFile ==
Function.Filenames[
I])
1467 FilenameEquivalence[
I] =
true;
1468 return FilenameEquivalence;
1472static std::optional<unsigned>
1475 return std::nullopt;
1477 for (
const auto &CR :
Function.CountedRegions)
1482 return std::nullopt;
1489static std::optional<unsigned>
1492 if (
I && SourceFile ==
Function.Filenames[*
I])
1494 return std::nullopt;
1502 assert(SingleByteCoverage);
1503 MergeableCoverageData FileCoverage(*SingleByteCoverage,
Filename);
1508 getImpreciseRecordIndicesForFilename(
Filename);
1509 for (
unsigned RecordIndex : RecordIndices) {
1513 FileCoverage.addFunctionRegions(
1515 [&](
auto &CR) {
return (MainFileID &&
isExpansion(CR, *MainFileID)); });
1520 return FileCoverage.buildSegments();
1523std::vector<InstantiationGroup>
1525 FunctionInstantiationSetCollector InstantiationSetCollector;
1529 getImpreciseRecordIndicesForFilename(
Filename);
1530 for (
unsigned RecordIndex : RecordIndices) {
1535 InstantiationSetCollector.insert(
Function, *MainFileID);
1538 std::vector<InstantiationGroup> Result;
1539 for (
auto &InstantiationSet : InstantiationSetCollector) {
1541 InstantiationSet.first.second,
1542 std::move(InstantiationSet.second)};
1543 Result.emplace_back(std::move(IG));
1554 assert(SingleByteCoverage);
1555 MergeableCoverageData FunctionCoverage(*SingleByteCoverage,
1557 FunctionCoverage.addFunctionRegions(
1559 [&](
auto &CR) {
return isExpansion(CR, *MainFileID); });
1564 return FunctionCoverage.buildSegments();
1569 assert(SingleByteCoverage);
1572 std::vector<CountedRegion> Regions;
1573 for (
const auto &CR :
1575 Regions.push_back(CR);
1586 ExpansionCoverage.
Segments = SegmentBuilder::buildSegments(Regions);
1588 return ExpansionCoverage;
1591LineCoverageStats::LineCoverageStats(
1594 : ExecutionCount(0), HasMultipleRegions(
false), Mapped(
false), Line(Line),
1595 LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
1597 unsigned MinRegionCount = 0;
1599 return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
1601 for (
unsigned I = 0;
I < LineSegments.size() && MinRegionCount < 2; ++
I)
1602 if (isStartOfRegion(LineSegments[
I]))
1605 bool StartOfSkippedRegion = !LineSegments.empty() &&
1606 !LineSegments.front()->HasCount &&
1607 LineSegments.front()->IsRegionEntry;
1609 HasMultipleRegions = MinRegionCount > 1;
1611 !StartOfSkippedRegion &&
1612 ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
1616 Mapped |=
any_of(LineSegments, [](
const auto *Seq) {
1617 return Seq->IsRegionEntry && Seq->HasCount;
1627 ExecutionCount = WrappedSegment->Count;
1628 if (!MinRegionCount)
1630 for (
const auto *LS : LineSegments)
1631 if (isStartOfRegion(LS))
1632 ExecutionCount = std::max(ExecutionCount, LS->Count);
1636 if (Next == CD.end()) {
1641 if (Segments.size())
1642 WrappedSegment = Segments.back();
1644 while (Next != CD.end() && Next->Line == Line)
1645 Segments.push_back(&*Next++);
1652 const std::string &ErrMsg =
"") {
1661 OS <<
"end of File";
1664 OS <<
"no coverage data found";
1667 OS <<
"unsupported coverage format version";
1670 OS <<
"truncated coverage data";
1673 OS <<
"malformed coverage data";
1676 OS <<
"failed to decompress coverage data (zlib)";
1679 OS <<
"`-arch` specifier is invalid or missing for universal binary";
1684 if (!ErrMsg.empty())
1685 OS <<
": " << ErrMsg;
1695class CoverageMappingErrorCategoryType :
public std::error_category {
1696 const char *
name()
const noexcept
override {
return "llvm.coveragemap"; }
1697 std::string message(
int IE)
const override {
1709 static CoverageMappingErrorCategoryType ErrorCategory;
1710 return ErrorCategory;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a library for handling Build IDs and using them to find debug info.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static SmallBitVector gatherFileIDs(StringRef SourceFile, const FunctionRecord &Function)
static std::optional< unsigned > findMainViewFileID(const FunctionRecord &Function)
Return the ID of the file where the definition of the function is located.
static bool isExpansion(const CountedRegion &R, unsigned FileID)
static Error handleMaybeNoDataFoundError(Error E)
static unsigned getMaxBitmapSize(const CoverageMappingRecord &Record, bool IsVersion11)
Returns the bit count.
static ArrayRef< CountedRegion > regionsForFileID(ArrayRef< CountedRegion > Regions, unsigned FileID)
Return the subrange of Regions whose FileID is FileID.
static std::string getCoverageMapErrString(coveragemap_error Err, const std::string &ErrMsg="")
static unsigned getMaxCounterID(const CounterMappingContext &Ctx, const CoverageMappingRecord &Record)
This file defines the DenseMap class.
MachineBasicBlock * Folded
if(!TBB||Cond.size()< 1) return false
static constexpr StringLiteral Filename
This file implements the SmallBitVector class.
This file defines the SmallVector class.
Defines the virtual file system interface vfs::FileSystem.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
Get the first element.
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const Twine &RemappingPath="")
Factory method to create an indexed reader.
static std::pair< instrprof_error, std::string > take(Error E)
Consume an Error and return the raw enum value contained within it, and the optional error message.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
MutableArrayRef< T > drop_back(size_t N=1) const
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
LLVM Value Representation.
static Expected< std::vector< std::unique_ptr< BinaryCoverageReader > > > create(MemoryBufferRef ObjectBuffer, StringRef Arch, SmallVectorImpl< std::unique_ptr< MemoryBuffer > > &ObjectFileBuffers, StringRef CompilationDir="", SmallVectorImpl< object::BuildIDRef > *BinaryIDs=nullptr)
LLVM_ABI Counter subtract(Counter LHS, Counter RHS, bool Simplify=true)
Return a counter that represents the expression that subtracts RHS from LHS.
LLVM_ABI Counter add(Counter LHS, Counter RHS, bool Simplify=true)
Return a counter that represents the expression that adds LHS and RHS.
LLVM_ABI Counter subst(Counter C, const SubstMap &Map)
std::map< Counter, Counter > SubstMap
K to V map.
A Counter mapping context is used to connect the counters, expressions and the obtained counter value...
LLVM_ABI Expected< MCDCRecord > evaluateMCDCRegion(const CounterMappingRegion &Region, ArrayRef< const CounterMappingRegion * > Branches, bool IsVersion11)
Return an MCDC record that indicates executed test vectors and condition pairs.
void setCounts(ArrayRef< uint64_t > Counts)
LLVM_ABI Expected< int64_t > evaluate(const Counter &C) const
Return the number of times that a region of code associated with this counter was executed.
void setBitmap(BitVector &&Bitmap_)
LLVM_ABI unsigned getMaxCounterID(const Counter &C) const
LLVM_ABI void dump(const Counter &C, raw_ostream &OS) const
Coverage information to be processed or displayed.
std::vector< CountedRegion > BranchRegions
std::vector< CoverageSegment > Segments
std::vector< ExpansionRecord > Expansions
std::string message() const override
Return the error message as a string.
coveragemap_error get() const
const std::string & getMessage() const
static LLVM_ABI Expected< std::unique_ptr< CoverageMapping > > load(ArrayRef< std::unique_ptr< CoverageMappingReader > > CoverageReaders, std::optional< std::reference_wrapper< IndexedInstrProfReader > > &ProfileReader)
Load the coverage mapping using the given readers.
LLVM_ABI std::vector< StringRef > getUniqueSourceFiles() const
Returns a lexicographically sorted, unique list of files that are covered.
LLVM_ABI CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion) const
Get the coverage for an expansion within a coverage set.
iterator_range< FunctionRecordIterator > getCoveredFunctions() const
Gets all of the functions covered by this profile.
LLVM_ABI CoverageData getCoverageForFunction(const FunctionRecord &Function) const
Get the coverage for a particular function.
LLVM_ABI std::vector< InstantiationGroup > getInstantiationGroups(StringRef Filename) const
Get the list of function instantiation groups in a particular file.
LLVM_ABI CoverageData getCoverageForFile(StringRef Filename) const
Get the coverage for a particular file.
Iterator over Functions, optionally filtered to a single file.
An instantiation group contains a FunctionRecord list, such that each record corresponds to a distinc...
LineCoverageIterator(const CoverageData &CD)
LLVM_ABI LineCoverageIterator & operator++()
Coverage statistics for a single line.
auto getIndex() const
Equivalent to buildTestVector's Index.
void set(int I, CondState Val)
Set the condition Val at position I.
Compute TestVector Indices "TVIdx" from the Conds graph.
static constexpr auto HardMaxTVs
Hard limit of test vectors.
LLVM_ABI TVIdxBuilder(const SmallVectorImpl< ConditionIDs > &NextIDs, int Offset=0)
Calculate and assign Indices.
SmallVector< std::array< int, 2 > > Indices
Output: Index for TestVectors bitmap (These are not CondIDs)
int NumTestVectors
Output: The number of test vectors.
SmallVector< MCDCNode > SavedNodes
This is no longer needed after the assignment.
std::pair< iterator, bool > insert(const ValueT &V)
BuildIDFetcher searches local cache directories for debug info.
virtual Expected< std::string > fetch(BuildIDRef BuildID) const
Returns the path to the debug file with the given build ID.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
The virtual file system interface.
@ Skipped
Validation or recovery was skipped, as it was not needed.
int16_t ConditionID
The ID for MCDCBranch.
std::array< ConditionID, 2 > ConditionIDs
LLVM_ABI const std::error_category & coveragemap_category()
std::pair< unsigned, unsigned > LineColPair
@ invalid_or_missing_arch_specifier
SmallVector< uint8_t, 10 > BuildID
A build ID in binary form.
ArrayRef< uint8_t > BuildIDRef
A reference to a BuildID in binary form.
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
bool operator<(int64_t V1, const APSInt &V2)
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
hash_code hash_value(const FixedPointSemantics &Val)
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
LLVM_ABI StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
auto unique(Range &&R, Predicate P)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
@ no_such_file_or_directory
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
ArrayRef(const T &OneElt) -> ArrayRef< T >
void toHex(ArrayRef< uint8_t > Input, bool LowerCase, SmallVectorImpl< char > &Output)
Convert buffer Input to its hexadecimal representation. The returned string is double the size of Inp...
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
@ End
Run the machine verifier once, at the end of the pipeline.
void consumeError(Error Err)
Consume a Error without doing anything.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Associates a source range with an execution count.
A Counter expression is a value that represents an arithmetic operation with two counters.
A Counter mapping region associates a source range with a specific counter.
@ ExpansionRegion
An ExpansionRegion represents a file expansion region that associates a source range with the expansi...
@ MCDCDecisionRegion
A DecisionRegion represents a top-level boolean expression and is associated with a variable length b...
@ MCDCBranchRegion
A Branch Region can be extended to include IDs to facilitate MC/DC.
@ SkippedRegion
A SkippedRegion represents a source range with code that was skipped by a preprocessor or similar mea...
@ GapRegion
A GapRegion is like a CodeRegion, but its count is only set as the line execution count when its the ...
@ CodeRegion
A CodeRegion associates some code with a counter.
A Counter is an abstract value that describes how to compute the execution count for a region of code...
static Counter getZero()
Return the counter that represents the number zero.
static Counter getCounter(unsigned CounterId)
Return the counter that corresponds to a specific profile counter.
static Counter getExpression(unsigned ExpressionId)
Return the counter that corresponds to a specific addition counter expression.
Coverage mapping information for a single function.
The execution count information starting at a point in a file.
Coverage information for a macro expansion or included file.
Code coverage information for a single function.
llvm::SmallVector< std::pair< TestVector, CondState > > TestVectors
LLVM_ABI void findIndependencePairs()
llvm::DenseMap< unsigned, unsigned > CondIDMap
llvm::DenseMap< unsigned, LineColPair > LineColPairMap
CondState
CondState represents the evaluation of a condition in an executed test vector, which can be True or F...
std::array< BitVector, 2 > BoolVector
unsigned BitmapIdx
Byte Index of Bitmap Coverage Object for a Decision Region.
uint16_t NumConditions
Number of Conditions used for a Decision Region.