20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ProfileData/Coverage/CoverageMapping.h"
23#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
24#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
25#include "llvm/ProfileData/InstrProfReader.h"
26#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/Path.h"
38 llvm::cl::desc(
"Enable single byte coverage"),
39 llvm::cl::Hidden, llvm::cl::init(
false));
43 "emptyline-comment-coverage",
44 llvm::cl::desc(
"Emit emptylines and comment lines as skipped regions (only "
45 "disable it on test)"),
46 llvm::cl::init(
true), llvm::cl::Hidden);
49 "system-headers-coverage",
50 llvm::cl::desc(
"Enable collecting coverage from system headers"),
51 llvm::cl::init(
false), llvm::cl::Hidden);
54using namespace CodeGen;
55using namespace llvm::coverage;
69 if (Tok.
getKind() != clang::tok::eod)
79 PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
80 SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
82 SkippedRanges.back().Range.setEnd(Range.getEnd());
84 SkippedRanges.push_back({Range, RangeKind, PrevTokLoc});
101 if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
102 SkippedRanges.back().NextTokLoc = Loc;
107class SourceMappingRegion {
112 std::optional<Counter> FalseCount;
115 mcdc::Parameters MCDCParams;
118 std::optional<SourceLocation> LocStart;
121 std::optional<SourceLocation> LocEnd;
132 SourceMappingRegion(Counter Count, std::optional<SourceLocation> LocStart,
133 std::optional<SourceLocation> LocEnd,
134 bool GapRegion =
false)
135 : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
136 SkippedRegion(
false) {}
138 SourceMappingRegion(Counter Count, std::optional<Counter> FalseCount,
139 mcdc::Parameters MCDCParams,
140 std::optional<SourceLocation> LocStart,
141 std::optional<SourceLocation> LocEnd,
142 bool GapRegion =
false)
143 : Count(Count), FalseCount(FalseCount), MCDCParams(MCDCParams),
144 LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
145 SkippedRegion(
false) {}
147 SourceMappingRegion(mcdc::Parameters MCDCParams,
148 std::optional<SourceLocation> LocStart,
149 std::optional<SourceLocation> LocEnd)
150 : MCDCParams(MCDCParams), LocStart(LocStart), LocEnd(LocEnd),
153 const Counter &getCounter()
const {
return Count; }
155 const Counter &getFalseCounter()
const {
156 assert(FalseCount &&
"Region has no alternate counter");
160 void setCounter(Counter
C) { Count =
C; }
162 bool hasStartLoc()
const {
return LocStart.has_value(); }
167 assert(LocStart &&
"Region has no start location");
171 bool hasEndLoc()
const {
return LocEnd.has_value(); }
174 assert(Loc.
isValid() &&
"Setting an invalid end location");
179 assert(LocEnd &&
"Region has no end location");
183 bool isGap()
const {
return GapRegion; }
185 void setGap(
bool Gap) { GapRegion = Gap; }
187 bool isSkipped()
const {
return SkippedRegion; }
189 void setSkipped(
bool Skipped) { SkippedRegion = Skipped; }
191 bool isBranch()
const {
return FalseCount.has_value(); }
193 bool isMCDCDecision()
const {
194 const auto *DecisionParams =
195 std::get_if<mcdc::DecisionParameters>(&MCDCParams);
196 assert(!DecisionParams || DecisionParams->NumConditions > 0);
197 return DecisionParams;
200 const auto &getMCDCDecisionParams()
const {
201 return mcdc::getParams<const mcdc::DecisionParameters>(MCDCParams);
204 const mcdc::Parameters &getMCDCParams()
const {
return MCDCParams; }
208struct SpellingRegion {
213 unsigned ColumnStart;
223 LineStart =
SM.getSpellingLineNumber(LocStart);
224 ColumnStart =
SM.getSpellingColumnNumber(LocStart);
225 LineEnd =
SM.getSpellingLineNumber(LocEnd);
226 ColumnEnd =
SM.getSpellingColumnNumber(LocEnd);
230 : SpellingRegion(
SM, R.getBeginLoc(), R.getEndLoc()) {}
234 bool isInSourceOrder()
const {
235 return (LineStart < LineEnd) ||
236 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
242class CoverageMappingBuilder {
250 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
257 std::vector<SourceMappingRegion> SourceRegions;
264 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
269 : CVM(CVM),
SM(
SM), LangOpts(LangOpts) {}
284 return SM.getLocForStartOfFile(
SM.getFileID(Loc));
291 SM.getFileOffset(Loc));
292 return SM.getLocForEndOfFile(
SM.getFileID(Loc));
297 return Loc.
isMacroID() ?
SM.getImmediateExpansionRange(Loc).getBegin()
298 :
SM.getIncludeLoc(
SM.getFileID(Loc));
303 return SM.getBufferName(
SM.getSpellingLoc(Loc)) ==
"<built-in>";
309 Loc = getIncludeOrExpansionLoc(Loc);
312 }
while (!
SM.isInFileID(Loc,
Parent));
319 while (
SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
320 Loc =
SM.getImmediateExpansionRange(Loc).getBegin();
327 while (
SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
328 Loc =
SM.getImmediateExpansionRange(Loc).getBegin();
329 return getPreciseTokenLocEnd(Loc);
338 FileIDMapping.clear();
340 llvm::SmallSet<FileID, 8>
Visited;
342 for (
const auto &Region : SourceRegions) {
357 FileLocs.push_back(std::make_pair(Loc, Depth));
359 llvm::stable_sort(FileLocs, llvm::less_second());
361 for (
const auto &FL : FileLocs) {
363 FileID SpellingFile =
SM.getDecomposedSpellingLoc(Loc).first;
364 auto Entry =
SM.getFileEntryRefForID(SpellingFile);
368 FileIDMapping[
SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
369 Mapping.push_back(CVM.
getFileID(*Entry));
377 auto Mapping = FileIDMapping.find(
SM.getFileID(Loc));
378 if (Mapping != FileIDMapping.end())
379 return Mapping->second.first;
393 SpellingRegion SR{
SM, LocStart, LocEnd};
395 if (PrevTokLoc.
isValid() &&
SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
396 SR.LineStart ==
SM.getSpellingLineNumber(PrevTokLoc))
398 if (NextTokLoc.
isValid() &&
SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
399 SR.LineEnd ==
SM.getSpellingLineNumber(NextTokLoc)) {
403 if (SR.isInSourceOrder())
410 void gatherSkippedRegions() {
414 FileLineRanges.resize(
415 FileIDMapping.size(),
416 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
417 for (
const auto &R : MappingRegions) {
418 FileLineRanges[R.FileID].first =
419 std::min(FileLineRanges[R.FileID].first, R.LineStart);
420 FileLineRanges[R.FileID].second =
421 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
425 for (
auto &I : SkippedRanges) {
427 auto LocStart =
Range.getBegin();
428 auto LocEnd =
Range.getEnd();
429 assert(
SM.isWrittenInSameFile(LocStart, LocEnd) &&
430 "region spans multiple files");
432 auto CovFileID = getCoverageFileID(LocStart);
435 std::optional<SpellingRegion> SR;
437 SR = adjustSkippedRange(
SM, LocStart, LocEnd, I.PrevTokLoc,
439 else if (I.isPPIfElse() || I.isEmptyLine())
440 SR = {
SM, LocStart, LocEnd};
444 auto Region = CounterMappingRegion::makeSkipped(
445 *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
449 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
450 Region.LineEnd <= FileLineRanges[*CovFileID].second)
451 MappingRegions.push_back(Region);
457 void emitSourceRegions(
const SourceRegionFilter &Filter) {
458 for (
const auto &Region : SourceRegions) {
459 assert(Region.hasEndLoc() &&
"incomplete region");
462 assert(
SM.getFileID(LocStart).isValid() &&
"region in invalid file");
467 SM.isInSystemHeader(
SM.getSpellingLoc(LocStart)))
470 auto CovFileID = getCoverageFileID(LocStart);
476 assert(
SM.isWrittenInSameFile(LocStart, LocEnd) &&
477 "region spans multiple files");
483 if (
Filter.count(std::make_pair(LocStart, LocEnd)))
487 SpellingRegion SR{
SM, LocStart, LocEnd};
488 assert(SR.isInSourceOrder() &&
"region start and end out of order");
490 if (Region.isGap()) {
491 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
492 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
493 SR.LineEnd, SR.ColumnEnd));
494 }
else if (Region.isSkipped()) {
495 MappingRegions.push_back(CounterMappingRegion::makeSkipped(
496 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd,
498 }
else if (Region.isBranch()) {
499 MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
500 Region.getCounter(), Region.getFalseCounter(), *CovFileID,
501 SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd,
502 Region.getMCDCParams()));
503 }
else if (Region.isMCDCDecision()) {
504 MappingRegions.push_back(CounterMappingRegion::makeDecisionRegion(
505 Region.getMCDCDecisionParams(), *CovFileID, SR.LineStart,
506 SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
508 MappingRegions.push_back(CounterMappingRegion::makeRegion(
509 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
510 SR.LineEnd, SR.ColumnEnd));
516 SourceRegionFilter emitExpansionRegions() {
517 SourceRegionFilter
Filter;
518 for (
const auto &FM : FileIDMapping) {
524 auto ParentFileID = getCoverageFileID(ParentLoc);
527 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
528 assert(ExpandedFileID &&
"expansion in uncovered file");
531 assert(
SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
532 "region spans multiple files");
533 Filter.insert(std::make_pair(ParentLoc, LocEnd));
535 SpellingRegion SR{
SM, ParentLoc, LocEnd};
536 assert(SR.isInSourceOrder() &&
"region start and end out of order");
537 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
538 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
539 SR.LineEnd, SR.ColumnEnd));
547struct EmptyCoverageMappingBuilder :
public CoverageMappingBuilder {
550 : CoverageMappingBuilder(CVM,
SM, LangOpts) {}
552 void VisitDecl(
const Decl *D) {
558 if (!
SM.isWrittenInSameFile(Start, End)) {
561 FileID StartFileID =
SM.getFileID(Start);
562 FileID EndFileID =
SM.getFileID(End);
563 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
564 Start = getIncludeOrExpansionLoc(Start);
566 "Declaration start location not nested within a known region");
567 StartFileID =
SM.getFileID(Start);
569 while (StartFileID != EndFileID) {
570 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
571 assert(End.isValid() &&
572 "Declaration end location not nested within a known region");
573 EndFileID =
SM.getFileID(End);
576 SourceRegions.emplace_back(Counter(), Start, End);
580 void write(llvm::raw_ostream &OS) {
582 gatherFileIDs(FileIDMapping);
583 emitSourceRegions(SourceRegionFilter());
585 if (MappingRegions.empty())
588 CoverageMappingWriter Writer(FileIDMapping, std::nullopt, MappingRegions);
601struct MCDCCoverageBuilder {
695 mcdc::ConditionID NextID = 0;
696 bool NotMapped =
false;
700 static constexpr mcdc::ConditionIDs DecisionStackSentinel{-1, -1};
709 : CGM(CGM), DecisionStack(1, DecisionStackSentinel),
710 MCDCState(MCDCState) {}
715 bool isIdle()
const {
return (NextID == 0 && !NotMapped); }
720 bool isBuilding()
const {
return (NextID > 0); }
723 void setCondID(
const Expr *Cond, mcdc::ConditionID
ID) {
728 mcdc::ConditionID getCondID(
const Expr *Cond)
const {
729 auto I = MCDCState.
BranchByStmt.find(CodeGenFunction::stripCond(Cond));
737 const mcdc::ConditionIDs &back()
const {
return DecisionStack.back(); }
748 !MCDCState.
DecisionByStmt.contains(CodeGenFunction::stripCond(E)))
755 const mcdc::ConditionIDs &ParentDecision = DecisionStack.back();
760 if (MCDCState.
BranchByStmt.contains(CodeGenFunction::stripCond(E)))
761 setCondID(E->
getLHS(), getCondID(E));
763 setCondID(E->
getLHS(), NextID++);
766 mcdc::ConditionID RHSid = NextID++;
767 setCondID(E->
getRHS(), RHSid);
771 DecisionStack.push_back({ParentDecision[
false], RHSid});
773 DecisionStack.push_back({RHSid, ParentDecision[
true]});
777 mcdc::ConditionIDs pop() {
779 return DecisionStackSentinel;
781 assert(DecisionStack.size() > 1);
782 return DecisionStack.pop_back_val();
792 assert(DecisionStack.size() == 1);
802 unsigned TotalConds = NextID;
813struct CounterCoverageMappingBuilder
814 :
public CoverageMappingBuilder,
817 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
825 MCDCCoverageBuilder MCDCBuilder;
827 CounterExpressionBuilder Builder;
836 bool HasTerminateStmt =
false;
839 Counter GapRegionCounter;
842 Counter subtractCounters(Counter LHS, Counter RHS,
bool Simplify =
true) {
844 "cannot add counters when single byte coverage mode is enabled");
845 return Builder.subtract(LHS, RHS, Simplify);
849 Counter addCounters(Counter LHS, Counter RHS,
bool Simplify =
true) {
851 "cannot add counters when single byte coverage mode is enabled");
852 return Builder.add(LHS, RHS, Simplify);
855 Counter addCounters(Counter C1, Counter C2, Counter C3,
856 bool Simplify =
true) {
858 "cannot add counters when single byte coverage mode is enabled");
859 return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
865 Counter getRegionCounter(
const Stmt *S) {
866 return Counter::getCounter(CounterMap[S]);
873 size_t pushRegion(Counter Count,
874 std::optional<SourceLocation> StartLoc = std::nullopt,
875 std::optional<SourceLocation> EndLoc = std::nullopt,
876 std::optional<Counter> FalseCount = std::nullopt,
877 const mcdc::Parameters &BranchParams = std::monostate()) {
879 if (StartLoc && !FalseCount) {
880 MostRecentLocation = *StartLoc;
885 assert((!StartLoc || StartLoc->isValid()) &&
"Start location is not valid");
886 assert((!EndLoc || EndLoc->isValid()) &&
"End location is not valid");
892 if (StartLoc && StartLoc->isInvalid())
893 StartLoc = std::nullopt;
894 if (EndLoc && EndLoc->isInvalid())
895 EndLoc = std::nullopt;
896 RegionStack.emplace_back(Count, FalseCount, BranchParams, StartLoc, EndLoc);
898 return RegionStack.size() - 1;
901 size_t pushRegion(
const mcdc::DecisionParameters &DecisionParams,
902 std::optional<SourceLocation> StartLoc = std::nullopt,
903 std::optional<SourceLocation> EndLoc = std::nullopt) {
905 RegionStack.emplace_back(DecisionParams, StartLoc, EndLoc);
907 return RegionStack.size() - 1;
913 Loc = getIncludeOrExpansionLoc(Loc);
923 void popRegions(
size_t ParentIndex) {
924 assert(RegionStack.size() >= ParentIndex &&
"parent not in stack");
925 while (RegionStack.size() > ParentIndex) {
926 SourceMappingRegion &Region = RegionStack.back();
927 if (Region.hasStartLoc() &&
928 (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
932 : RegionStack[ParentIndex].getEndLoc();
933 bool isBranch = Region.isBranch();
934 size_t StartDepth = locationDepth(StartLoc);
935 size_t EndDepth = locationDepth(EndLoc);
936 while (!
SM.isWrittenInSameFile(StartLoc, EndLoc)) {
937 bool UnnestStart = StartDepth >= EndDepth;
938 bool UnnestEnd = EndDepth >= StartDepth;
947 assert(
SM.isWrittenInSameFile(NestedLoc, EndLoc));
949 if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
950 SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
953 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
955 llvm::report_fatal_error(
956 "File exit not handled before popRegions");
967 assert(
SM.isWrittenInSameFile(StartLoc, NestedLoc));
969 if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
970 SourceRegions.emplace_back(Region.getCounter(), StartLoc,
973 StartLoc = getIncludeOrExpansionLoc(StartLoc);
975 llvm::report_fatal_error(
976 "File exit not handled before popRegions");
980 Region.setStartLoc(StartLoc);
981 Region.setEndLoc(EndLoc);
984 MostRecentLocation = EndLoc;
987 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
988 EndLoc == getEndOfFileOrMacro(EndLoc))
989 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
992 assert(
SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
993 assert(SpellingRegion(
SM, Region).isInSourceOrder());
994 SourceRegions.push_back(Region);
996 RegionStack.pop_back();
1001 SourceMappingRegion &getRegion() {
1002 assert(!RegionStack.empty() &&
"statement has no region");
1003 return RegionStack.back();
1008 Counter propagateCounts(Counter TopCount,
const Stmt *S,
1009 bool VisitChildren =
true) {
1012 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
1015 Counter ExitCount = getRegion().getCounter();
1020 if (
SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
1021 MostRecentLocation = EndLoc;
1027 bool ConditionFoldsToBool(
const Expr *Cond) {
1036 void createBranchRegion(
const Expr *
C, Counter TrueCnt, Counter FalseCnt,
1037 const mcdc::ConditionIDs &Conds = {}) {
1046 if (CodeGenFunction::isInstrumentedCondition(
C)) {
1047 mcdc::Parameters BranchParams;
1048 mcdc::ConditionID
ID = MCDCBuilder.getCondID(
C);
1050 BranchParams = mcdc::BranchParameters{
ID, Conds};
1058 if (ConditionFoldsToBool(
C))
1059 popRegions(pushRegion(Counter::getZero(), getStart(
C), getEnd(
C),
1060 Counter::getZero(), BranchParams));
1063 popRegions(pushRegion(TrueCnt, getStart(
C), getEnd(
C), FalseCnt,
1071 void createDecisionRegion(
const Expr *
C,
1072 const mcdc::DecisionParameters &DecisionParams) {
1073 popRegions(pushRegion(DecisionParams, getStart(
C), getEnd(
C)));
1078 void createSwitchCaseRegion(
const SwitchCase *SC, Counter TrueCnt,
1083 popRegions(pushRegion(TrueCnt, getStart(SC), SC->
getColonLoc(), FalseCnt));
1089 bool isBranch =
false) {
1090 return llvm::any_of(
1091 llvm::reverse(SourceRegions), [&](
const SourceMappingRegion &Region) {
1092 return Region.getBeginLoc() == StartLoc &&
1093 Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
1101 MostRecentLocation = EndLoc;
1107 if (getRegion().hasEndLoc() &&
1108 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
1109 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
1110 MostRecentLocation, getRegion().isBranch()))
1111 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
1121 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
1127 FileID ParentFile =
SM.getFileID(LCA);
1128 while (!isNestedIn(MostRecentLocation, ParentFile)) {
1129 LCA = getIncludeOrExpansionLoc(LCA);
1130 if (LCA.
isInvalid() ||
SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
1133 MostRecentLocation = NewLoc;
1136 ParentFile =
SM.getFileID(LCA);
1139 llvm::SmallSet<SourceLocation, 8> StartLocs;
1140 std::optional<Counter> ParentCounter;
1141 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
1142 if (!I.hasStartLoc())
1145 if (!isNestedIn(Loc, ParentFile)) {
1146 ParentCounter = I.getCounter();
1150 while (!
SM.isInFileID(Loc, ParentFile)) {
1154 if (StartLocs.insert(Loc).second) {
1156 SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(),
1157 I.getMCDCParams(), Loc,
1158 getEndOfFileOrMacro(Loc), I.isBranch());
1160 SourceRegions.emplace_back(I.getCounter(), Loc,
1161 getEndOfFileOrMacro(Loc));
1163 Loc = getIncludeOrExpansionLoc(Loc);
1165 I.setStartLoc(getPreciseTokenLocEnd(Loc));
1168 if (ParentCounter) {
1173 while (isNestedIn(Loc, ParentFile)) {
1175 if (StartLocs.insert(FileStart).second) {
1176 SourceRegions.emplace_back(*ParentCounter, FileStart,
1177 getEndOfFileOrMacro(Loc));
1178 assert(SpellingRegion(
SM, SourceRegions.back()).isInSourceOrder());
1180 Loc = getIncludeOrExpansionLoc(Loc);
1184 MostRecentLocation = NewLoc;
1188 void extendRegion(
const Stmt *S) {
1189 SourceMappingRegion &Region = getRegion();
1192 handleFileExit(StartLoc);
1193 if (!Region.hasStartLoc())
1194 Region.setStartLoc(StartLoc);
1198 void terminateRegion(
const Stmt *S) {
1200 SourceMappingRegion &Region = getRegion();
1202 if (!Region.hasEndLoc())
1203 Region.setEndLoc(EndLoc);
1204 pushRegion(Counter::getZero());
1205 HasTerminateStmt =
true;
1209 std::optional<SourceRange> findGapAreaBetween(
SourceLocation AfterLoc,
1214 FileID FID =
SM.getFileID(AfterLoc);
1220 size_t StartDepth = locationDepth(AfterLoc);
1221 size_t EndDepth = locationDepth(BeforeLoc);
1222 while (!
SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
1223 bool UnnestStart = StartDepth >= EndDepth;
1224 bool UnnestEnd = EndDepth >= StartDepth;
1226 assert(
SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1229 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1234 assert(
SM.isWrittenInSameFile(AfterLoc,
1235 getEndOfFileOrMacro(AfterLoc)));
1237 AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
1239 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1244 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1248 return std::nullopt;
1249 if (!
SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
1250 !SpellingRegion(
SM, AfterLoc, BeforeLoc).isInSourceOrder())
1251 return std::nullopt;
1252 return {{AfterLoc, BeforeLoc}};
1258 if (StartLoc == EndLoc)
1260 assert(SpellingRegion(
SM, StartLoc, EndLoc).isInSourceOrder());
1261 handleFileExit(StartLoc);
1262 size_t Index = pushRegion(Count, StartLoc, EndLoc);
1263 getRegion().setGap(
true);
1264 handleFileExit(EndLoc);
1270 std::optional<SourceRange> findAreaStartingFromTo(
SourceLocation StartingLoc,
1274 FileID FID =
SM.getFileID(StartingLoc);
1280 size_t StartDepth = locationDepth(StartingLoc);
1281 size_t EndDepth = locationDepth(BeforeLoc);
1282 while (!
SM.isWrittenInSameFile(StartingLoc, BeforeLoc)) {
1283 bool UnnestStart = StartDepth >= EndDepth;
1284 bool UnnestEnd = EndDepth >= StartDepth;
1286 assert(
SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1289 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1294 assert(
SM.isWrittenInSameFile(StartingLoc,
1295 getStartOfFileOrMacro(StartingLoc)));
1297 StartingLoc = getIncludeOrExpansionLoc(StartingLoc);
1298 assert(StartingLoc.
isValid());
1305 return std::nullopt;
1306 if (!
SM.isWrittenInSameFile(StartingLoc, BeforeLoc) ||
1307 !SpellingRegion(
SM, StartingLoc, BeforeLoc).isInSourceOrder())
1308 return std::nullopt;
1309 return {{StartingLoc, BeforeLoc}};
1313 const auto Skipped = findAreaStartingFromTo(StartLoc, BeforeLoc);
1318 const auto NewStartLoc = Skipped->getBegin();
1319 const auto EndLoc = Skipped->getEnd();
1321 if (NewStartLoc == EndLoc)
1323 assert(SpellingRegion(
SM, NewStartLoc, EndLoc).isInSourceOrder());
1324 handleFileExit(NewStartLoc);
1325 size_t Index = pushRegion(Counter{}, NewStartLoc, EndLoc);
1326 getRegion().setSkipped(
true);
1327 handleFileExit(EndLoc);
1332 struct BreakContinue {
1334 Counter ContinueCount;
1338 CounterCoverageMappingBuilder(
1340 llvm::DenseMap<const Stmt *, unsigned> &CounterMap,
1342 : CoverageMappingBuilder(CVM,
SM, LangOpts), CounterMap(CounterMap),
1343 MCDCState(MCDCState), MCDCBuilder(CVM.getCodeGenModule(), MCDCState) {}
1346 void write(llvm::raw_ostream &OS) {
1348 gatherFileIDs(VirtualFileMapping);
1349 SourceRegionFilter
Filter = emitExpansionRegions();
1350 emitSourceRegions(Filter);
1351 gatherSkippedRegions();
1353 if (MappingRegions.empty())
1356 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
1361 void VisitStmt(
const Stmt *S) {
1362 if (S->getBeginLoc().isValid())
1364 const Stmt *LastStmt =
nullptr;
1365 bool SaveTerminateStmt = HasTerminateStmt;
1366 HasTerminateStmt =
false;
1367 GapRegionCounter = Counter::getZero();
1368 for (
const Stmt *Child : S->children())
1373 if (LastStmt && HasTerminateStmt && !isa<AttributedStmt>(Child)) {
1374 auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
1376 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
1378 SaveTerminateStmt =
true;
1379 HasTerminateStmt =
false;
1384 if (SaveTerminateStmt)
1385 HasTerminateStmt =
true;
1386 handleFileExit(getEnd(S));
1389 void VisitDecl(
const Decl *D) {
1395 SM.isInSystemHeader(
SM.getSpellingLoc(getStart(Body))))
1402 Counter BodyCounter = getRegionCounter(Body);
1404 if (
auto *Method = dyn_cast<CXXMethodDecl>(D))
1406 if (
auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1410 if (getStart(
Init).isValid() && getEnd(
Init).isValid())
1411 propagateCounts(BodyCounter,
Init);
1416 propagateCounts(BodyCounter, Body,
1418 assert(RegionStack.empty() &&
"Regions entered but never exited");
1423 if (S->getRetValue())
1424 Visit(S->getRetValue());
1430 Visit(S->getBody());
1435 if (S->getOperand())
1436 Visit(S->getOperand());
1447 void VisitGotoStmt(
const GotoStmt *S) { terminateRegion(S); }
1449 void VisitLabelStmt(
const LabelStmt *S) {
1450 Counter LabelCount = getRegionCounter(S);
1453 handleFileExit(Start);
1454 pushRegion(LabelCount, Start);
1455 Visit(S->getSubStmt());
1458 void VisitBreakStmt(
const BreakStmt *S) {
1459 assert(!BreakContinueStack.empty() &&
"break not in a loop or switch!");
1461 BreakContinueStack.back().BreakCount = addCounters(
1462 BreakContinueStack.back().BreakCount, getRegion().getCounter());
1469 assert(!BreakContinueStack.empty() &&
"continue stmt not in a loop!");
1471 BreakContinueStack.back().ContinueCount = addCounters(
1472 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1476 void VisitCallExpr(
const CallExpr *E) {
1486 void VisitWhileStmt(
const WhileStmt *S) {
1489 Counter ParentCount = getRegion().getCounter();
1491 ? getRegionCounter(S->getBody())
1492 : getRegionCounter(S);
1495 BreakContinueStack.push_back(BreakContinue());
1496 extendRegion(S->getBody());
1497 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1498 BreakContinue BC = BreakContinueStack.pop_back_val();
1500 bool BodyHasTerminateStmt = HasTerminateStmt;
1501 HasTerminateStmt =
false;
1506 ? getRegionCounter(S->getCond())
1507 : addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1508 propagateCounts(CondCount, S->getCond());
1509 adjustForOutOfOrderTraversal(getEnd(S));
1512 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1514 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1518 ? getRegionCounter(S)
1519 : addCounters(BC.BreakCount,
1520 subtractCounters(CondCount, BodyCount));
1522 if (OutCount != ParentCount) {
1523 pushRegion(OutCount);
1524 GapRegionCounter = OutCount;
1525 if (BodyHasTerminateStmt)
1526 HasTerminateStmt =
true;
1531 createBranchRegion(S->getCond(), BodyCount,
1532 subtractCounters(CondCount, BodyCount));
1535 void VisitDoStmt(
const DoStmt *S) {
1538 Counter ParentCount = getRegion().getCounter();
1540 ? getRegionCounter(S->getBody())
1541 : getRegionCounter(S);
1543 BreakContinueStack.push_back(BreakContinue());
1544 extendRegion(S->getBody());
1546 Counter BackedgeCount;
1548 propagateCounts(BodyCount, S->getBody());
1551 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1553 BreakContinue BC = BreakContinueStack.pop_back_val();
1555 bool BodyHasTerminateStmt = HasTerminateStmt;
1556 HasTerminateStmt =
false;
1559 ? getRegionCounter(S->getCond())
1560 : addCounters(BackedgeCount, BC.ContinueCount);
1561 propagateCounts(CondCount, S->getCond());
1565 ? getRegionCounter(S)
1566 : addCounters(BC.BreakCount,
1567 subtractCounters(CondCount, BodyCount));
1568 if (OutCount != ParentCount) {
1569 pushRegion(OutCount);
1570 GapRegionCounter = OutCount;
1575 createBranchRegion(S->getCond(), BodyCount,
1576 subtractCounters(CondCount, BodyCount));
1578 if (BodyHasTerminateStmt)
1579 HasTerminateStmt =
true;
1582 void VisitForStmt(
const ForStmt *S) {
1585 Visit(S->getInit());
1587 Counter ParentCount = getRegion().getCounter();
1589 ? getRegionCounter(S->getBody())
1590 : getRegionCounter(S);
1594 BreakContinueStack.emplace_back();
1597 BreakContinueStack.emplace_back();
1598 extendRegion(S->getBody());
1599 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1600 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1602 bool BodyHasTerminateStmt = HasTerminateStmt;
1603 HasTerminateStmt =
false;
1607 BreakContinue IncrementBC;
1608 if (
const Stmt *Inc = S->getInc()) {
1611 IncCount = getRegionCounter(S->getInc());
1613 IncCount = addCounters(BackedgeCount, BodyBC.ContinueCount);
1614 propagateCounts(IncCount, Inc);
1615 IncrementBC = BreakContinueStack.pop_back_val();
1621 ? getRegionCounter(S->getCond())
1623 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1624 IncrementBC.ContinueCount);
1626 if (
const Expr *Cond = S->getCond()) {
1627 propagateCounts(CondCount, Cond);
1628 adjustForOutOfOrderTraversal(getEnd(S));
1632 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1634 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1638 ? getRegionCounter(S)
1639 : addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1640 subtractCounters(CondCount, BodyCount));
1641 if (OutCount != ParentCount) {
1642 pushRegion(OutCount);
1643 GapRegionCounter = OutCount;
1644 if (BodyHasTerminateStmt)
1645 HasTerminateStmt =
true;
1650 createBranchRegion(S->getCond(), BodyCount,
1651 subtractCounters(CondCount, BodyCount));
1657 Visit(S->getInit());
1658 Visit(S->getLoopVarStmt());
1659 Visit(S->getRangeStmt());
1661 Counter ParentCount = getRegion().getCounter();
1663 ? getRegionCounter(S->getBody())
1664 : getRegionCounter(S);
1666 BreakContinueStack.push_back(BreakContinue());
1667 extendRegion(S->getBody());
1668 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1669 BreakContinue BC = BreakContinueStack.pop_back_val();
1671 bool BodyHasTerminateStmt = HasTerminateStmt;
1672 HasTerminateStmt =
false;
1675 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1677 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1682 OutCount = getRegionCounter(S);
1684 LoopCount = addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1686 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1688 if (OutCount != ParentCount) {
1689 pushRegion(OutCount);
1690 GapRegionCounter = OutCount;
1691 if (BodyHasTerminateStmt)
1692 HasTerminateStmt =
true;
1697 createBranchRegion(S->getCond(), BodyCount,
1698 subtractCounters(LoopCount, BodyCount));
1703 Visit(S->getElement());
1705 Counter ParentCount = getRegion().getCounter();
1706 Counter BodyCount = getRegionCounter(S);
1708 BreakContinueStack.push_back(BreakContinue());
1709 extendRegion(S->getBody());
1710 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1711 BreakContinue BC = BreakContinueStack.pop_back_val();
1714 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1716 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1719 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1721 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1722 if (OutCount != ParentCount) {
1723 pushRegion(OutCount);
1724 GapRegionCounter = OutCount;
1731 Visit(S->getInit());
1732 Visit(S->getCond());
1734 BreakContinueStack.push_back(BreakContinue());
1736 const Stmt *Body = S->getBody();
1738 if (
const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1739 if (!CS->body_empty()) {
1743 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1744 getRegion().setGap(
true);
1748 for (
size_t i = RegionStack.size(); i != Index; --i) {
1749 if (!RegionStack[i - 1].hasEndLoc())
1750 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1756 propagateCounts(Counter::getZero(), Body);
1757 BreakContinue BC = BreakContinueStack.pop_back_val();
1760 BreakContinueStack.back().ContinueCount = addCounters(
1761 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1763 Counter ParentCount = getRegion().getCounter();
1764 Counter ExitCount = getRegionCounter(S);
1766 pushRegion(ExitCount);
1767 GapRegionCounter = ExitCount;
1771 MostRecentLocation = getStart(S);
1772 handleFileExit(ExitLoc);
1781 Counter CaseCountSum;
1782 bool HasDefaultCase =
false;
1783 const SwitchCase *Case = S->getSwitchCaseList();
1785 HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1787 addCounters(CaseCountSum, getRegionCounter(Case),
false);
1788 createSwitchCaseRegion(
1789 Case, getRegionCounter(Case),
1790 subtractCounters(ParentCount, getRegionCounter(Case)));
1795 CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
1800 if (!HasDefaultCase) {
1801 Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
1802 Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
1803 createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
1810 SourceMappingRegion &
Parent = getRegion();
1812 ? getRegionCounter(S)
1813 : addCounters(
Parent.getCounter(), getRegionCounter(S));
1817 if (
Parent.hasStartLoc() &&
Parent.getBeginLoc() == getStart(S))
1818 Parent.setCounter(Count);
1820 pushRegion(Count, getStart(S));
1822 GapRegionCounter = Count;
1824 if (
const auto *CS = dyn_cast<CaseStmt>(S)) {
1825 Visit(CS->getLHS());
1826 if (
const Expr *RHS = CS->getRHS())
1829 Visit(S->getSubStmt());
1832 void coverIfConsteval(
const IfStmt *S) {
1833 assert(S->isConsteval());
1835 const auto *Then = S->getThen();
1836 const auto *Else = S->getElse();
1841 const Counter ParentCount = getRegion().getCounter();
1845 if (S->isNegatedConsteval()) {
1847 markSkipped(S->getIfLoc(), getStart(Then));
1848 propagateCounts(ParentCount, Then);
1852 markSkipped(getEnd(Then), getEnd(Else));
1855 assert(S->isNonNegatedConsteval());
1857 markSkipped(S->getIfLoc(), Else ? getStart(Else) : getEnd(Then));
1860 propagateCounts(ParentCount, Else);
1864 void coverIfConstexpr(
const IfStmt *S) {
1865 assert(S->isConstexpr());
1877 const Counter ParentCount = getRegion().getCounter();
1882 if (
const auto *
Init = S->getInit()) {
1883 const auto start = getStart(
Init);
1884 const auto end = getEnd(
Init);
1888 if (start.isValid() && end.isValid()) {
1889 markSkipped(startOfSkipped, start);
1890 propagateCounts(ParentCount,
Init);
1891 startOfSkipped = getEnd(
Init);
1895 const auto *Then = S->getThen();
1896 const auto *Else = S->getElse();
1900 markSkipped(startOfSkipped, getStart(Then));
1901 propagateCounts(ParentCount, Then);
1905 markSkipped(getEnd(Then), getEnd(Else));
1908 markSkipped(startOfSkipped, Else ? getStart(Else) : getEnd(Then));
1911 propagateCounts(ParentCount, Else);
1915 void VisitIfStmt(
const IfStmt *S) {
1918 if (S->isConsteval())
1919 return coverIfConsteval(S);
1920 else if (S->isConstexpr())
1921 return coverIfConstexpr(S);
1925 Visit(S->getInit());
1929 extendRegion(S->getCond());
1931 Counter ParentCount = getRegion().getCounter();
1933 ? getRegionCounter(S->getThen())
1934 : getRegionCounter(S);
1938 propagateCounts(ParentCount, S->getCond());
1941 std::optional<SourceRange> Gap =
1942 findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
1944 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
1946 extendRegion(S->getThen());
1947 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1951 ElseCount = subtractCounters(ParentCount, ThenCount);
1952 else if (S->getElse())
1953 ElseCount = getRegionCounter(S->getElse());
1955 if (
const Stmt *Else = S->getElse()) {
1956 bool ThenHasTerminateStmt = HasTerminateStmt;
1957 HasTerminateStmt =
false;
1959 std::optional<SourceRange> Gap =
1960 findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
1962 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
1965 Counter ElseOutCount = propagateCounts(ElseCount, Else);
1967 OutCount = addCounters(OutCount, ElseOutCount);
1969 if (ThenHasTerminateStmt)
1970 HasTerminateStmt =
true;
1972 OutCount = addCounters(OutCount, ElseCount);
1975 OutCount = getRegionCounter(S);
1977 if (OutCount != ParentCount) {
1978 pushRegion(OutCount);
1979 GapRegionCounter = OutCount;
1984 createBranchRegion(S->getCond(), ThenCount,
1985 subtractCounters(ParentCount, ThenCount));
1991 extendRegion(S->getTryBlock());
1993 Counter ParentCount = getRegion().getCounter();
1994 propagateCounts(ParentCount, S->getTryBlock());
1996 for (
unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1997 Visit(S->getHandler(I));
1999 Counter ExitCount = getRegionCounter(S);
2000 pushRegion(ExitCount);
2004 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
2010 Counter ParentCount = getRegion().getCounter();
2013 : getRegionCounter(E);
2015 propagateCounts(ParentCount, E->
getCond());
2018 if (!isa<BinaryConditionalOperator>(E)) {
2023 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
2026 OutCount = propagateCounts(TrueCount, E->
getTrueExpr());
2028 OutCount = TrueCount;
2034 : subtractCounters(ParentCount, TrueCount);
2036 Counter FalseOutCount = propagateCounts(FalseCount, E->
getFalseExpr());
2038 OutCount = getRegionCounter(E);
2040 OutCount = addCounters(OutCount, FalseOutCount);
2042 if (OutCount != ParentCount) {
2043 pushRegion(OutCount);
2044 GapRegionCounter = OutCount;
2049 createBranchRegion(E->
getCond(), TrueCount,
2050 subtractCounters(ParentCount, TrueCount));
2054 unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(E);
2058 auto DecisionParams = mcdc::DecisionParameters{
2064 createDecisionRegion(E, DecisionParams);
2068 bool IsRootNode = MCDCBuilder.isIdle();
2071 MCDCBuilder.pushAndAssignIDs(E);
2073 extendRegion(E->
getLHS());
2074 propagateCounts(getRegion().getCounter(), E->
getLHS());
2075 handleFileExit(getEnd(E->
getLHS()));
2078 const auto DecisionLHS = MCDCBuilder.pop();
2081 extendRegion(E->
getRHS());
2082 propagateCounts(getRegionCounter(E), E->
getRHS());
2085 const auto DecisionRHS = MCDCBuilder.back();
2088 Counter RHSExecCnt = getRegionCounter(E);
2091 Counter RHSTrueCnt = getRegionCounter(E->
getRHS());
2094 Counter ParentCnt = getRegion().getCounter();
2098 createBranchRegion(E->
getLHS(), RHSExecCnt,
2099 subtractCounters(ParentCnt, RHSExecCnt), DecisionLHS);
2103 createBranchRegion(E->
getRHS(), RHSTrueCnt,
2104 subtractCounters(RHSExecCnt, RHSTrueCnt), DecisionRHS);
2112 bool shouldVisitRHS(
const Expr *LHS) {
2113 bool LHSIsTrue =
false;
2114 bool LHSIsConst =
false;
2118 return !LHSIsConst || (LHSIsConst && !LHSIsTrue);
2122 bool IsRootNode = MCDCBuilder.isIdle();
2125 MCDCBuilder.pushAndAssignIDs(E);
2127 extendRegion(E->
getLHS());
2128 Counter OutCount = propagateCounts(getRegion().getCounter(), E->
getLHS());
2129 handleFileExit(getEnd(E->
getLHS()));
2132 const auto DecisionLHS = MCDCBuilder.pop();
2135 extendRegion(E->
getRHS());
2136 propagateCounts(getRegionCounter(E), E->
getRHS());
2139 const auto DecisionRHS = MCDCBuilder.back();
2142 Counter RHSExecCnt = getRegionCounter(E);
2145 Counter RHSFalseCnt = getRegionCounter(E->
getRHS());
2147 if (!shouldVisitRHS(E->
getLHS())) {
2148 GapRegionCounter = OutCount;
2152 Counter ParentCnt = getRegion().getCounter();
2156 createBranchRegion(E->
getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
2157 RHSExecCnt, DecisionLHS);
2161 createBranchRegion(E->
getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
2162 RHSFalseCnt, DecisionRHS);
2186static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
2189 OS << FunctionName <<
":\n";
2190 CounterMappingContext Ctx(Expressions);
2191 for (
const auto &R : Regions) {
2194 case CounterMappingRegion::CodeRegion:
2196 case CounterMappingRegion::ExpansionRegion:
2199 case CounterMappingRegion::SkippedRegion:
2202 case CounterMappingRegion::GapRegion:
2205 case CounterMappingRegion::BranchRegion:
2206 case CounterMappingRegion::MCDCBranchRegion:
2209 case CounterMappingRegion::MCDCDecisionRegion:
2214 OS <<
"File " << R.FileID <<
", " << R.LineStart <<
":" << R.ColumnStart
2215 <<
" -> " << R.LineEnd <<
":" << R.ColumnEnd <<
" = ";
2217 if (
const auto *DecisionParams =
2218 std::get_if<mcdc::DecisionParameters>(&R.MCDCParams)) {
2219 OS <<
"M:" << DecisionParams->BitmapIdx;
2220 OS <<
", C:" << DecisionParams->NumConditions;
2222 Ctx.dump(R.Count, OS);
2224 if (R.Kind == CounterMappingRegion::BranchRegion ||
2225 R.Kind == CounterMappingRegion::MCDCBranchRegion) {
2227 Ctx.dump(R.FalseCount, OS);
2231 if (
const auto *BranchParams =
2232 std::get_if<mcdc::BranchParameters>(&R.MCDCParams)) {
2233 OS <<
" [" << BranchParams->ID + 1 <<
","
2234 << BranchParams->Conds[
true] + 1;
2235 OS <<
"," << BranchParams->Conds[
false] + 1 <<
"] ";
2238 if (R.Kind == CounterMappingRegion::ExpansionRegion)
2239 OS <<
" (Expanded file = " << R.ExpandedFileID <<
")";
2246 : CGM(CGM), SourceInfo(SourceInfo) {}
2248std::string CoverageMappingModuleGen::getCurrentDirname() {
2253 llvm::sys::fs::current_path(CWD);
2254 return CWD.str().str();
2257std::string CoverageMappingModuleGen::normalizeFilename(StringRef
Filename) {
2259 llvm::sys::path::remove_dots(Path,
true);
2264 for (
const auto &[From, To] :
2266 if (llvm::sys::path::replace_path_prefix(Path, From, To))
2269 return Path.str().str();
2273 llvm::InstrProfSectKind SK) {
2274 return llvm::getInstrProfSectionName(
2278void CoverageMappingModuleGen::emitFunctionMappingRecord(
2279 const FunctionInfo &Info, uint64_t FilenamesRef) {
2283 std::string FuncRecordName =
"__covrec_" + llvm::utohexstr(Info.NameHash);
2290 FuncRecordName +=
"u";
2293 const uint64_t NameHash = Info.NameHash;
2294 const uint64_t FuncHash = Info.FuncHash;
2295 const std::string &CoverageMapping = Info.CoverageMapping;
2296#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
2297 llvm::Type *FunctionRecordTypes[] = {
2298#include "llvm/ProfileData/InstrProfData.inc"
2300 auto *FunctionRecordTy =
2301 llvm::StructType::get(Ctx,
ArrayRef(FunctionRecordTypes),
2305#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
2306 llvm::Constant *FunctionRecordVals[] = {
2307 #include "llvm/ProfileData/InstrProfData.inc"
2309 auto *FuncRecordConstant =
2310 llvm::ConstantStruct::get(FunctionRecordTy,
ArrayRef(FunctionRecordVals));
2313 auto *FuncRecord =
new llvm::GlobalVariable(
2314 CGM.
getModule(), FunctionRecordTy,
true,
2315 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
2317 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
2319 FuncRecord->setAlignment(llvm::Align(8));
2321 FuncRecord->setComdat(CGM.
getModule().getOrInsertComdat(FuncRecordName));
2328 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
2329 const std::string &CoverageMapping,
bool IsUsed) {
2330 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
2331 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
2334 FunctionNames.push_back(NamePtr);
2343 std::vector<StringRef> Filenames;
2344 std::vector<CounterExpression> Expressions;
2345 std::vector<CounterMappingRegion> Regions;
2346 FilenameStrs.resize(FileEntries.size() + 1);
2347 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2348 for (
const auto &Entry : FileEntries) {
2349 auto I = Entry.second;
2350 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2353 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
2354 Expressions, Regions);
2357 dump(llvm::outs(), NameValue, Expressions, Regions);
2362 if (FunctionRecords.empty())
2365 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
2369 FilenameStrs.resize(FileEntries.size() + 1);
2371 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2372 for (
const auto &Entry : FileEntries) {
2373 auto I = Entry.second;
2374 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2377 std::string Filenames;
2379 llvm::raw_string_ostream OS(Filenames);
2380 CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
2382 auto *FilenamesVal =
2383 llvm::ConstantDataArray::getString(Ctx, Filenames,
false);
2384 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
2387 for (
const FunctionInfo &Info : FunctionRecords)
2388 emitFunctionMappingRecord(Info, FilenamesRef);
2390 const unsigned NRecords = 0;
2391 const size_t FilenamesSize = Filenames.size();
2392 const unsigned CoverageMappingSize = 0;
2393 llvm::Type *CovDataHeaderTypes[] = {
2394#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
2395#include "llvm/ProfileData/InstrProfData.inc"
2397 auto CovDataHeaderTy =
2398 llvm::StructType::get(Ctx,
ArrayRef(CovDataHeaderTypes));
2399 llvm::Constant *CovDataHeaderVals[] = {
2400#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
2401#include "llvm/ProfileData/InstrProfData.inc"
2403 auto CovDataHeaderVal =
2404 llvm::ConstantStruct::get(CovDataHeaderTy,
ArrayRef(CovDataHeaderVals));
2407 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
2408 auto CovDataTy = llvm::StructType::get(Ctx,
ArrayRef(CovDataTypes));
2409 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
2410 auto CovDataVal = llvm::ConstantStruct::get(CovDataTy,
ArrayRef(TUDataVals));
2411 auto CovData =
new llvm::GlobalVariable(
2412 CGM.
getModule(), CovDataTy,
true, llvm::GlobalValue::PrivateLinkage,
2413 CovDataVal, llvm::getCoverageMappingVarName());
2416 CovData->setAlignment(llvm::Align(8));
2421 if (!FunctionNames.empty()) {
2422 auto NamesArrTy = llvm::ArrayType::get(llvm::PointerType::getUnqual(Ctx),
2423 FunctionNames.size());
2424 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
2427 new llvm::GlobalVariable(CGM.
getModule(), NamesArrTy,
true,
2428 llvm::GlobalValue::InternalLinkage, NamesArrVal,
2429 llvm::getCoverageUnusedNamesVarName());
2434 auto It = FileEntries.find(
File);
2435 if (It != FileEntries.end())
2437 unsigned FileID = FileEntries.size() + 1;
2438 FileEntries.insert(std::make_pair(
File,
FileID));
2443 llvm::raw_ostream &OS) {
2444 assert(CounterMap && MCDCState);
2445 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, *MCDCState,
SM,
2447 Walker.VisitDecl(D);
2452 llvm::raw_ostream &OS) {
2453 EmptyCoverageMappingBuilder Walker(CVM,
SM, LangOpts);
2454 Walker.VisitDecl(D);
Defines the Diagnostic-related interfaces.
llvm::cl::opt< bool > SystemHeadersCoverage
static std::string getInstrProfSection(const CodeGenModule &CGM, llvm::InstrProfSectKind SK)
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
static llvm::cl::opt< bool > EmptyLineCommentCoverage("emptyline-comment-coverage", llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only " "disable it on test)"), llvm::cl::init(true), llvm::cl::Hidden)
Defines the clang::FileManager interface and associated types.
llvm::DenseSet< const void * > Visited
const TargetInfo & getTargetInfo() const
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
SourceLocation getQuestionLoc() const
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
A builtin binary operation expression such as "x + y" or "x <= y".
BreakStmt - This represents a break.
CXXCatchStmt - This represents a C++ catch block.
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
A C++ throw-expression (C++ [except.throw]).
const Expr * getSubExpr() const
CXXTryStmt - A C++ try block, including all handlers.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
llvm::SmallVector< std::pair< std::string, std::string >, 0 > CoveragePrefixMap
Prefix replacement map for source-based code coverage to remap source file paths in coverage mapping.
std::string CoverageCompilationDir
The string to embed in coverage mapping as the current working directory.
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
ASTContext & getContext() const
bool supportsCOMDAT() const
const CodeGenOptions & getCodeGenOpts() const
llvm::LLVMContext & getLLVMContext()
void emitEmptyMapping(const Decl *D, llvm::raw_ostream &OS)
Emit the coverage mapping data for an unused function.
void emitCounterMapping(const Decl *D, llvm::raw_ostream &OS)
Emit the coverage mapping data which maps the regions of code to counters that will be used to find t...
Organizes the cross-function state that is used while generating code coverage mapping data.
void addFunctionMappingRecord(llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue, uint64_t FunctionHash, const std::string &CoverageMapping, bool IsUsed=true)
Add a function's coverage mapping record to the collection of the function mapping records.
CoverageSourceInfo & getSourceInfo() const
static CoverageSourceInfo * setUpCoverageCallbacks(Preprocessor &PP)
CoverageMappingModuleGen(CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
void emit()
Emit the coverage mapping data for a translation unit.
CodeGenModule & getCodeGenModule()
Return an interface into CodeGenModule.
unsigned getFileID(FileEntryRef File)
Return the coverage mapping translation unit file id for the given file.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
ContinueStmt - This represents a continue.
Represents a 'co_return' statement in the C++ Coroutines TS.
Represents the body of a coroutine.
Stores additional source code information like skipped ranges which is required by the coverage mappi...
void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override
Hook called when a source range is skipped.
void updateNextTokLoc(SourceLocation Loc)
void AddSkippedRange(SourceRange Range, SkippedRange::Kind RangeKind)
std::vector< SkippedRange > & getSkippedRanges()
bool HandleComment(Preprocessor &PP, SourceRange Range) override
SourceLocation PrevTokLoc
void HandleEmptyline(SourceRange Range) override
Decl - This represents one declaration (or definition), e.g.
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
DoStmt - This represents a 'do/while' stmt.
This represents one expression.
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
ForStmt - This represents a 'for (init;cond;inc)' stmt.
GotoStmt - This represents a direct goto.
IfStmt - This represents an if/then/else.
LabelStmt - Represents a label, which has a substatement.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Represents Objective-C's collection statement.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
SourceManager & getSourceManager() const
void setPreprocessToken(bool Preprocess)
void setTokenWatcher(llvm::unique_function< void(const clang::Token &)> F)
Register a function that would be called on each token in the final expanded token stream.
void setEmptylineHandler(EmptylineHandler *Handler)
Set empty line handler.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
A (possibly-)qualified type.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded,...
SourceLocation getExpansionLocStart() const
bool isFunctionMacroExpansion() const
SourceLocation getExpansionLocEnd() const
Stmt - This represents one statement.
SourceLocation getColonLoc() const
const SwitchCase * getNextSwitchCase() const
SwitchStmt - This represents a 'switch' stmt.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Token - This structure provides full information about a lexed token.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
tok::TokenKind getKind() const
WhileStmt - This represents a 'while' stmt.
The JSON file list parser is used to communicate input to InstallAPI.
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
YAML serialization mapping.
cl::opt< bool > EnableSingleByteCoverage
Per-Function MC/DC state.
llvm::DenseMap< const Stmt *, Branch > BranchByStmt
llvm::DenseMap< const Stmt *, Decision > DecisionByStmt
EvalResult is a struct with detailed info about an evaluated expression.