#include "CoverageMappingGen.h"
#include "CodeGenFunction.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ProfileData/Coverage/CoverageMapping.h"
#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
#include "llvm/ProfileData/InstrProfReader.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#define COVMAP_V3
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);
using namespace clang;
using namespace CodeGen;
using namespace llvm::coverage;
CoverageSourceInfo *
CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
CoverageSourceInfo *CoverageInfo =
new CoverageSourceInfo(PP.getSourceManager());
PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
if (EmptyLineCommentCoverage) {
PP.addCommentHandler(CoverageInfo);
PP.setEmptylineHandler(CoverageInfo);
PP.setPreprocessToken(true);
PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
CoverageInfo->PrevTokLoc = Tok.getLocation();
if (Tok.getKind() != clang::tok::eod)
CoverageInfo->updateNextTokLoc(Tok.getLocation());
});
}
return CoverageInfo;
}
void CoverageSourceInfo::AddSkippedRange(SourceRange Range,
SkippedRange::Kind RangeKind) {
if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
Range.getBegin()))
SkippedRanges.back().Range.setEnd(Range.getEnd());
else
SkippedRanges.push_back({Range, RangeKind, PrevTokLoc});
}
void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
AddSkippedRange(Range, SkippedRange::PPIfElse);
}
void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
AddSkippedRange(Range, SkippedRange::EmptyLine);
}
bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
AddSkippedRange(Range, SkippedRange::Comment);
return false;
}
void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
SkippedRanges.back().NextTokLoc = Loc;
}
namespace {
class SourceMappingRegion {
Counter Count;
Optional<Counter> FalseCount;
Optional<SourceLocation> LocStart;
Optional<SourceLocation> LocEnd;
bool GapRegion;
public:
SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Optional<SourceLocation> LocEnd, bool GapRegion = false)
: Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) {
}
SourceMappingRegion(Counter Count, Optional<Counter> FalseCount,
Optional<SourceLocation> LocStart,
Optional<SourceLocation> LocEnd, bool GapRegion = false)
: Count(Count), FalseCount(FalseCount), LocStart(LocStart),
LocEnd(LocEnd), GapRegion(GapRegion) {}
const Counter &getCounter() const { return Count; }
const Counter &getFalseCounter() const {
assert(FalseCount && "Region has no alternate counter");
return *FalseCount;
}
void setCounter(Counter C) { Count = C; }
bool hasStartLoc() const { return LocStart.has_value(); }
void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
SourceLocation getBeginLoc() const {
assert(LocStart && "Region has no start location");
return *LocStart;
}
bool hasEndLoc() const { return LocEnd.has_value(); }
void setEndLoc(SourceLocation Loc) {
assert(Loc.isValid() && "Setting an invalid end location");
LocEnd = Loc;
}
SourceLocation getEndLoc() const {
assert(LocEnd && "Region has no end location");
return *LocEnd;
}
bool isGap() const { return GapRegion; }
void setGap(bool Gap) { GapRegion = Gap; }
bool isBranch() const { return FalseCount.has_value(); }
};
struct SpellingRegion {
unsigned LineStart;
unsigned ColumnStart;
unsigned LineEnd;
unsigned ColumnEnd;
SpellingRegion(SourceManager &SM, SourceLocation LocStart,
SourceLocation LocEnd) {
LineStart = SM.getSpellingLineNumber(LocStart);
ColumnStart = SM.getSpellingColumnNumber(LocStart);
LineEnd = SM.getSpellingLineNumber(LocEnd);
ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
}
SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
: SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
bool isInSourceOrder() const {
return (LineStart < LineEnd) ||
(LineStart == LineEnd && ColumnStart <= ColumnEnd);
}
};
class CoverageMappingBuilder {
public:
CoverageMappingModuleGen &CVM;
SourceManager &SM;
const LangOptions &LangOpts;
private:
llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
FileIDMapping;
public:
llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
std::vector<SourceMappingRegion> SourceRegions;
typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
SourceRegionFilter;
CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
const LangOptions &LangOpts)
: CVM(CVM), SM(SM), LangOpts(LangOpts) {}
SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
unsigned TokLen =
Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
return Loc.getLocWithOffset(TokLen);
}
SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
if (Loc.isMacroID())
return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
return SM.getLocForStartOfFile(SM.getFileID(Loc));
}
SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
if (Loc.isMacroID())
return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
SM.getFileOffset(Loc));
return SM.getLocForEndOfFile(SM.getFileID(Loc));
}
SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
: SM.getIncludeLoc(SM.getFileID(Loc));
}
bool isInBuiltin(SourceLocation Loc) {
return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
}
bool isNestedIn(SourceLocation Loc, FileID Parent) {
do {
Loc = getIncludeOrExpansionLoc(Loc);
if (Loc.isInvalid())
return false;
} while (!SM.isInFileID(Loc, Parent));
return true;
}
SourceLocation getStart(const Stmt *S) {
SourceLocation Loc = S->getBeginLoc();
while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Loc = SM.getImmediateExpansionRange(Loc).getBegin();
return Loc;
}
SourceLocation getEnd(const Stmt *S) {
SourceLocation Loc = S->getEndLoc();
while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Loc = SM.getImmediateExpansionRange(Loc).getBegin();
return getPreciseTokenLocEnd(Loc);
}
void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
FileIDMapping.clear();
llvm::SmallSet<FileID, 8> Visited;
SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
for (const auto &Region : SourceRegions) {
SourceLocation Loc = Region.getBeginLoc();
FileID File = SM.getFileID(Loc);
if (!Visited.insert(File).second)
continue;
if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
continue;
unsigned Depth = 0;
for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
++Depth;
FileLocs.push_back(std::make_pair(Loc, Depth));
}
llvm::stable_sort(FileLocs, llvm::less_second());
for (const auto &FL : FileLocs) {
SourceLocation Loc = FL.first;
FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
auto Entry = SM.getFileEntryForID(SpellingFile);
if (!Entry)
continue;
FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
Mapping.push_back(CVM.getFileID(Entry));
}
}
Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
if (Mapping != FileIDMapping.end())
return Mapping->second.first;
return None;
}
Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
SourceLocation LocStart,
SourceLocation LocEnd,
SourceLocation PrevTokLoc,
SourceLocation NextTokLoc) {
SpellingRegion SR{SM, LocStart, LocEnd};
SR.ColumnStart = 1;
if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
SR.LineStart++;
if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
SR.LineEnd--;
SR.ColumnEnd++;
}
if (SR.isInSourceOrder())
return SR;
return None;
}
void gatherSkippedRegions() {
llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
FileLineRanges.resize(
FileIDMapping.size(),
std::make_pair(std::numeric_limits<unsigned>::max(), 0));
for (const auto &R : MappingRegions) {
FileLineRanges[R.FileID].first =
std::min(FileLineRanges[R.FileID].first, R.LineStart);
FileLineRanges[R.FileID].second =
std::max(FileLineRanges[R.FileID].second, R.LineEnd);
}
auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
for (auto &I : SkippedRanges) {
SourceRange Range = I.Range;
auto LocStart = Range.getBegin();
auto LocEnd = Range.getEnd();
assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
"region spans multiple files");
auto CovFileID = getCoverageFileID(LocStart);
if (!CovFileID)
continue;
Optional<SpellingRegion> SR;
if (I.isComment())
SR = adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc,
I.NextTokLoc);
else if (I.isPPIfElse() || I.isEmptyLine())
SR = {SM, LocStart, LocEnd};
if (!SR)
continue;
auto Region = CounterMappingRegion::makeSkipped(
*CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
SR->ColumnEnd);
if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
Region.LineEnd <= FileLineRanges[*CovFileID].second)
MappingRegions.push_back(Region);
}
}
void emitSourceRegions(const SourceRegionFilter &Filter) {
for (const auto &Region : SourceRegions) {
assert(Region.hasEndLoc() && "incomplete region");
SourceLocation LocStart = Region.getBeginLoc();
assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
continue;
auto CovFileID = getCoverageFileID(LocStart);
if (!CovFileID)
continue;
SourceLocation LocEnd = Region.getEndLoc();
assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
"region spans multiple files");
if (Filter.count(std::make_pair(LocStart, LocEnd)))
continue;
SpellingRegion SR{SM, LocStart, LocEnd};
assert(SR.isInSourceOrder() && "region start and end out of order");
if (Region.isGap()) {
MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
SR.LineEnd, SR.ColumnEnd));
} else if (Region.isBranch()) {
MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
Region.getCounter(), Region.getFalseCounter(), *CovFileID,
SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
} else {
MappingRegions.push_back(CounterMappingRegion::makeRegion(
Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
SR.LineEnd, SR.ColumnEnd));
}
}
}
SourceRegionFilter emitExpansionRegions() {
SourceRegionFilter Filter;
for (const auto &FM : FileIDMapping) {
SourceLocation ExpandedLoc = FM.second.second;
SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
if (ParentLoc.isInvalid())
continue;
auto ParentFileID = getCoverageFileID(ParentLoc);
if (!ParentFileID)
continue;
auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
assert(ExpandedFileID && "expansion in uncovered file");
SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
"region spans multiple files");
Filter.insert(std::make_pair(ParentLoc, LocEnd));
SpellingRegion SR{SM, ParentLoc, LocEnd};
assert(SR.isInSourceOrder() && "region start and end out of order");
MappingRegions.push_back(CounterMappingRegion::makeExpansion(
*ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
SR.LineEnd, SR.ColumnEnd));
}
return Filter;
}
};
struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
const LangOptions &LangOpts)
: CoverageMappingBuilder(CVM, SM, LangOpts) {}
void VisitDecl(const Decl *D) {
if (!D->hasBody())
return;
auto Body = D->getBody();
SourceLocation Start = getStart(Body);
SourceLocation End = getEnd(Body);
if (!SM.isWrittenInSameFile(Start, End)) {
FileID StartFileID = SM.getFileID(Start);
FileID EndFileID = SM.getFileID(End);
while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
Start = getIncludeOrExpansionLoc(Start);
assert(Start.isValid() &&
"Declaration start location not nested within a known region");
StartFileID = SM.getFileID(Start);
}
while (StartFileID != EndFileID) {
End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
assert(End.isValid() &&
"Declaration end location not nested within a known region");
EndFileID = SM.getFileID(End);
}
}
SourceRegions.emplace_back(Counter(), Start, End);
}
void write(llvm::raw_ostream &OS) {
SmallVector<unsigned, 16> FileIDMapping;
gatherFileIDs(FileIDMapping);
emitSourceRegions(SourceRegionFilter());
if (MappingRegions.empty())
return;
CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Writer.write(OS);
}
};
struct CounterCoverageMappingBuilder
: public CoverageMappingBuilder,
public ConstStmtVisitor<CounterCoverageMappingBuilder> {
llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
std::vector<SourceMappingRegion> RegionStack;
CounterExpressionBuilder Builder;
SourceLocation MostRecentLocation;
bool HasTerminateStmt = false;
Counter GapRegionCounter;
Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
return Builder.subtract(LHS, RHS, Simplify);
}
Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) {
return Builder.add(LHS, RHS, Simplify);
}
Counter addCounters(Counter C1, Counter C2, Counter C3,
bool Simplify = true) {
return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
}
Counter getRegionCounter(const Stmt *S) {
return Counter::getCounter(CounterMap[S]);
}
size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
Optional<SourceLocation> EndLoc = None,
Optional<Counter> FalseCount = None) {
if (StartLoc && !FalseCount) {
MostRecentLocation = *StartLoc;
}
RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc);
return RegionStack.size() - 1;
}
size_t locationDepth(SourceLocation Loc) {
size_t Depth = 0;
while (Loc.isValid()) {
Loc = getIncludeOrExpansionLoc(Loc);
Depth++;
}
return Depth;
}
void popRegions(size_t ParentIndex) {
assert(RegionStack.size() >= ParentIndex && "parent not in stack");
while (RegionStack.size() > ParentIndex) {
SourceMappingRegion &Region = RegionStack.back();
if (Region.hasStartLoc()) {
SourceLocation StartLoc = Region.getBeginLoc();
SourceLocation EndLoc = Region.hasEndLoc()
? Region.getEndLoc()
: RegionStack[ParentIndex].getEndLoc();
bool isBranch = Region.isBranch();
size_t StartDepth = locationDepth(StartLoc);
size_t EndDepth = locationDepth(EndLoc);
while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
bool UnnestStart = StartDepth >= EndDepth;
bool UnnestEnd = EndDepth >= StartDepth;
if (UnnestEnd) {
SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
EndLoc);
EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
if (EndLoc.isInvalid())
llvm::report_fatal_error(
"File exit not handled before popRegions");
EndDepth--;
}
if (UnnestStart) {
SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
SourceRegions.emplace_back(Region.getCounter(), StartLoc,
NestedLoc);
StartLoc = getIncludeOrExpansionLoc(StartLoc);
if (StartLoc.isInvalid())
llvm::report_fatal_error(
"File exit not handled before popRegions");
StartDepth--;
}
}
Region.setStartLoc(StartLoc);
Region.setEndLoc(EndLoc);
if (!isBranch) {
MostRecentLocation = EndLoc;
if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
EndLoc == getEndOfFileOrMacro(EndLoc))
MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
}
assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
assert(SpellingRegion(SM, Region).isInSourceOrder());
SourceRegions.push_back(Region);
}
RegionStack.pop_back();
}
}
SourceMappingRegion &getRegion() {
assert(!RegionStack.empty() && "statement has no region");
return RegionStack.back();
}
Counter propagateCounts(Counter TopCount, const Stmt *S,
bool VisitChildren = true) {
SourceLocation StartLoc = getStart(S);
SourceLocation EndLoc = getEnd(S);
size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
if (VisitChildren)
Visit(S);
Counter ExitCount = getRegion().getCounter();
popRegions(Index);
if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
MostRecentLocation = EndLoc;
return ExitCount;
}
bool ConditionFoldsToBool(const Expr *Cond) {
Expr::EvalResult Result;
return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
}
void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt) {
if (!C)
return;
if (CodeGenFunction::isInstrumentedCondition(C)) {
if (ConditionFoldsToBool(C))
popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
Counter::getZero()));
else
popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt));
}
}
void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt,
Counter FalseCnt) {
popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
}
bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
bool isBranch = false) {
return llvm::any_of(
llvm::reverse(SourceRegions), [&](const SourceMappingRegion &Region) {
return Region.getBeginLoc() == StartLoc &&
Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
});
}
void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
MostRecentLocation = EndLoc;
if (getRegion().hasEndLoc() &&
MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
MostRecentLocation, getRegion().isBranch()))
MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
}
void handleFileExit(SourceLocation NewLoc) {
if (NewLoc.isInvalid() ||
SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
return;
SourceLocation LCA = NewLoc;
FileID ParentFile = SM.getFileID(LCA);
while (!isNestedIn(MostRecentLocation, ParentFile)) {
LCA = getIncludeOrExpansionLoc(LCA);
if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
MostRecentLocation = NewLoc;
return;
}
ParentFile = SM.getFileID(LCA);
}
llvm::SmallSet<SourceLocation, 8> StartLocs;
Optional<Counter> ParentCounter;
for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
if (!I.hasStartLoc())
continue;
SourceLocation Loc = I.getBeginLoc();
if (!isNestedIn(Loc, ParentFile)) {
ParentCounter = I.getCounter();
break;
}
while (!SM.isInFileID(Loc, ParentFile)) {
if (StartLocs.insert(Loc).second) {
if (I.isBranch())
SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(), Loc,
getEndOfFileOrMacro(Loc), I.isBranch());
else
SourceRegions.emplace_back(I.getCounter(), Loc,
getEndOfFileOrMacro(Loc));
}
Loc = getIncludeOrExpansionLoc(Loc);
}
I.setStartLoc(getPreciseTokenLocEnd(Loc));
}
if (ParentCounter) {
SourceLocation Loc = MostRecentLocation;
while (isNestedIn(Loc, ParentFile)) {
SourceLocation FileStart = getStartOfFileOrMacro(Loc);
if (StartLocs.insert(FileStart).second) {
SourceRegions.emplace_back(*ParentCounter, FileStart,
getEndOfFileOrMacro(Loc));
assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
}
Loc = getIncludeOrExpansionLoc(Loc);
}
}
MostRecentLocation = NewLoc;
}
void extendRegion(const Stmt *S) {
SourceMappingRegion &Region = getRegion();
SourceLocation StartLoc = getStart(S);
handleFileExit(StartLoc);
if (!Region.hasStartLoc())
Region.setStartLoc(StartLoc);
}
void terminateRegion(const Stmt *S) {
extendRegion(S);
SourceMappingRegion &Region = getRegion();
SourceLocation EndLoc = getEnd(S);
if (!Region.hasEndLoc())
Region.setEndLoc(EndLoc);
pushRegion(Counter::getZero());
HasTerminateStmt = true;
}
Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
SourceLocation BeforeLoc) {
if (AfterLoc.isMacroID()) {
FileID FID = SM.getFileID(AfterLoc);
const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
if (EI->isFunctionMacroExpansion())
AfterLoc = EI->getExpansionLocEnd();
}
size_t StartDepth = locationDepth(AfterLoc);
size_t EndDepth = locationDepth(BeforeLoc);
while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
bool UnnestStart = StartDepth >= EndDepth;
bool UnnestEnd = EndDepth >= StartDepth;
if (UnnestEnd) {
assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
BeforeLoc));
BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
assert(BeforeLoc.isValid());
EndDepth--;
}
if (UnnestStart) {
assert(SM.isWrittenInSameFile(AfterLoc,
getEndOfFileOrMacro(AfterLoc)));
AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
assert(AfterLoc.isValid());
AfterLoc = getPreciseTokenLocEnd(AfterLoc);
assert(AfterLoc.isValid());
StartDepth--;
}
}
AfterLoc = getPreciseTokenLocEnd(AfterLoc);
if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
return None;
if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
!SpellingRegion(SM, AfterLoc, BeforeLoc).isInSourceOrder())
return None;
return {{AfterLoc, BeforeLoc}};
}
void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
Counter Count) {
if (StartLoc == EndLoc)
return;
assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
handleFileExit(StartLoc);
size_t Index = pushRegion(Count, StartLoc, EndLoc);
getRegion().setGap(true);
handleFileExit(EndLoc);
popRegions(Index);
}
struct BreakContinue {
Counter BreakCount;
Counter ContinueCount;
};
SmallVector<BreakContinue, 8> BreakContinueStack;
CounterCoverageMappingBuilder(
CoverageMappingModuleGen &CVM,
llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
const LangOptions &LangOpts)
: CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
void write(llvm::raw_ostream &OS) {
llvm::SmallVector<unsigned, 8> VirtualFileMapping;
gatherFileIDs(VirtualFileMapping);
SourceRegionFilter Filter = emitExpansionRegions();
emitSourceRegions(Filter);
gatherSkippedRegions();
if (MappingRegions.empty())
return;
CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
MappingRegions);
Writer.write(OS);
}
void VisitStmt(const Stmt *S) {
if (S->getBeginLoc().isValid())
extendRegion(S);
const Stmt *LastStmt = nullptr;
bool SaveTerminateStmt = HasTerminateStmt;
HasTerminateStmt = false;
GapRegionCounter = Counter::getZero();
for (const Stmt *Child : S->children())
if (Child) {
if (LastStmt && HasTerminateStmt && !isa<AttributedStmt>(Child)) {
auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
if (Gap)
fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
GapRegionCounter);
SaveTerminateStmt = true;
HasTerminateStmt = false;
}
this->Visit(Child);
LastStmt = Child;
}
if (SaveTerminateStmt)
HasTerminateStmt = true;
handleFileExit(getEnd(S));
}
void VisitDecl(const Decl *D) {
Stmt *Body = D->getBody();
if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
return;
bool Defaulted = false;
if (auto *Method = dyn_cast<CXXMethodDecl>(D))
Defaulted = Method->isDefaulted();
propagateCounts(getRegionCounter(Body), Body,
!Defaulted);
assert(RegionStack.empty() && "Regions entered but never exited");
}
void VisitReturnStmt(const ReturnStmt *S) {
extendRegion(S);
if (S->getRetValue())
Visit(S->getRetValue());
terminateRegion(S);
}
void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
extendRegion(S);
Visit(S->getBody());
}
void VisitCoreturnStmt(const CoreturnStmt *S) {
extendRegion(S);
if (S->getOperand())
Visit(S->getOperand());
terminateRegion(S);
}
void VisitCXXThrowExpr(const CXXThrowExpr *E) {
extendRegion(E);
if (E->getSubExpr())
Visit(E->getSubExpr());
terminateRegion(E);
}
void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
void VisitLabelStmt(const LabelStmt *S) {
Counter LabelCount = getRegionCounter(S);
SourceLocation Start = getStart(S);
handleFileExit(Start);
pushRegion(LabelCount, Start);
Visit(S->getSubStmt());
}
void VisitBreakStmt(const BreakStmt *S) {
assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
BreakContinueStack.back().BreakCount = addCounters(
BreakContinueStack.back().BreakCount, getRegion().getCounter());
terminateRegion(S);
}
void VisitContinueStmt(const ContinueStmt *S) {
assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
BreakContinueStack.back().ContinueCount = addCounters(
BreakContinueStack.back().ContinueCount, getRegion().getCounter());
terminateRegion(S);
}
void VisitCallExpr(const CallExpr *E) {
VisitStmt(E);
QualType CalleeType = E->getCallee()->getType();
if (getFunctionExtInfo(*CalleeType).getNoReturn())
terminateRegion(E);
}
void VisitWhileStmt(const WhileStmt *S) {
extendRegion(S);
Counter ParentCount = getRegion().getCounter();
Counter BodyCount = getRegionCounter(S);
BreakContinueStack.push_back(BreakContinue());
extendRegion(S->getBody());
Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
BreakContinue BC = BreakContinueStack.pop_back_val();
bool BodyHasTerminateStmt = HasTerminateStmt;
HasTerminateStmt = false;
Counter CondCount =
addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
propagateCounts(CondCount, S->getCond());
adjustForOutOfOrderTraversal(getEnd(S));
auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
if (Gap)
fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
Counter OutCount =
addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
if (OutCount != ParentCount) {
pushRegion(OutCount);
GapRegionCounter = OutCount;
if (BodyHasTerminateStmt)
HasTerminateStmt = true;
}
createBranchRegion(S->getCond(), BodyCount,
subtractCounters(CondCount, BodyCount));
}
void VisitDoStmt(const DoStmt *S) {
extendRegion(S);
Counter ParentCount = getRegion().getCounter();
Counter BodyCount = getRegionCounter(S);
BreakContinueStack.push_back(BreakContinue());
extendRegion(S->getBody());
Counter BackedgeCount =
propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
BreakContinue BC = BreakContinueStack.pop_back_val();
bool BodyHasTerminateStmt = HasTerminateStmt;
HasTerminateStmt = false;
Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
propagateCounts(CondCount, S->getCond());
Counter OutCount =
addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
if (OutCount != ParentCount) {
pushRegion(OutCount);
GapRegionCounter = OutCount;
}
createBranchRegion(S->getCond(), BodyCount,
subtractCounters(CondCount, BodyCount));
if (BodyHasTerminateStmt)
HasTerminateStmt = true;
}
void VisitForStmt(const ForStmt *S) {
extendRegion(S);
if (S->getInit())
Visit(S->getInit());
Counter ParentCount = getRegion().getCounter();
Counter BodyCount = getRegionCounter(S);
if (S->getInc())
BreakContinueStack.emplace_back();
BreakContinueStack.emplace_back();
extendRegion(S->getBody());
Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
BreakContinue BodyBC = BreakContinueStack.pop_back_val();
bool BodyHasTerminateStmt = HasTerminateStmt;
HasTerminateStmt = false;
BreakContinue IncrementBC;
if (const Stmt *Inc = S->getInc()) {
propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
IncrementBC = BreakContinueStack.pop_back_val();
}
Counter CondCount = addCounters(
addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
IncrementBC.ContinueCount);
if (const Expr *Cond = S->getCond()) {
propagateCounts(CondCount, Cond);
adjustForOutOfOrderTraversal(getEnd(S));
}
auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
if (Gap)
fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
subtractCounters(CondCount, BodyCount));
if (OutCount != ParentCount) {
pushRegion(OutCount);
GapRegionCounter = OutCount;
if (BodyHasTerminateStmt)
HasTerminateStmt = true;
}
createBranchRegion(S->getCond(), BodyCount,
subtractCounters(CondCount, BodyCount));
}
void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
extendRegion(S);
if (S->getInit())
Visit(S->getInit());
Visit(S->getLoopVarStmt());
Visit(S->getRangeStmt());
Counter ParentCount = getRegion().getCounter();
Counter BodyCount = getRegionCounter(S);
BreakContinueStack.push_back(BreakContinue());
extendRegion(S->getBody());
Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
BreakContinue BC = BreakContinueStack.pop_back_val();
bool BodyHasTerminateStmt = HasTerminateStmt;
HasTerminateStmt = false;
auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
if (Gap)
fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
Counter LoopCount =
addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
Counter OutCount =
addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
if (OutCount != ParentCount) {
pushRegion(OutCount);
GapRegionCounter = OutCount;
if (BodyHasTerminateStmt)
HasTerminateStmt = true;
}
createBranchRegion(S->getCond(), BodyCount,
subtractCounters(LoopCount, BodyCount));
}
void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
extendRegion(S);
Visit(S->getElement());
Counter ParentCount = getRegion().getCounter();
Counter BodyCount = getRegionCounter(S);
BreakContinueStack.push_back(BreakContinue());
extendRegion(S->getBody());
Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
BreakContinue BC = BreakContinueStack.pop_back_val();
auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
if (Gap)
fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
Counter LoopCount =
addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
Counter OutCount =
addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
if (OutCount != ParentCount) {
pushRegion(OutCount);
GapRegionCounter = OutCount;
}
}
void VisitSwitchStmt(const SwitchStmt *S) {
extendRegion(S);
if (S->getInit())
Visit(S->getInit());
Visit(S->getCond());
BreakContinueStack.push_back(BreakContinue());
const Stmt *Body = S->getBody();
extendRegion(Body);
if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
if (!CS->body_empty()) {
size_t Index = pushRegion(Counter::getZero(), getStart(CS));
getRegion().setGap(true);
Visit(Body);
for (size_t i = RegionStack.size(); i != Index; --i) {
if (!RegionStack[i - 1].hasEndLoc())
RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
}
popRegions(Index);
}
} else
propagateCounts(Counter::getZero(), Body);
BreakContinue BC = BreakContinueStack.pop_back_val();
if (!BreakContinueStack.empty())
BreakContinueStack.back().ContinueCount = addCounters(
BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Counter ParentCount = getRegion().getCounter();
Counter ExitCount = getRegionCounter(S);
SourceLocation ExitLoc = getEnd(S);
pushRegion(ExitCount);
GapRegionCounter = ExitCount;
MostRecentLocation = getStart(S);
handleFileExit(ExitLoc);
Counter CaseCountSum;
bool HasDefaultCase = false;
const SwitchCase *Case = S->getSwitchCaseList();
for (; Case; Case = Case->getNextSwitchCase()) {
HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
CaseCountSum =
addCounters(CaseCountSum, getRegionCounter(Case), false);
createSwitchCaseRegion(
Case, getRegionCounter(Case),
subtractCounters(ParentCount, getRegionCounter(Case)));
}
CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
if (!HasDefaultCase) {
Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
}
}
void VisitSwitchCase(const SwitchCase *S) {
extendRegion(S);
SourceMappingRegion &Parent = getRegion();
Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
Parent.setCounter(Count);
else
pushRegion(Count, getStart(S));
GapRegionCounter = Count;
if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Visit(CS->getLHS());
if (const Expr *RHS = CS->getRHS())
Visit(RHS);
}
Visit(S->getSubStmt());
}
void VisitIfStmt(const IfStmt *S) {
extendRegion(S);
if (S->getInit())
Visit(S->getInit());
if (!S->isConsteval())
extendRegion(S->getCond());
Counter ParentCount = getRegion().getCounter();
Counter ThenCount = getRegionCounter(S);
if (!S->isConsteval()) {
propagateCounts(ParentCount, S->getCond());
Optional<SourceRange> Gap =
findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
if (Gap)
fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
}
extendRegion(S->getThen());
Counter OutCount = propagateCounts(ThenCount, S->getThen());
Counter ElseCount = subtractCounters(ParentCount, ThenCount);
if (const Stmt *Else = S->getElse()) {
bool ThenHasTerminateStmt = HasTerminateStmt;
HasTerminateStmt = false;
Optional<SourceRange> Gap =
findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
if (Gap)
fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
extendRegion(Else);
OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
if (ThenHasTerminateStmt)
HasTerminateStmt = true;
} else
OutCount = addCounters(OutCount, ElseCount);
if (OutCount != ParentCount) {
pushRegion(OutCount);
GapRegionCounter = OutCount;
}
if (!S->isConsteval()) {
createBranchRegion(S->getCond(), ThenCount,
subtractCounters(ParentCount, ThenCount));
}
}
void VisitCXXTryStmt(const CXXTryStmt *S) {
extendRegion(S);
extendRegion(S->getTryBlock());
Counter ParentCount = getRegion().getCounter();
propagateCounts(ParentCount, S->getTryBlock());
for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
Visit(S->getHandler(I));
Counter ExitCount = getRegionCounter(S);
pushRegion(ExitCount);
}
void VisitCXXCatchStmt(const CXXCatchStmt *S) {
propagateCounts(getRegionCounter(S), S->getHandlerBlock());
}
void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
extendRegion(E);
Counter ParentCount = getRegion().getCounter();
Counter TrueCount = getRegionCounter(E);
propagateCounts(ParentCount, E->getCond());
if (!isa<BinaryConditionalOperator>(E)) {
auto Gap =
findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
if (Gap)
fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
extendRegion(E->getTrueExpr());
propagateCounts(TrueCount, E->getTrueExpr());
}
extendRegion(E->getFalseExpr());
propagateCounts(subtractCounters(ParentCount, TrueCount),
E->getFalseExpr());
createBranchRegion(E->getCond(), TrueCount,
subtractCounters(ParentCount, TrueCount));
}
void VisitBinLAnd(const BinaryOperator *E) {
extendRegion(E->getLHS());
propagateCounts(getRegion().getCounter(), E->getLHS());
handleFileExit(getEnd(E->getLHS()));
extendRegion(E->getRHS());
propagateCounts(getRegionCounter(E), E->getRHS());
Counter RHSExecCnt = getRegionCounter(E);
Counter RHSTrueCnt = getRegionCounter(E->getRHS());
Counter ParentCnt = getRegion().getCounter();
createBranchRegion(E->getLHS(), RHSExecCnt,
subtractCounters(ParentCnt, RHSExecCnt));
createBranchRegion(E->getRHS(), RHSTrueCnt,
subtractCounters(RHSExecCnt, RHSTrueCnt));
}
void VisitBinLOr(const BinaryOperator *E) {
extendRegion(E->getLHS());
propagateCounts(getRegion().getCounter(), E->getLHS());
handleFileExit(getEnd(E->getLHS()));
extendRegion(E->getRHS());
propagateCounts(getRegionCounter(E), E->getRHS());
Counter RHSExecCnt = getRegionCounter(E);
Counter RHSFalseCnt = getRegionCounter(E->getRHS());
Counter ParentCnt = getRegion().getCounter();
createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
RHSExecCnt);
createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
RHSFalseCnt);
}
void VisitLambdaExpr(const LambdaExpr *LE) {
}
};
}
static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
ArrayRef<CounterExpression> Expressions,
ArrayRef<CounterMappingRegion> Regions) {
OS << FunctionName << ":\n";
CounterMappingContext Ctx(Expressions);
for (const auto &R : Regions) {
OS.indent(2);
switch (R.Kind) {
case CounterMappingRegion::CodeRegion:
break;
case CounterMappingRegion::ExpansionRegion:
OS << "Expansion,";
break;
case CounterMappingRegion::SkippedRegion:
OS << "Skipped,";
break;
case CounterMappingRegion::GapRegion:
OS << "Gap,";
break;
case CounterMappingRegion::BranchRegion:
OS << "Branch,";
break;
}
OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
<< " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Ctx.dump(R.Count, OS);
if (R.Kind == CounterMappingRegion::BranchRegion) {
OS << ", ";
Ctx.dump(R.FalseCount, OS);
}
if (R.Kind == CounterMappingRegion::ExpansionRegion)
OS << " (Expanded file = " << R.ExpandedFileID << ")";
OS << "\n";
}
}
CoverageMappingModuleGen::CoverageMappingModuleGen(
CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
: CGM(CGM), SourceInfo(SourceInfo) {
CoveragePrefixMap = CGM.getCodeGenOpts().CoveragePrefixMap;
}
std::string CoverageMappingModuleGen::getCurrentDirname() {
if (!CGM.getCodeGenOpts().CoverageCompilationDir.empty())
return CGM.getCodeGenOpts().CoverageCompilationDir;
SmallString<256> CWD;
llvm::sys::fs::current_path(CWD);
return CWD.str().str();
}
std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
llvm::SmallString<256> Path(Filename);
llvm::sys::path::remove_dots(Path, true);
for (const auto &Entry : CoveragePrefixMap) {
if (llvm::sys::path::replace_path_prefix(Path, Entry.first, Entry.second))
break;
}
return Path.str().str();
}
static std::string getInstrProfSection(const CodeGenModule &CGM,
llvm::InstrProfSectKind SK) {
return llvm::getInstrProfSectionName(
SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
}
void CoverageMappingModuleGen::emitFunctionMappingRecord(
const FunctionInfo &Info, uint64_t FilenamesRef) {
llvm::LLVMContext &Ctx = CGM.getLLVMContext();
std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
if (Info.IsUsed)
FuncRecordName += "u";
const uint64_t NameHash = Info.NameHash;
const uint64_t FuncHash = Info.FuncHash;
const std::string &CoverageMapping = Info.CoverageMapping;
#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
llvm::Type *FunctionRecordTypes[] = {
#include "llvm/ProfileData/InstrProfData.inc"
};
auto *FunctionRecordTy =
llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
true);
#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
llvm::Constant *FunctionRecordVals[] = {
#include "llvm/ProfileData/InstrProfData.inc"
};
auto *FuncRecordConstant = llvm::ConstantStruct::get(
FunctionRecordTy, makeArrayRef(FunctionRecordVals));
auto *FuncRecord = new llvm::GlobalVariable(
CGM.getModule(), FunctionRecordTy, true,
llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
FuncRecordName);
FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
FuncRecord->setAlignment(llvm::Align(8));
if (CGM.supportsCOMDAT())
FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
CGM.addUsedGlobal(FuncRecord);
}
void CoverageMappingModuleGen::addFunctionMappingRecord(
llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
const std::string &CoverageMapping, bool IsUsed) {
llvm::LLVMContext &Ctx = CGM.getLLVMContext();
const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
if (!IsUsed)
FunctionNames.push_back(
llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
if (CGM.getCodeGenOpts().DumpCoverageMapping) {
llvm::SmallVector<std::string, 16> FilenameStrs;
std::vector<StringRef> Filenames;
std::vector<CounterExpression> Expressions;
std::vector<CounterMappingRegion> Regions;
FilenameStrs.resize(FileEntries.size() + 1);
FilenameStrs[0] = normalizeFilename(getCurrentDirname());
for (const auto &Entry : FileEntries) {
auto I = Entry.second;
FilenameStrs[I] = normalizeFilename(Entry.first->getName());
}
ArrayRef<std::string> FilenameRefs = llvm::makeArrayRef(FilenameStrs);
RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
Expressions, Regions);
if (Reader.read())
return;
dump(llvm::outs(), NameValue, Expressions, Regions);
}
}
void CoverageMappingModuleGen::emit() {
if (FunctionRecords.empty())
return;
llvm::LLVMContext &Ctx = CGM.getLLVMContext();
auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
llvm::SmallVector<std::string, 16> FilenameStrs;
FilenameStrs.resize(FileEntries.size() + 1);
FilenameStrs[0] = normalizeFilename(getCurrentDirname());
for (const auto &Entry : FileEntries) {
auto I = Entry.second;
FilenameStrs[I] = normalizeFilename(Entry.first->getName());
}
std::string Filenames;
{
llvm::raw_string_ostream OS(Filenames);
CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
}
auto *FilenamesVal =
llvm::ConstantDataArray::getString(Ctx, Filenames, false);
const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
for (const FunctionInfo &Info : FunctionRecords)
emitFunctionMappingRecord(Info, FilenamesRef);
const unsigned NRecords = 0;
const size_t FilenamesSize = Filenames.size();
const unsigned CoverageMappingSize = 0;
llvm::Type *CovDataHeaderTypes[] = {
#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
#include "llvm/ProfileData/InstrProfData.inc"
};
auto CovDataHeaderTy =
llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
llvm::Constant *CovDataHeaderVals[] = {
#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
#include "llvm/ProfileData/InstrProfData.inc"
};
auto CovDataHeaderVal = llvm::ConstantStruct::get(
CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
auto CovDataVal =
llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
auto CovData = new llvm::GlobalVariable(
CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
CovDataVal, llvm::getCoverageMappingVarName());
CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
CovData->setAlignment(llvm::Align(8));
CGM.addUsedGlobal(CovData);
if (!FunctionNames.empty()) {
auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
FunctionNames.size());
auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
llvm::GlobalValue::InternalLinkage, NamesArrVal,
llvm::getCoverageUnusedNamesVarName());
}
}
unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
auto It = FileEntries.find(File);
if (It != FileEntries.end())
return It->second;
unsigned FileID = FileEntries.size() + 1;
FileEntries.insert(std::make_pair(File, FileID));
return FileID;
}
void CoverageMappingGen::emitCounterMapping(const Decl *D,
llvm::raw_ostream &OS) {
assert(CounterMap);
CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Walker.VisitDecl(D);
Walker.write(OS);
}
void CoverageMappingGen::emitEmptyMapping(const Decl *D,
llvm::raw_ostream &OS) {
EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
Walker.VisitDecl(D);
Walker.write(OS);
}