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();
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;
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,
1215 return std::nullopt;
1220 FileID FID =
SM.getFileID(AfterLoc);
1226 size_t StartDepth = locationDepth(AfterLoc);
1227 size_t EndDepth = locationDepth(BeforeLoc);
1228 while (!
SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
1229 bool UnnestStart = StartDepth >= EndDepth;
1230 bool UnnestEnd = EndDepth >= StartDepth;
1232 assert(
SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1235 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1240 assert(
SM.isWrittenInSameFile(AfterLoc,
1241 getEndOfFileOrMacro(AfterLoc)));
1243 AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
1245 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1250 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1254 return std::nullopt;
1255 if (!
SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
1256 !SpellingRegion(
SM, AfterLoc, BeforeLoc).isInSourceOrder())
1257 return std::nullopt;
1258 return {{AfterLoc, BeforeLoc}};
1264 if (StartLoc == EndLoc)
1266 assert(SpellingRegion(
SM, StartLoc, EndLoc).isInSourceOrder());
1267 handleFileExit(StartLoc);
1268 size_t Index = pushRegion(Count, StartLoc, EndLoc);
1270 handleFileExit(EndLoc);
1276 std::optional<SourceRange> findAreaStartingFromTo(
SourceLocation StartingLoc,
1280 FileID FID =
SM.getFileID(StartingLoc);
1286 size_t StartDepth = locationDepth(StartingLoc);
1287 size_t EndDepth = locationDepth(BeforeLoc);
1288 while (!
SM.isWrittenInSameFile(StartingLoc, BeforeLoc)) {
1289 bool UnnestStart = StartDepth >= EndDepth;
1290 bool UnnestEnd = EndDepth >= StartDepth;
1292 assert(
SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1295 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1300 assert(
SM.isWrittenInSameFile(StartingLoc,
1301 getStartOfFileOrMacro(StartingLoc)));
1303 StartingLoc = getIncludeOrExpansionLoc(StartingLoc);
1304 assert(StartingLoc.
isValid());
1311 return std::nullopt;
1312 if (!
SM.isWrittenInSameFile(StartingLoc, BeforeLoc) ||
1313 !SpellingRegion(
SM, StartingLoc, BeforeLoc).isInSourceOrder())
1314 return std::nullopt;
1315 return {{StartingLoc, BeforeLoc}};
1319 const auto Skipped = findAreaStartingFromTo(StartLoc, BeforeLoc);
1324 const auto NewStartLoc = Skipped->getBegin();
1325 const auto EndLoc = Skipped->getEnd();
1327 if (NewStartLoc == EndLoc)
1329 assert(SpellingRegion(
SM, NewStartLoc, EndLoc).isInSourceOrder());
1330 handleFileExit(NewStartLoc);
1331 size_t Index = pushRegion(Counter{}, NewStartLoc, EndLoc);
1333 handleFileExit(EndLoc);
1338 struct BreakContinue {
1340 Counter ContinueCount;
1344 CounterCoverageMappingBuilder(
1346 llvm::DenseMap<const Stmt *, unsigned> &CounterMap,
1348 : CoverageMappingBuilder(CVM,
SM, LangOpts), CounterMap(CounterMap),
1349 MCDCState(MCDCState), MCDCBuilder(CVM.getCodeGenModule(), MCDCState) {}
1352 void write(llvm::raw_ostream &OS) {
1354 gatherFileIDs(VirtualFileMapping);
1355 SourceRegionFilter
Filter = emitExpansionRegions();
1356 emitSourceRegions(Filter);
1357 gatherSkippedRegions();
1359 if (MappingRegions.empty())
1362 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
1367 void VisitStmt(
const Stmt *S) {
1368 if (S->getBeginLoc().isValid())
1370 const Stmt *LastStmt =
nullptr;
1371 bool SaveTerminateStmt = HasTerminateStmt;
1372 HasTerminateStmt =
false;
1373 GapRegionCounter = Counter::getZero();
1374 for (
const Stmt *Child : S->children())
1378 if (LastStmt && HasTerminateStmt) {
1379 auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
1381 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
1383 SaveTerminateStmt =
true;
1384 HasTerminateStmt =
false;
1389 if (SaveTerminateStmt)
1390 HasTerminateStmt =
true;
1391 handleFileExit(getEnd(S));
1394 void VisitDecl(
const Decl *D) {
1400 SM.isInSystemHeader(
SM.getSpellingLoc(getStart(Body))))
1407 Counter BodyCounter = getRegionCounter(Body);
1409 if (
auto *Method = dyn_cast<CXXMethodDecl>(D))
1411 if (
auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1415 if (getStart(
Init).isValid() && getEnd(
Init).isValid())
1416 propagateCounts(BodyCounter,
Init);
1421 propagateCounts(BodyCounter, Body,
1423 assert(RegionStack.empty() &&
"Regions entered but never exited");
1428 if (S->getRetValue())
1429 Visit(S->getRetValue());
1435 Visit(S->getBody());
1440 if (S->getOperand())
1441 Visit(S->getOperand());
1452 void VisitGotoStmt(
const GotoStmt *S) { terminateRegion(S); }
1454 void VisitLabelStmt(
const LabelStmt *S) {
1455 Counter LabelCount = getRegionCounter(S);
1458 handleFileExit(Start);
1459 pushRegion(LabelCount, Start);
1460 Visit(S->getSubStmt());
1463 void VisitBreakStmt(
const BreakStmt *S) {
1464 assert(!BreakContinueStack.empty() &&
"break not in a loop or switch!");
1466 BreakContinueStack.back().BreakCount = addCounters(
1467 BreakContinueStack.back().BreakCount,
getRegion().getCounter());
1474 assert(!BreakContinueStack.empty() &&
"continue stmt not in a loop!");
1476 BreakContinueStack.back().ContinueCount = addCounters(
1477 BreakContinueStack.back().ContinueCount,
getRegion().getCounter());
1481 void VisitCallExpr(
const CallExpr *E) {
1491 void VisitWhileStmt(
const WhileStmt *S) {
1494 Counter ParentCount =
getRegion().getCounter();
1496 ? getRegionCounter(S->getBody())
1497 : getRegionCounter(S);
1500 BreakContinueStack.push_back(BreakContinue());
1501 extendRegion(S->getBody());
1502 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1503 BreakContinue BC = BreakContinueStack.pop_back_val();
1505 bool BodyHasTerminateStmt = HasTerminateStmt;
1506 HasTerminateStmt =
false;
1511 ? getRegionCounter(S->getCond())
1512 : addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1513 propagateCounts(CondCount, S->getCond());
1514 adjustForOutOfOrderTraversal(getEnd(S));
1517 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1519 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1523 ? getRegionCounter(S)
1524 : addCounters(BC.BreakCount,
1525 subtractCounters(CondCount, BodyCount));
1527 if (OutCount != ParentCount) {
1528 pushRegion(OutCount);
1529 GapRegionCounter = OutCount;
1530 if (BodyHasTerminateStmt)
1531 HasTerminateStmt =
true;
1536 createBranchRegion(S->getCond(), BodyCount,
1537 subtractCounters(CondCount, BodyCount));
1540 void VisitDoStmt(
const DoStmt *S) {
1543 Counter ParentCount =
getRegion().getCounter();
1545 ? getRegionCounter(S->getBody())
1546 : getRegionCounter(S);
1548 BreakContinueStack.push_back(BreakContinue());
1549 extendRegion(S->getBody());
1551 Counter BackedgeCount;
1553 propagateCounts(BodyCount, S->getBody());
1556 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1558 BreakContinue BC = BreakContinueStack.pop_back_val();
1560 bool BodyHasTerminateStmt = HasTerminateStmt;
1561 HasTerminateStmt =
false;
1564 ? getRegionCounter(S->getCond())
1565 : addCounters(BackedgeCount, BC.ContinueCount);
1566 propagateCounts(CondCount, S->getCond());
1570 ? getRegionCounter(S)
1571 : addCounters(BC.BreakCount,
1572 subtractCounters(CondCount, BodyCount));
1573 if (OutCount != ParentCount) {
1574 pushRegion(OutCount);
1575 GapRegionCounter = OutCount;
1580 createBranchRegion(S->getCond(), BodyCount,
1581 subtractCounters(CondCount, BodyCount));
1583 if (BodyHasTerminateStmt)
1584 HasTerminateStmt =
true;
1587 void VisitForStmt(
const ForStmt *S) {
1590 Visit(S->getInit());
1592 Counter ParentCount =
getRegion().getCounter();
1594 ? getRegionCounter(S->getBody())
1595 : getRegionCounter(S);
1599 BreakContinueStack.emplace_back();
1602 BreakContinueStack.emplace_back();
1603 extendRegion(S->getBody());
1604 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1605 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1607 bool BodyHasTerminateStmt = HasTerminateStmt;
1608 HasTerminateStmt =
false;
1612 BreakContinue IncrementBC;
1613 if (
const Stmt *Inc = S->getInc()) {
1616 IncCount = getRegionCounter(S->getInc());
1618 IncCount = addCounters(BackedgeCount, BodyBC.ContinueCount);
1619 propagateCounts(IncCount, Inc);
1620 IncrementBC = BreakContinueStack.pop_back_val();
1626 ? getRegionCounter(S->getCond())
1628 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1629 IncrementBC.ContinueCount);
1631 if (
const Expr *Cond = S->getCond()) {
1632 propagateCounts(CondCount, Cond);
1633 adjustForOutOfOrderTraversal(getEnd(S));
1637 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1639 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1643 ? getRegionCounter(S)
1644 : addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1645 subtractCounters(CondCount, BodyCount));
1646 if (OutCount != ParentCount) {
1647 pushRegion(OutCount);
1648 GapRegionCounter = OutCount;
1649 if (BodyHasTerminateStmt)
1650 HasTerminateStmt =
true;
1655 createBranchRegion(S->getCond(), BodyCount,
1656 subtractCounters(CondCount, BodyCount));
1662 Visit(S->getInit());
1663 Visit(S->getLoopVarStmt());
1664 Visit(S->getRangeStmt());
1666 Counter ParentCount =
getRegion().getCounter();
1668 ? getRegionCounter(S->getBody())
1669 : getRegionCounter(S);
1671 BreakContinueStack.push_back(BreakContinue());
1672 extendRegion(S->getBody());
1673 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1674 BreakContinue BC = BreakContinueStack.pop_back_val();
1676 bool BodyHasTerminateStmt = HasTerminateStmt;
1677 HasTerminateStmt =
false;
1680 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1682 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1687 OutCount = getRegionCounter(S);
1689 LoopCount = addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1691 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1693 if (OutCount != ParentCount) {
1694 pushRegion(OutCount);
1695 GapRegionCounter = OutCount;
1696 if (BodyHasTerminateStmt)
1697 HasTerminateStmt =
true;
1702 createBranchRegion(S->getCond(), BodyCount,
1703 subtractCounters(LoopCount, BodyCount));
1708 Visit(S->getElement());
1710 Counter ParentCount =
getRegion().getCounter();
1711 Counter BodyCount = getRegionCounter(S);
1713 BreakContinueStack.push_back(BreakContinue());
1714 extendRegion(S->getBody());
1715 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1716 BreakContinue BC = BreakContinueStack.pop_back_val();
1719 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1721 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1724 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1726 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1727 if (OutCount != ParentCount) {
1728 pushRegion(OutCount);
1729 GapRegionCounter = OutCount;
1736 Visit(S->getInit());
1737 Visit(S->getCond());
1739 BreakContinueStack.push_back(BreakContinue());
1741 const Stmt *Body = S->getBody();
1743 if (
const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1744 if (!CS->body_empty()) {
1748 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1753 for (
size_t i = RegionStack.size(); i != Index; --i) {
1754 if (!RegionStack[i - 1].hasEndLoc())
1755 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1761 propagateCounts(Counter::getZero(), Body);
1762 BreakContinue BC = BreakContinueStack.pop_back_val();
1765 BreakContinueStack.back().ContinueCount = addCounters(
1766 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1768 Counter ParentCount =
getRegion().getCounter();
1769 Counter ExitCount = getRegionCounter(S);
1771 pushRegion(ExitCount);
1772 GapRegionCounter = ExitCount;
1776 MostRecentLocation = getStart(S);
1777 handleFileExit(ExitLoc);
1786 Counter CaseCountSum;
1787 bool HasDefaultCase =
false;
1788 const SwitchCase *Case = S->getSwitchCaseList();
1790 HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1792 addCounters(CaseCountSum, getRegionCounter(Case),
false);
1793 createSwitchCaseRegion(
1794 Case, getRegionCounter(Case),
1795 subtractCounters(ParentCount, getRegionCounter(Case)));
1800 CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
1805 if (!HasDefaultCase) {
1806 Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
1807 Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
1808 createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
1817 ? getRegionCounter(S)
1818 : addCounters(
Parent.getCounter(), getRegionCounter(S));
1822 if (
Parent.hasStartLoc() &&
Parent.getBeginLoc() == getStart(S))
1823 Parent.setCounter(Count);
1825 pushRegion(Count, getStart(S));
1827 GapRegionCounter = Count;
1829 if (
const auto *CS = dyn_cast<CaseStmt>(S)) {
1830 Visit(CS->getLHS());
1831 if (
const Expr *RHS = CS->getRHS())
1834 Visit(S->getSubStmt());
1837 void coverIfConsteval(
const IfStmt *S) {
1838 assert(S->isConsteval());
1840 const auto *Then = S->getThen();
1841 const auto *Else = S->getElse();
1846 const Counter ParentCount =
getRegion().getCounter();
1850 if (S->isNegatedConsteval()) {
1852 markSkipped(S->getIfLoc(), getStart(Then));
1853 propagateCounts(ParentCount, Then);
1857 markSkipped(getEnd(Then), getEnd(Else));
1860 assert(S->isNonNegatedConsteval());
1862 markSkipped(S->getIfLoc(), Else ? getStart(Else) : getEnd(Then));
1865 propagateCounts(ParentCount, Else);
1869 void coverIfConstexpr(
const IfStmt *S) {
1870 assert(S->isConstexpr());
1882 const Counter ParentCount =
getRegion().getCounter();
1887 if (
const auto *
Init = S->getInit()) {
1888 const auto start = getStart(
Init);
1889 const auto end = getEnd(
Init);
1893 if (start.isValid() && end.isValid()) {
1894 markSkipped(startOfSkipped, start);
1895 propagateCounts(ParentCount,
Init);
1896 startOfSkipped = getEnd(
Init);
1900 const auto *Then = S->getThen();
1901 const auto *Else = S->getElse();
1905 markSkipped(startOfSkipped, getStart(Then));
1906 propagateCounts(ParentCount, Then);
1910 markSkipped(getEnd(Then), getEnd(Else));
1913 markSkipped(startOfSkipped, Else ? getStart(Else) : getEnd(Then));
1916 propagateCounts(ParentCount, Else);
1920 void VisitIfStmt(
const IfStmt *S) {
1923 if (S->isConsteval())
1924 return coverIfConsteval(S);
1925 else if (S->isConstexpr())
1926 return coverIfConstexpr(S);
1930 Visit(S->getInit());
1934 extendRegion(S->getCond());
1936 Counter ParentCount =
getRegion().getCounter();
1938 ? getRegionCounter(S->getThen())
1939 : getRegionCounter(S);
1943 propagateCounts(ParentCount, S->getCond());
1946 std::optional<SourceRange> Gap =
1947 findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
1949 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
1951 extendRegion(S->getThen());
1952 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1956 ElseCount = subtractCounters(ParentCount, ThenCount);
1957 else if (S->getElse())
1958 ElseCount = getRegionCounter(S->getElse());
1960 if (
const Stmt *Else = S->getElse()) {
1961 bool ThenHasTerminateStmt = HasTerminateStmt;
1962 HasTerminateStmt =
false;
1964 std::optional<SourceRange> Gap =
1965 findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
1967 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
1970 Counter ElseOutCount = propagateCounts(ElseCount, Else);
1972 OutCount = addCounters(OutCount, ElseOutCount);
1974 if (ThenHasTerminateStmt)
1975 HasTerminateStmt =
true;
1977 OutCount = addCounters(OutCount, ElseCount);
1980 OutCount = getRegionCounter(S);
1982 if (OutCount != ParentCount) {
1983 pushRegion(OutCount);
1984 GapRegionCounter = OutCount;
1989 createBranchRegion(S->getCond(), ThenCount,
1990 subtractCounters(ParentCount, ThenCount));
1996 extendRegion(S->getTryBlock());
1998 Counter ParentCount =
getRegion().getCounter();
1999 propagateCounts(ParentCount, S->getTryBlock());
2001 for (
unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
2002 Visit(S->getHandler(I));
2004 Counter ExitCount = getRegionCounter(S);
2005 pushRegion(ExitCount);
2009 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
2015 Counter ParentCount =
getRegion().getCounter();
2018 : getRegionCounter(E);
2021 if (
const auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) {
2022 propagateCounts(ParentCount, BCO->getCommon());
2023 OutCount = TrueCount;
2025 propagateCounts(ParentCount, E->
getCond());
2030 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
2033 OutCount = propagateCounts(TrueCount, E->
getTrueExpr());
2039 : subtractCounters(ParentCount, TrueCount);
2041 Counter FalseOutCount = propagateCounts(FalseCount, E->
getFalseExpr());
2043 OutCount = getRegionCounter(E);
2045 OutCount = addCounters(OutCount, FalseOutCount);
2047 if (OutCount != ParentCount) {
2048 pushRegion(OutCount);
2049 GapRegionCounter = OutCount;
2054 createBranchRegion(E->
getCond(), TrueCount,
2055 subtractCounters(ParentCount, TrueCount));
2059 unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(E);
2063 auto DecisionParams = mcdc::DecisionParameters{
2069 createDecisionRegion(E, DecisionParams);
2073 bool IsRootNode = MCDCBuilder.isIdle();
2076 MCDCBuilder.pushAndAssignIDs(E);
2078 extendRegion(E->
getLHS());
2080 handleFileExit(getEnd(E->
getLHS()));
2083 const auto DecisionLHS = MCDCBuilder.pop();
2086 extendRegion(E->
getRHS());
2087 propagateCounts(getRegionCounter(E), E->
getRHS());
2090 const auto DecisionRHS = MCDCBuilder.back();
2093 Counter RHSExecCnt = getRegionCounter(E);
2096 Counter RHSTrueCnt = getRegionCounter(E->
getRHS());
2099 Counter ParentCnt =
getRegion().getCounter();
2103 createBranchRegion(E->
getLHS(), RHSExecCnt,
2104 subtractCounters(ParentCnt, RHSExecCnt), DecisionLHS);
2108 createBranchRegion(E->
getRHS(), RHSTrueCnt,
2109 subtractCounters(RHSExecCnt, RHSTrueCnt), DecisionRHS);
2117 bool shouldVisitRHS(
const Expr *LHS) {
2118 bool LHSIsTrue =
false;
2119 bool LHSIsConst =
false;
2123 return !LHSIsConst || (LHSIsConst && !LHSIsTrue);
2127 bool IsRootNode = MCDCBuilder.isIdle();
2130 MCDCBuilder.pushAndAssignIDs(E);
2132 extendRegion(E->
getLHS());
2133 Counter OutCount = propagateCounts(
getRegion().getCounter(), E->
getLHS());
2134 handleFileExit(getEnd(E->
getLHS()));
2137 const auto DecisionLHS = MCDCBuilder.pop();
2140 extendRegion(E->
getRHS());
2141 propagateCounts(getRegionCounter(E), E->
getRHS());
2144 const auto DecisionRHS = MCDCBuilder.back();
2147 Counter RHSExecCnt = getRegionCounter(E);
2150 Counter RHSFalseCnt = getRegionCounter(E->
getRHS());
2152 if (!shouldVisitRHS(E->
getLHS())) {
2153 GapRegionCounter = OutCount;
2157 Counter ParentCnt =
getRegion().getCounter();
2161 createBranchRegion(E->
getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
2162 RHSExecCnt, DecisionLHS);
2166 createBranchRegion(E->
getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
2167 RHSFalseCnt, DecisionRHS);
2191static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
2194 OS << FunctionName <<
":\n";
2195 CounterMappingContext Ctx(Expressions);
2196 for (
const auto &R : Regions) {
2199 case CounterMappingRegion::CodeRegion:
2201 case CounterMappingRegion::ExpansionRegion:
2204 case CounterMappingRegion::SkippedRegion:
2207 case CounterMappingRegion::GapRegion:
2210 case CounterMappingRegion::BranchRegion:
2211 case CounterMappingRegion::MCDCBranchRegion:
2214 case CounterMappingRegion::MCDCDecisionRegion:
2219 OS <<
"File " << R.FileID <<
", " << R.LineStart <<
":" << R.ColumnStart
2220 <<
" -> " << R.LineEnd <<
":" << R.ColumnEnd <<
" = ";
2222 if (
const auto *DecisionParams =
2223 std::get_if<mcdc::DecisionParameters>(&R.MCDCParams)) {
2224 OS <<
"M:" << DecisionParams->BitmapIdx;
2225 OS <<
", C:" << DecisionParams->NumConditions;
2227 Ctx.dump(R.Count, OS);
2229 if (R.Kind == CounterMappingRegion::BranchRegion ||
2230 R.Kind == CounterMappingRegion::MCDCBranchRegion) {
2232 Ctx.dump(R.FalseCount, OS);
2236 if (
const auto *BranchParams =
2237 std::get_if<mcdc::BranchParameters>(&R.MCDCParams)) {
2238 OS <<
" [" << BranchParams->ID + 1 <<
","
2239 << BranchParams->Conds[
true] + 1;
2240 OS <<
"," << BranchParams->Conds[
false] + 1 <<
"] ";
2243 if (R.Kind == CounterMappingRegion::ExpansionRegion)
2244 OS <<
" (Expanded file = " << R.ExpandedFileID <<
")";
2251 : CGM(CGM), SourceInfo(SourceInfo) {}
2253std::string CoverageMappingModuleGen::getCurrentDirname() {
2258 llvm::sys::fs::current_path(CWD);
2259 return CWD.str().str();
2262std::string CoverageMappingModuleGen::normalizeFilename(StringRef
Filename) {
2264 llvm::sys::path::remove_dots(Path,
true);
2269 for (
const auto &[From, To] :
2271 if (llvm::sys::path::replace_path_prefix(Path, From, To))
2274 return Path.str().str();
2278 llvm::InstrProfSectKind SK) {
2279 return llvm::getInstrProfSectionName(
2283void CoverageMappingModuleGen::emitFunctionMappingRecord(
2284 const FunctionInfo &Info, uint64_t FilenamesRef) {
2288 std::string FuncRecordName =
"__covrec_" + llvm::utohexstr(Info.NameHash);
2295 FuncRecordName +=
"u";
2298 const uint64_t NameHash = Info.NameHash;
2299 const uint64_t FuncHash = Info.FuncHash;
2300 const std::string &CoverageMapping = Info.CoverageMapping;
2301#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
2302 llvm::Type *FunctionRecordTypes[] = {
2303#include "llvm/ProfileData/InstrProfData.inc"
2305 auto *FunctionRecordTy =
2306 llvm::StructType::get(Ctx,
ArrayRef(FunctionRecordTypes),
2310#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
2311 llvm::Constant *FunctionRecordVals[] = {
2312 #include "llvm/ProfileData/InstrProfData.inc"
2314 auto *FuncRecordConstant =
2315 llvm::ConstantStruct::get(FunctionRecordTy,
ArrayRef(FunctionRecordVals));
2318 auto *FuncRecord =
new llvm::GlobalVariable(
2319 CGM.
getModule(), FunctionRecordTy,
true,
2320 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
2322 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
2324 FuncRecord->setAlignment(llvm::Align(8));
2326 FuncRecord->setComdat(CGM.
getModule().getOrInsertComdat(FuncRecordName));
2333 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
2334 const std::string &CoverageMapping,
bool IsUsed) {
2335 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
2336 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
2339 FunctionNames.push_back(NamePtr);
2348 std::vector<StringRef> Filenames;
2349 std::vector<CounterExpression> Expressions;
2350 std::vector<CounterMappingRegion> Regions;
2351 FilenameStrs.resize(FileEntries.size() + 1);
2352 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2353 for (
const auto &Entry : FileEntries) {
2354 auto I = Entry.second;
2355 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2358 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
2359 Expressions, Regions);
2362 dump(llvm::outs(), NameValue, Expressions, Regions);
2367 if (FunctionRecords.empty())
2370 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
2374 FilenameStrs.resize(FileEntries.size() + 1);
2376 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2377 for (
const auto &Entry : FileEntries) {
2378 auto I = Entry.second;
2379 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2382 std::string Filenames;
2384 llvm::raw_string_ostream OS(Filenames);
2385 CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
2387 auto *FilenamesVal =
2388 llvm::ConstantDataArray::getString(Ctx, Filenames,
false);
2389 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
2392 for (
const FunctionInfo &Info : FunctionRecords)
2393 emitFunctionMappingRecord(Info, FilenamesRef);
2395 const unsigned NRecords = 0;
2396 const size_t FilenamesSize = Filenames.size();
2397 const unsigned CoverageMappingSize = 0;
2398 llvm::Type *CovDataHeaderTypes[] = {
2399#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
2400#include "llvm/ProfileData/InstrProfData.inc"
2402 auto CovDataHeaderTy =
2403 llvm::StructType::get(Ctx,
ArrayRef(CovDataHeaderTypes));
2404 llvm::Constant *CovDataHeaderVals[] = {
2405#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
2406#include "llvm/ProfileData/InstrProfData.inc"
2408 auto CovDataHeaderVal =
2409 llvm::ConstantStruct::get(CovDataHeaderTy,
ArrayRef(CovDataHeaderVals));
2412 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
2413 auto CovDataTy = llvm::StructType::get(Ctx,
ArrayRef(CovDataTypes));
2414 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
2415 auto CovDataVal = llvm::ConstantStruct::get(CovDataTy,
ArrayRef(TUDataVals));
2416 auto CovData =
new llvm::GlobalVariable(
2417 CGM.
getModule(), CovDataTy,
true, llvm::GlobalValue::PrivateLinkage,
2418 CovDataVal, llvm::getCoverageMappingVarName());
2421 CovData->setAlignment(llvm::Align(8));
2426 if (!FunctionNames.empty()) {
2427 auto NamesArrTy = llvm::ArrayType::get(llvm::PointerType::getUnqual(Ctx),
2428 FunctionNames.size());
2429 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
2432 new llvm::GlobalVariable(CGM.
getModule(), NamesArrTy,
true,
2433 llvm::GlobalValue::InternalLinkage, NamesArrVal,
2434 llvm::getCoverageUnusedNamesVarName());
2439 auto It = FileEntries.find(
File);
2440 if (It != FileEntries.end())
2442 unsigned FileID = FileEntries.size() + 1;
2443 FileEntries.insert(std::make_pair(
File,
FileID));
2448 llvm::raw_ostream &OS) {
2449 assert(CounterMap && MCDCState);
2450 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, *MCDCState,
SM,
2452 Walker.VisitDecl(D);
2457 llvm::raw_ostream &OS) {
2458 EmptyCoverageMappingBuilder Walker(CVM,
SM, LangOpts);
2459 Walker.VisitDecl(D);
Defines the Diagnostic-related interfaces.
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
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)
Diagnostic wrappers for TextAPI types for error reporting.
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.