xref: /src/contrib/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
106d4ba38SDimitry Andric //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
206d4ba38SDimitry Andric //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606d4ba38SDimitry Andric //
706d4ba38SDimitry Andric //===----------------------------------------------------------------------===//
806d4ba38SDimitry Andric //
906d4ba38SDimitry Andric // Instrumentation-based code coverage mapping generator
1006d4ba38SDimitry Andric //
1106d4ba38SDimitry Andric //===----------------------------------------------------------------------===//
1206d4ba38SDimitry Andric 
1306d4ba38SDimitry Andric #include "CoverageMappingGen.h"
1406d4ba38SDimitry Andric #include "CodeGenFunction.h"
1506d4ba38SDimitry Andric #include "clang/AST/StmtVisitor.h"
16cfca06d7SDimitry Andric #include "clang/Basic/Diagnostic.h"
17cfca06d7SDimitry Andric #include "clang/Basic/FileManager.h"
18cfca06d7SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
1906d4ba38SDimitry Andric #include "clang/Lex/Lexer.h"
20ac9a064cSDimitry Andric #include "llvm/ADT/DenseSet.h"
212b6b257fSDimitry Andric #include "llvm/ADT/SmallSet.h"
222b6b257fSDimitry Andric #include "llvm/ADT/StringExtras.h"
232b6b257fSDimitry Andric #include "llvm/ProfileData/Coverage/CoverageMapping.h"
242b6b257fSDimitry Andric #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
252b6b257fSDimitry Andric #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
2606d4ba38SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
2706d4ba38SDimitry Andric #include "llvm/Support/FileSystem.h"
28bab175ecSDimitry Andric #include "llvm/Support/Path.h"
29e3b55780SDimitry Andric #include <optional>
3006d4ba38SDimitry Andric 
31cfca06d7SDimitry Andric // This selects the coverage mapping format defined when `InstrProfData.inc`
32cfca06d7SDimitry Andric // is textually included.
33cfca06d7SDimitry Andric #define COVMAP_V3
34cfca06d7SDimitry Andric 
35ac9a064cSDimitry Andric namespace llvm {
36ac9a064cSDimitry Andric cl::opt<bool>
37ac9a064cSDimitry Andric     EnableSingleByteCoverage("enable-single-byte-coverage",
38ac9a064cSDimitry Andric                              llvm::cl::ZeroOrMore,
39ac9a064cSDimitry Andric                              llvm::cl::desc("Enable single byte coverage"),
40ac9a064cSDimitry Andric                              llvm::cl::Hidden, llvm::cl::init(false));
41ac9a064cSDimitry Andric } // namespace llvm
42ac9a064cSDimitry Andric 
43b60736ecSDimitry Andric static llvm::cl::opt<bool> EmptyLineCommentCoverage(
44b60736ecSDimitry Andric     "emptyline-comment-coverage",
45b60736ecSDimitry Andric     llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
46b60736ecSDimitry Andric                    "disable it on test)"),
47b60736ecSDimitry Andric     llvm::cl::init(true), llvm::cl::Hidden);
48b60736ecSDimitry Andric 
49ac9a064cSDimitry Andric namespace llvm::coverage {
50ac9a064cSDimitry Andric cl::opt<bool> SystemHeadersCoverage(
517fa27ce4SDimitry Andric     "system-headers-coverage",
52ac9a064cSDimitry Andric     cl::desc("Enable collecting coverage from system headers"), cl::init(false),
53ac9a064cSDimitry Andric     cl::Hidden);
54ac9a064cSDimitry Andric }
557fa27ce4SDimitry Andric 
5606d4ba38SDimitry Andric using namespace clang;
5706d4ba38SDimitry Andric using namespace CodeGen;
5806d4ba38SDimitry Andric using namespace llvm::coverage;
5906d4ba38SDimitry Andric 
60b60736ecSDimitry Andric CoverageSourceInfo *
setUpCoverageCallbacks(Preprocessor & PP)61b60736ecSDimitry Andric CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
62b60736ecSDimitry Andric   CoverageSourceInfo *CoverageInfo =
63b60736ecSDimitry Andric       new CoverageSourceInfo(PP.getSourceManager());
64b60736ecSDimitry Andric   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
65b60736ecSDimitry Andric   if (EmptyLineCommentCoverage) {
66b60736ecSDimitry Andric     PP.addCommentHandler(CoverageInfo);
67b60736ecSDimitry Andric     PP.setEmptylineHandler(CoverageInfo);
68b60736ecSDimitry Andric     PP.setPreprocessToken(true);
69b60736ecSDimitry Andric     PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
70b60736ecSDimitry Andric       // Update previous token location.
71b60736ecSDimitry Andric       CoverageInfo->PrevTokLoc = Tok.getLocation();
72b60736ecSDimitry Andric       if (Tok.getKind() != clang::tok::eod)
73b60736ecSDimitry Andric         CoverageInfo->updateNextTokLoc(Tok.getLocation());
74b60736ecSDimitry Andric     });
75b60736ecSDimitry Andric   }
76b60736ecSDimitry Andric   return CoverageInfo;
77b60736ecSDimitry Andric }
78b60736ecSDimitry Andric 
AddSkippedRange(SourceRange Range,SkippedRange::Kind RangeKind)79145449b1SDimitry Andric void CoverageSourceInfo::AddSkippedRange(SourceRange Range,
80145449b1SDimitry Andric                                          SkippedRange::Kind RangeKind) {
81b60736ecSDimitry Andric   if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
82b60736ecSDimitry Andric       PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
83b60736ecSDimitry Andric       SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
84b60736ecSDimitry Andric                                     Range.getBegin()))
85b60736ecSDimitry Andric     SkippedRanges.back().Range.setEnd(Range.getEnd());
86b60736ecSDimitry Andric   else
87145449b1SDimitry Andric     SkippedRanges.push_back({Range, RangeKind, PrevTokLoc});
88b60736ecSDimitry Andric }
89b60736ecSDimitry Andric 
SourceRangeSkipped(SourceRange Range,SourceLocation)90461a67faSDimitry Andric void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
91145449b1SDimitry Andric   AddSkippedRange(Range, SkippedRange::PPIfElse);
92b60736ecSDimitry Andric }
93b60736ecSDimitry Andric 
HandleEmptyline(SourceRange Range)94b60736ecSDimitry Andric void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
95145449b1SDimitry Andric   AddSkippedRange(Range, SkippedRange::EmptyLine);
96b60736ecSDimitry Andric }
97b60736ecSDimitry Andric 
HandleComment(Preprocessor & PP,SourceRange Range)98b60736ecSDimitry Andric bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
99145449b1SDimitry Andric   AddSkippedRange(Range, SkippedRange::Comment);
100b60736ecSDimitry Andric   return false;
101b60736ecSDimitry Andric }
102b60736ecSDimitry Andric 
updateNextTokLoc(SourceLocation Loc)103b60736ecSDimitry Andric void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
104b60736ecSDimitry Andric   if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
105b60736ecSDimitry Andric     SkippedRanges.back().NextTokLoc = Loc;
10606d4ba38SDimitry Andric }
10706d4ba38SDimitry Andric 
10806d4ba38SDimitry Andric namespace {
10948675466SDimitry Andric /// A region of source code that can be mapped to a counter.
11006d4ba38SDimitry Andric class SourceMappingRegion {
111b60736ecSDimitry Andric   /// Primary Counter that is also used for Branch Regions for "True" branches.
11206d4ba38SDimitry Andric   Counter Count;
11306d4ba38SDimitry Andric 
114b60736ecSDimitry Andric   /// Secondary Counter used for Branch Regions for "False" branches.
115e3b55780SDimitry Andric   std::optional<Counter> FalseCount;
116b60736ecSDimitry Andric 
117aca2e42cSDimitry Andric   /// Parameters used for Modified Condition/Decision Coverage
118ac9a064cSDimitry Andric   mcdc::Parameters MCDCParams;
119aca2e42cSDimitry Andric 
12048675466SDimitry Andric   /// The region's starting location.
121e3b55780SDimitry Andric   std::optional<SourceLocation> LocStart;
12206d4ba38SDimitry Andric 
12348675466SDimitry Andric   /// The region's ending location.
124e3b55780SDimitry Andric   std::optional<SourceLocation> LocEnd;
12506d4ba38SDimitry Andric 
126461a67faSDimitry Andric   /// Whether this region is a gap region. The count from a gap region is set
127461a67faSDimitry Andric   /// as the line execution count if there are no other regions on the line.
128461a67faSDimitry Andric   bool GapRegion;
129461a67faSDimitry Andric 
1304df029ccSDimitry Andric   /// Whetever this region is skipped ('if constexpr' or 'if consteval' untaken
1314df029ccSDimitry Andric   /// branch, or anything skipped but not empty line / comments)
1324df029ccSDimitry Andric   bool SkippedRegion;
1334df029ccSDimitry Andric 
13406d4ba38SDimitry Andric public:
SourceMappingRegion(Counter Count,std::optional<SourceLocation> LocStart,std::optional<SourceLocation> LocEnd,bool GapRegion=false)135e3b55780SDimitry Andric   SourceMappingRegion(Counter Count, std::optional<SourceLocation> LocStart,
136e3b55780SDimitry Andric                       std::optional<SourceLocation> LocEnd,
137e3b55780SDimitry Andric                       bool GapRegion = false)
1384df029ccSDimitry Andric       : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
1394df029ccSDimitry Andric         SkippedRegion(false) {}
14006d4ba38SDimitry Andric 
SourceMappingRegion(Counter Count,std::optional<Counter> FalseCount,mcdc::Parameters MCDCParams,std::optional<SourceLocation> LocStart,std::optional<SourceLocation> LocEnd,bool GapRegion=false)141e3b55780SDimitry Andric   SourceMappingRegion(Counter Count, std::optional<Counter> FalseCount,
142ac9a064cSDimitry Andric                       mcdc::Parameters MCDCParams,
143e3b55780SDimitry Andric                       std::optional<SourceLocation> LocStart,
144e3b55780SDimitry Andric                       std::optional<SourceLocation> LocEnd,
145e3b55780SDimitry Andric                       bool GapRegion = false)
146aca2e42cSDimitry Andric       : Count(Count), FalseCount(FalseCount), MCDCParams(MCDCParams),
1474df029ccSDimitry Andric         LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
1484df029ccSDimitry Andric         SkippedRegion(false) {}
149aca2e42cSDimitry Andric 
SourceMappingRegion(mcdc::Parameters MCDCParams,std::optional<SourceLocation> LocStart,std::optional<SourceLocation> LocEnd)150ac9a064cSDimitry Andric   SourceMappingRegion(mcdc::Parameters MCDCParams,
151aca2e42cSDimitry Andric                       std::optional<SourceLocation> LocStart,
152aca2e42cSDimitry Andric                       std::optional<SourceLocation> LocEnd)
153aca2e42cSDimitry Andric       : MCDCParams(MCDCParams), LocStart(LocStart), LocEnd(LocEnd),
1544df029ccSDimitry Andric         GapRegion(false), SkippedRegion(false) {}
155b60736ecSDimitry Andric 
getCounter() const15606d4ba38SDimitry Andric   const Counter &getCounter() const { return Count; }
15706d4ba38SDimitry Andric 
getFalseCounter() const158b60736ecSDimitry Andric   const Counter &getFalseCounter() const {
159b60736ecSDimitry Andric     assert(FalseCount && "Region has no alternate counter");
160b60736ecSDimitry Andric     return *FalseCount;
161b60736ecSDimitry Andric   }
162b60736ecSDimitry Andric 
setCounter(Counter C)1635e20cdd8SDimitry Andric   void setCounter(Counter C) { Count = C; }
16406d4ba38SDimitry Andric 
hasStartLoc() const165145449b1SDimitry Andric   bool hasStartLoc() const { return LocStart.has_value(); }
1665e20cdd8SDimitry Andric 
setStartLoc(SourceLocation Loc)1675e20cdd8SDimitry Andric   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
1685e20cdd8SDimitry Andric 
getBeginLoc() const169676fbe81SDimitry Andric   SourceLocation getBeginLoc() const {
1705e20cdd8SDimitry Andric     assert(LocStart && "Region has no start location");
1715e20cdd8SDimitry Andric     return *LocStart;
17206d4ba38SDimitry Andric   }
17306d4ba38SDimitry Andric 
hasEndLoc() const174145449b1SDimitry Andric   bool hasEndLoc() const { return LocEnd.has_value(); }
17506d4ba38SDimitry Andric 
setEndLoc(SourceLocation Loc)17648675466SDimitry Andric   void setEndLoc(SourceLocation Loc) {
17748675466SDimitry Andric     assert(Loc.isValid() && "Setting an invalid end location");
17848675466SDimitry Andric     LocEnd = Loc;
17948675466SDimitry Andric   }
18006d4ba38SDimitry Andric 
getEndLoc() const18145b53394SDimitry Andric   SourceLocation getEndLoc() const {
1825e20cdd8SDimitry Andric     assert(LocEnd && "Region has no end location");
1835e20cdd8SDimitry Andric     return *LocEnd;
18406d4ba38SDimitry Andric   }
185461a67faSDimitry Andric 
isGap() const186461a67faSDimitry Andric   bool isGap() const { return GapRegion; }
187461a67faSDimitry Andric 
setGap(bool Gap)188461a67faSDimitry Andric   void setGap(bool Gap) { GapRegion = Gap; }
189b60736ecSDimitry Andric 
isSkipped() const1904df029ccSDimitry Andric   bool isSkipped() const { return SkippedRegion; }
1914df029ccSDimitry Andric 
setSkipped(bool Skipped)1924df029ccSDimitry Andric   void setSkipped(bool Skipped) { SkippedRegion = Skipped; }
1934df029ccSDimitry Andric 
isBranch() const194145449b1SDimitry Andric   bool isBranch() const { return FalseCount.has_value(); }
195aca2e42cSDimitry Andric 
isMCDCBranch() const196ac9a064cSDimitry Andric   bool isMCDCBranch() const {
197ac9a064cSDimitry Andric     return std::holds_alternative<mcdc::BranchParameters>(MCDCParams);
198ac9a064cSDimitry Andric   }
199aca2e42cSDimitry Andric 
getMCDCBranchParams() const200ac9a064cSDimitry Andric   const auto &getMCDCBranchParams() const {
201ac9a064cSDimitry Andric     return mcdc::getParams<const mcdc::BranchParameters>(MCDCParams);
202ac9a064cSDimitry Andric   }
203ac9a064cSDimitry Andric 
isMCDCDecision() const204ac9a064cSDimitry Andric   bool isMCDCDecision() const {
205ac9a064cSDimitry Andric     return std::holds_alternative<mcdc::DecisionParameters>(MCDCParams);
206ac9a064cSDimitry Andric   }
207ac9a064cSDimitry Andric 
getMCDCDecisionParams() const208ac9a064cSDimitry Andric   const auto &getMCDCDecisionParams() const {
209ac9a064cSDimitry Andric     return mcdc::getParams<const mcdc::DecisionParameters>(MCDCParams);
210ac9a064cSDimitry Andric   }
211ac9a064cSDimitry Andric 
getMCDCParams() const212ac9a064cSDimitry Andric   const mcdc::Parameters &getMCDCParams() const { return MCDCParams; }
213ac9a064cSDimitry Andric 
resetMCDCParams()214ac9a064cSDimitry Andric   void resetMCDCParams() { MCDCParams = mcdc::Parameters(); }
215461a67faSDimitry Andric };
216461a67faSDimitry Andric 
217461a67faSDimitry Andric /// Spelling locations for the start and end of a source region.
218461a67faSDimitry Andric struct SpellingRegion {
219461a67faSDimitry Andric   /// The line where the region starts.
220461a67faSDimitry Andric   unsigned LineStart;
221461a67faSDimitry Andric 
222461a67faSDimitry Andric   /// The column where the region starts.
223461a67faSDimitry Andric   unsigned ColumnStart;
224461a67faSDimitry Andric 
225461a67faSDimitry Andric   /// The line where the region ends.
226461a67faSDimitry Andric   unsigned LineEnd;
227461a67faSDimitry Andric 
228461a67faSDimitry Andric   /// The column where the region ends.
229461a67faSDimitry Andric   unsigned ColumnEnd;
230461a67faSDimitry Andric 
SpellingRegion__anon015dba650211::SpellingRegion231461a67faSDimitry Andric   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
232461a67faSDimitry Andric                  SourceLocation LocEnd) {
233461a67faSDimitry Andric     LineStart = SM.getSpellingLineNumber(LocStart);
234461a67faSDimitry Andric     ColumnStart = SM.getSpellingColumnNumber(LocStart);
235461a67faSDimitry Andric     LineEnd = SM.getSpellingLineNumber(LocEnd);
236461a67faSDimitry Andric     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
237461a67faSDimitry Andric   }
238461a67faSDimitry Andric 
SpellingRegion__anon015dba650211::SpellingRegion239461a67faSDimitry Andric   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
240676fbe81SDimitry Andric       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
241461a67faSDimitry Andric 
242461a67faSDimitry Andric   /// Check if the start and end locations appear in source order, i.e
243461a67faSDimitry Andric   /// top->bottom, left->right.
isInSourceOrder__anon015dba650211::SpellingRegion244461a67faSDimitry Andric   bool isInSourceOrder() const {
245461a67faSDimitry Andric     return (LineStart < LineEnd) ||
246461a67faSDimitry Andric            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
247461a67faSDimitry Andric   }
24806d4ba38SDimitry Andric };
24906d4ba38SDimitry Andric 
25048675466SDimitry Andric /// Provides the common functionality for the different
25106d4ba38SDimitry Andric /// coverage mapping region builders.
25206d4ba38SDimitry Andric class CoverageMappingBuilder {
25306d4ba38SDimitry Andric public:
25406d4ba38SDimitry Andric   CoverageMappingModuleGen &CVM;
25506d4ba38SDimitry Andric   SourceManager &SM;
25606d4ba38SDimitry Andric   const LangOptions &LangOpts;
25706d4ba38SDimitry Andric 
25806d4ba38SDimitry Andric private:
25948675466SDimitry Andric   /// Map of clang's FileIDs to IDs used for coverage mapping.
2605e20cdd8SDimitry Andric   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
2615e20cdd8SDimitry Andric       FileIDMapping;
26206d4ba38SDimitry Andric 
26306d4ba38SDimitry Andric public:
26448675466SDimitry Andric   /// The coverage mapping regions for this function
26506d4ba38SDimitry Andric   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
26648675466SDimitry Andric   /// The source mapping regions for this function.
26706d4ba38SDimitry Andric   std::vector<SourceMappingRegion> SourceRegions;
26806d4ba38SDimitry Andric 
26948675466SDimitry Andric   /// A set of regions which can be used as a filter.
270bab175ecSDimitry Andric   ///
271bab175ecSDimitry Andric   /// It is produced by emitExpansionRegions() and is used in
272bab175ecSDimitry Andric   /// emitSourceRegions() to suppress producing code regions if
273bab175ecSDimitry Andric   /// the same area is covered by expansion regions.
274bab175ecSDimitry Andric   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
275bab175ecSDimitry Andric       SourceRegionFilter;
276bab175ecSDimitry Andric 
CoverageMappingBuilder(CoverageMappingModuleGen & CVM,SourceManager & SM,const LangOptions & LangOpts)27706d4ba38SDimitry Andric   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
27806d4ba38SDimitry Andric                          const LangOptions &LangOpts)
2795e20cdd8SDimitry Andric       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
28006d4ba38SDimitry Andric 
28148675466SDimitry Andric   /// Return the precise end location for the given token.
getPreciseTokenLocEnd(SourceLocation Loc)28206d4ba38SDimitry Andric   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
2835e20cdd8SDimitry Andric     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
2845e20cdd8SDimitry Andric     // macro locations, which we just treat as expanded files.
2855e20cdd8SDimitry Andric     unsigned TokLen =
2865e20cdd8SDimitry Andric         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
2875e20cdd8SDimitry Andric     return Loc.getLocWithOffset(TokLen);
28806d4ba38SDimitry Andric   }
28906d4ba38SDimitry Andric 
29048675466SDimitry Andric   /// Return the start location of an included file or expanded macro.
getStartOfFileOrMacro(SourceLocation Loc)2915e20cdd8SDimitry Andric   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
2925e20cdd8SDimitry Andric     if (Loc.isMacroID())
2935e20cdd8SDimitry Andric       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
2945e20cdd8SDimitry Andric     return SM.getLocForStartOfFile(SM.getFileID(Loc));
29506d4ba38SDimitry Andric   }
29606d4ba38SDimitry Andric 
29748675466SDimitry Andric   /// Return the end location of an included file or expanded macro.
getEndOfFileOrMacro(SourceLocation Loc)2985e20cdd8SDimitry Andric   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
2995e20cdd8SDimitry Andric     if (Loc.isMacroID())
3005e20cdd8SDimitry Andric       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
3015e20cdd8SDimitry Andric                                   SM.getFileOffset(Loc));
3025e20cdd8SDimitry Andric     return SM.getLocForEndOfFile(SM.getFileID(Loc));
30306d4ba38SDimitry Andric   }
30406d4ba38SDimitry Andric 
305ac9a064cSDimitry Andric   /// Find out where a macro is expanded. If the immediate result is a
306ac9a064cSDimitry Andric   /// <scratch space>, keep looking until the result isn't. Return a pair of
307ac9a064cSDimitry Andric   /// \c SourceLocation. The first object is always the begin sloc of found
308ac9a064cSDimitry Andric   /// result. The second should be checked by the caller: if it has value, it's
309ac9a064cSDimitry Andric   /// the end sloc of the found result. Otherwise the while loop didn't get
310ac9a064cSDimitry Andric   /// executed, which means the location wasn't changed and the caller has to
311ac9a064cSDimitry Andric   /// learn the end sloc from somewhere else.
312ac9a064cSDimitry Andric   std::pair<SourceLocation, std::optional<SourceLocation>>
getNonScratchExpansionLoc(SourceLocation Loc)313ac9a064cSDimitry Andric   getNonScratchExpansionLoc(SourceLocation Loc) {
314ac9a064cSDimitry Andric     std::optional<SourceLocation> EndLoc = std::nullopt;
315ac9a064cSDimitry Andric     while (Loc.isMacroID() &&
316ac9a064cSDimitry Andric            SM.isWrittenInScratchSpace(SM.getSpellingLoc(Loc))) {
317ac9a064cSDimitry Andric       auto ExpansionRange = SM.getImmediateExpansionRange(Loc);
318ac9a064cSDimitry Andric       Loc = ExpansionRange.getBegin();
319ac9a064cSDimitry Andric       EndLoc = ExpansionRange.getEnd();
320ac9a064cSDimitry Andric     }
321ac9a064cSDimitry Andric     return std::make_pair(Loc, EndLoc);
322ac9a064cSDimitry Andric   }
323ac9a064cSDimitry Andric 
324ac9a064cSDimitry Andric   /// Find out where the current file is included or macro is expanded. If
325ac9a064cSDimitry Andric   /// \c AcceptScratch is set to false, keep looking for expansions until the
326ac9a064cSDimitry Andric   /// found sloc is not a <scratch space>.
getIncludeOrExpansionLoc(SourceLocation Loc,bool AcceptScratch=true)327ac9a064cSDimitry Andric   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc,
328ac9a064cSDimitry Andric                                           bool AcceptScratch = true) {
329ac9a064cSDimitry Andric     if (!Loc.isMacroID())
330ac9a064cSDimitry Andric       return SM.getIncludeLoc(SM.getFileID(Loc));
331ac9a064cSDimitry Andric     Loc = SM.getImmediateExpansionRange(Loc).getBegin();
332ac9a064cSDimitry Andric     if (AcceptScratch)
333ac9a064cSDimitry Andric       return Loc;
334ac9a064cSDimitry Andric     return getNonScratchExpansionLoc(Loc).first;
3355e20cdd8SDimitry Andric   }
3365e20cdd8SDimitry Andric 
33748675466SDimitry Andric   /// Return true if \c Loc is a location in a built-in macro.
isInBuiltin(SourceLocation Loc)3385e20cdd8SDimitry Andric   bool isInBuiltin(SourceLocation Loc) {
339bab175ecSDimitry Andric     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
3405e20cdd8SDimitry Andric   }
3415e20cdd8SDimitry Andric 
34248675466SDimitry Andric   /// Check whether \c Loc is included or expanded from \c Parent.
isNestedIn(SourceLocation Loc,FileID Parent)3432b6b257fSDimitry Andric   bool isNestedIn(SourceLocation Loc, FileID Parent) {
3442b6b257fSDimitry Andric     do {
3452b6b257fSDimitry Andric       Loc = getIncludeOrExpansionLoc(Loc);
3462b6b257fSDimitry Andric       if (Loc.isInvalid())
3472b6b257fSDimitry Andric         return false;
3482b6b257fSDimitry Andric     } while (!SM.isInFileID(Loc, Parent));
3492b6b257fSDimitry Andric     return true;
3502b6b257fSDimitry Andric   }
3512b6b257fSDimitry Andric 
35248675466SDimitry Andric   /// Get the start of \c S ignoring macro arguments and builtin macros.
getStart(const Stmt * S)3535e20cdd8SDimitry Andric   SourceLocation getStart(const Stmt *S) {
354676fbe81SDimitry Andric     SourceLocation Loc = S->getBeginLoc();
3555e20cdd8SDimitry Andric     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
35648675466SDimitry Andric       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
3575e20cdd8SDimitry Andric     return Loc;
3585e20cdd8SDimitry Andric   }
3595e20cdd8SDimitry Andric 
36048675466SDimitry Andric   /// Get the end of \c S ignoring macro arguments and builtin macros.
getEnd(const Stmt * S)3615e20cdd8SDimitry Andric   SourceLocation getEnd(const Stmt *S) {
362676fbe81SDimitry Andric     SourceLocation Loc = S->getEndLoc();
3635e20cdd8SDimitry Andric     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
36448675466SDimitry Andric       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
3655e20cdd8SDimitry Andric     return getPreciseTokenLocEnd(Loc);
3665e20cdd8SDimitry Andric   }
3675e20cdd8SDimitry Andric 
36848675466SDimitry Andric   /// Find the set of files we have regions for and assign IDs
3695e20cdd8SDimitry Andric   ///
3705e20cdd8SDimitry Andric   /// Fills \c Mapping with the virtual file mapping needed to write out
3715e20cdd8SDimitry Andric   /// coverage and collects the necessary file information to emit source and
3725e20cdd8SDimitry Andric   /// expansion regions.
gatherFileIDs(SmallVectorImpl<unsigned> & Mapping)3735e20cdd8SDimitry Andric   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
3745e20cdd8SDimitry Andric     FileIDMapping.clear();
3755e20cdd8SDimitry Andric 
3762b6b257fSDimitry Andric     llvm::SmallSet<FileID, 8> Visited;
3775e20cdd8SDimitry Andric     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
378ac9a064cSDimitry Andric     for (auto &Region : SourceRegions) {
379676fbe81SDimitry Andric       SourceLocation Loc = Region.getBeginLoc();
380ac9a064cSDimitry Andric 
381ac9a064cSDimitry Andric       // Replace Region with its definition if it is in <scratch space>.
382ac9a064cSDimitry Andric       auto NonScratchExpansionLoc = getNonScratchExpansionLoc(Loc);
383ac9a064cSDimitry Andric       auto EndLoc = NonScratchExpansionLoc.second;
384ac9a064cSDimitry Andric       if (EndLoc.has_value()) {
385ac9a064cSDimitry Andric         Loc = NonScratchExpansionLoc.first;
386ac9a064cSDimitry Andric         Region.setStartLoc(Loc);
387ac9a064cSDimitry Andric         Region.setEndLoc(EndLoc.value());
388ac9a064cSDimitry Andric       }
389ac9a064cSDimitry Andric 
390ac9a064cSDimitry Andric       // Replace Loc with FileLoc if it is expanded with system headers.
391ac9a064cSDimitry Andric       if (!SystemHeadersCoverage && SM.isInSystemMacro(Loc)) {
392ac9a064cSDimitry Andric         auto BeginLoc = SM.getSpellingLoc(Loc);
393ac9a064cSDimitry Andric         auto EndLoc = SM.getSpellingLoc(Region.getEndLoc());
394ac9a064cSDimitry Andric         if (SM.isWrittenInSameFile(BeginLoc, EndLoc)) {
395ac9a064cSDimitry Andric           Loc = SM.getFileLoc(Loc);
396ac9a064cSDimitry Andric           Region.setStartLoc(Loc);
397ac9a064cSDimitry Andric           Region.setEndLoc(SM.getFileLoc(Region.getEndLoc()));
398ac9a064cSDimitry Andric         }
399ac9a064cSDimitry Andric       }
400ac9a064cSDimitry Andric 
4015e20cdd8SDimitry Andric       FileID File = SM.getFileID(Loc);
4022b6b257fSDimitry Andric       if (!Visited.insert(File).second)
4035e20cdd8SDimitry Andric         continue;
4042b6b257fSDimitry Andric 
405ac9a064cSDimitry Andric       assert(SystemHeadersCoverage ||
406ac9a064cSDimitry Andric              !SM.isInSystemHeader(SM.getSpellingLoc(Loc)));
4075e20cdd8SDimitry Andric 
4085e20cdd8SDimitry Andric       unsigned Depth = 0;
4095e20cdd8SDimitry Andric       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
41045b53394SDimitry Andric            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
4115e20cdd8SDimitry Andric         ++Depth;
4125e20cdd8SDimitry Andric       FileLocs.push_back(std::make_pair(Loc, Depth));
4135e20cdd8SDimitry Andric     }
41422989816SDimitry Andric     llvm::stable_sort(FileLocs, llvm::less_second());
4155e20cdd8SDimitry Andric 
4165e20cdd8SDimitry Andric     for (const auto &FL : FileLocs) {
4175e20cdd8SDimitry Andric       SourceLocation Loc = FL.first;
4185e20cdd8SDimitry Andric       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
419b1c73532SDimitry Andric       auto Entry = SM.getFileEntryRefForID(SpellingFile);
42006d4ba38SDimitry Andric       if (!Entry)
4215e20cdd8SDimitry Andric         continue;
42206d4ba38SDimitry Andric 
4235e20cdd8SDimitry Andric       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
424b1c73532SDimitry Andric       Mapping.push_back(CVM.getFileID(*Entry));
4255e20cdd8SDimitry Andric     }
42606d4ba38SDimitry Andric   }
42706d4ba38SDimitry Andric 
42848675466SDimitry Andric   /// Get the coverage mapping file ID for \c Loc.
4295e20cdd8SDimitry Andric   ///
430e3b55780SDimitry Andric   /// If such file id doesn't exist, return std::nullopt.
getCoverageFileID(SourceLocation Loc)431e3b55780SDimitry Andric   std::optional<unsigned> getCoverageFileID(SourceLocation Loc) {
4325e20cdd8SDimitry Andric     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
4335e20cdd8SDimitry Andric     if (Mapping != FileIDMapping.end())
4345e20cdd8SDimitry Andric       return Mapping->second.first;
435e3b55780SDimitry Andric     return std::nullopt;
43606d4ba38SDimitry Andric   }
43706d4ba38SDimitry Andric 
438b60736ecSDimitry Andric   /// This shrinks the skipped range if it spans a line that contains a
439b60736ecSDimitry Andric   /// non-comment token. If shrinking the skipped range would make it empty,
440e3b55780SDimitry Andric   /// this returns std::nullopt.
441145449b1SDimitry Andric   /// Note this function can potentially be expensive because
442145449b1SDimitry Andric   /// getSpellingLineNumber uses getLineNumber, which is expensive.
adjustSkippedRange(SourceManager & SM,SourceLocation LocStart,SourceLocation LocEnd,SourceLocation PrevTokLoc,SourceLocation NextTokLoc)443e3b55780SDimitry Andric   std::optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
444b60736ecSDimitry Andric                                                    SourceLocation LocStart,
445b60736ecSDimitry Andric                                                    SourceLocation LocEnd,
446b60736ecSDimitry Andric                                                    SourceLocation PrevTokLoc,
447b60736ecSDimitry Andric                                                    SourceLocation NextTokLoc) {
448b60736ecSDimitry Andric     SpellingRegion SR{SM, LocStart, LocEnd};
449b60736ecSDimitry Andric     SR.ColumnStart = 1;
450b60736ecSDimitry Andric     if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
451b60736ecSDimitry Andric         SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
452b60736ecSDimitry Andric       SR.LineStart++;
453b60736ecSDimitry Andric     if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
454b60736ecSDimitry Andric         SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
455b60736ecSDimitry Andric       SR.LineEnd--;
456b60736ecSDimitry Andric       SR.ColumnEnd++;
457b60736ecSDimitry Andric     }
458b60736ecSDimitry Andric     if (SR.isInSourceOrder())
459b60736ecSDimitry Andric       return SR;
460e3b55780SDimitry Andric     return std::nullopt;
461b60736ecSDimitry Andric   }
462b60736ecSDimitry Andric 
46348675466SDimitry Andric   /// Gather all the regions that were skipped by the preprocessor
464b60736ecSDimitry Andric   /// using the constructs like #if or comments.
gatherSkippedRegions()46506d4ba38SDimitry Andric   void gatherSkippedRegions() {
46606d4ba38SDimitry Andric     /// An array of the minimum lineStarts and the maximum lineEnds
46706d4ba38SDimitry Andric     /// for mapping regions from the appropriate source files.
46806d4ba38SDimitry Andric     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
46906d4ba38SDimitry Andric     FileLineRanges.resize(
47006d4ba38SDimitry Andric         FileIDMapping.size(),
47106d4ba38SDimitry Andric         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
47206d4ba38SDimitry Andric     for (const auto &R : MappingRegions) {
47306d4ba38SDimitry Andric       FileLineRanges[R.FileID].first =
47406d4ba38SDimitry Andric           std::min(FileLineRanges[R.FileID].first, R.LineStart);
47506d4ba38SDimitry Andric       FileLineRanges[R.FileID].second =
47606d4ba38SDimitry Andric           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
47706d4ba38SDimitry Andric     }
47806d4ba38SDimitry Andric 
47906d4ba38SDimitry Andric     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
480b60736ecSDimitry Andric     for (auto &I : SkippedRanges) {
481b60736ecSDimitry Andric       SourceRange Range = I.Range;
482b60736ecSDimitry Andric       auto LocStart = Range.getBegin();
483b60736ecSDimitry Andric       auto LocEnd = Range.getEnd();
4845e20cdd8SDimitry Andric       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
4855e20cdd8SDimitry Andric              "region spans multiple files");
48606d4ba38SDimitry Andric 
4875e20cdd8SDimitry Andric       auto CovFileID = getCoverageFileID(LocStart);
4885e20cdd8SDimitry Andric       if (!CovFileID)
48906d4ba38SDimitry Andric         continue;
490e3b55780SDimitry Andric       std::optional<SpellingRegion> SR;
491145449b1SDimitry Andric       if (I.isComment())
492145449b1SDimitry Andric         SR = adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc,
493145449b1SDimitry Andric                                 I.NextTokLoc);
494145449b1SDimitry Andric       else if (I.isPPIfElse() || I.isEmptyLine())
495145449b1SDimitry Andric         SR = {SM, LocStart, LocEnd};
496145449b1SDimitry Andric 
497145449b1SDimitry Andric       if (!SR)
498b60736ecSDimitry Andric         continue;
4995e20cdd8SDimitry Andric       auto Region = CounterMappingRegion::makeSkipped(
500b60736ecSDimitry Andric           *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
501b60736ecSDimitry Andric           SR->ColumnEnd);
50206d4ba38SDimitry Andric       // Make sure that we only collect the regions that are inside
50348675466SDimitry Andric       // the source code of this function.
5045e20cdd8SDimitry Andric       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
5055e20cdd8SDimitry Andric           Region.LineEnd <= FileLineRanges[*CovFileID].second)
50606d4ba38SDimitry Andric         MappingRegions.push_back(Region);
50706d4ba38SDimitry Andric     }
50806d4ba38SDimitry Andric   }
50906d4ba38SDimitry Andric 
51048675466SDimitry Andric   /// Generate the coverage counter mapping regions from collected
51106d4ba38SDimitry Andric   /// source regions.
emitSourceRegions(const SourceRegionFilter & Filter)512bab175ecSDimitry Andric   void emitSourceRegions(const SourceRegionFilter &Filter) {
5135e20cdd8SDimitry Andric     for (const auto &Region : SourceRegions) {
5145e20cdd8SDimitry Andric       assert(Region.hasEndLoc() && "incomplete region");
51506d4ba38SDimitry Andric 
516676fbe81SDimitry Andric       SourceLocation LocStart = Region.getBeginLoc();
51745b53394SDimitry Andric       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
51806d4ba38SDimitry Andric 
5197fa27ce4SDimitry Andric       // Ignore regions from system headers unless collecting coverage from
5207fa27ce4SDimitry Andric       // system headers is explicitly enabled.
5217fa27ce4SDimitry Andric       if (!SystemHeadersCoverage &&
522ac9a064cSDimitry Andric           SM.isInSystemHeader(SM.getSpellingLoc(LocStart))) {
523ac9a064cSDimitry Andric         assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
524ac9a064cSDimitry Andric                "Don't suppress the condition in system headers");
5252b6b257fSDimitry Andric         continue;
526ac9a064cSDimitry Andric       }
5272b6b257fSDimitry Andric 
5285e20cdd8SDimitry Andric       auto CovFileID = getCoverageFileID(LocStart);
5295e20cdd8SDimitry Andric       // Ignore regions that don't have a file, such as builtin macros.
530ac9a064cSDimitry Andric       if (!CovFileID) {
531ac9a064cSDimitry Andric         assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
532ac9a064cSDimitry Andric                "Don't suppress the condition in non-file regions");
53306d4ba38SDimitry Andric         continue;
534ac9a064cSDimitry Andric       }
53506d4ba38SDimitry Andric 
5365e20cdd8SDimitry Andric       SourceLocation LocEnd = Region.getEndLoc();
5375e20cdd8SDimitry Andric       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
5385e20cdd8SDimitry Andric              "region spans multiple files");
5395e20cdd8SDimitry Andric 
540bab175ecSDimitry Andric       // Don't add code regions for the area covered by expansion regions.
541bab175ecSDimitry Andric       // This not only suppresses redundant regions, but sometimes prevents
542bab175ecSDimitry Andric       // creating regions with wrong counters if, for example, a statement's
543bab175ecSDimitry Andric       // body ends at the end of a nested macro.
544ac9a064cSDimitry Andric       if (Filter.count(std::make_pair(LocStart, LocEnd))) {
545ac9a064cSDimitry Andric         assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
546ac9a064cSDimitry Andric                "Don't suppress the condition");
547bab175ecSDimitry Andric         continue;
548ac9a064cSDimitry Andric       }
549bab175ecSDimitry Andric 
550461a67faSDimitry Andric       // Find the spelling locations for the mapping region.
551461a67faSDimitry Andric       SpellingRegion SR{SM, LocStart, LocEnd};
552461a67faSDimitry Andric       assert(SR.isInSourceOrder() && "region start and end out of order");
55306d4ba38SDimitry Andric 
554461a67faSDimitry Andric       if (Region.isGap()) {
555461a67faSDimitry Andric         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
556461a67faSDimitry Andric             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
557461a67faSDimitry Andric             SR.LineEnd, SR.ColumnEnd));
5584df029ccSDimitry Andric       } else if (Region.isSkipped()) {
5594df029ccSDimitry Andric         MappingRegions.push_back(CounterMappingRegion::makeSkipped(
5604df029ccSDimitry Andric             *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd,
5614df029ccSDimitry Andric             SR.ColumnEnd));
562b60736ecSDimitry Andric       } else if (Region.isBranch()) {
563b60736ecSDimitry Andric         MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
564ac9a064cSDimitry Andric             Region.getCounter(), Region.getFalseCounter(), *CovFileID,
565ac9a064cSDimitry Andric             SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd,
566ac9a064cSDimitry Andric             Region.getMCDCParams()));
567aca2e42cSDimitry Andric       } else if (Region.isMCDCDecision()) {
568aca2e42cSDimitry Andric         MappingRegions.push_back(CounterMappingRegion::makeDecisionRegion(
569ac9a064cSDimitry Andric             Region.getMCDCDecisionParams(), *CovFileID, SR.LineStart,
570ac9a064cSDimitry Andric             SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
571461a67faSDimitry Andric       } else {
5725e20cdd8SDimitry Andric         MappingRegions.push_back(CounterMappingRegion::makeRegion(
573461a67faSDimitry Andric             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
574461a67faSDimitry Andric             SR.LineEnd, SR.ColumnEnd));
575461a67faSDimitry Andric       }
5765e20cdd8SDimitry Andric     }
5775e20cdd8SDimitry Andric   }
5785e20cdd8SDimitry Andric 
57948675466SDimitry Andric   /// Generate expansion regions for each virtual file we've seen.
emitExpansionRegions()580bab175ecSDimitry Andric   SourceRegionFilter emitExpansionRegions() {
581bab175ecSDimitry Andric     SourceRegionFilter Filter;
5825e20cdd8SDimitry Andric     for (const auto &FM : FileIDMapping) {
5835e20cdd8SDimitry Andric       SourceLocation ExpandedLoc = FM.second.second;
584ac9a064cSDimitry Andric       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc, false);
5855e20cdd8SDimitry Andric       if (ParentLoc.isInvalid())
58606d4ba38SDimitry Andric         continue;
58706d4ba38SDimitry Andric 
5885e20cdd8SDimitry Andric       auto ParentFileID = getCoverageFileID(ParentLoc);
5895e20cdd8SDimitry Andric       if (!ParentFileID)
5905e20cdd8SDimitry Andric         continue;
5915e20cdd8SDimitry Andric       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
5925e20cdd8SDimitry Andric       assert(ExpandedFileID && "expansion in uncovered file");
5935e20cdd8SDimitry Andric 
5945e20cdd8SDimitry Andric       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
5955e20cdd8SDimitry Andric       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
5965e20cdd8SDimitry Andric              "region spans multiple files");
597bab175ecSDimitry Andric       Filter.insert(std::make_pair(ParentLoc, LocEnd));
5985e20cdd8SDimitry Andric 
599461a67faSDimitry Andric       SpellingRegion SR{SM, ParentLoc, LocEnd};
600461a67faSDimitry Andric       assert(SR.isInSourceOrder() && "region start and end out of order");
6015e20cdd8SDimitry Andric       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
602461a67faSDimitry Andric           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
603461a67faSDimitry Andric           SR.LineEnd, SR.ColumnEnd));
60406d4ba38SDimitry Andric     }
605bab175ecSDimitry Andric     return Filter;
60606d4ba38SDimitry Andric   }
60706d4ba38SDimitry Andric };
60806d4ba38SDimitry Andric 
60948675466SDimitry Andric /// Creates unreachable coverage regions for the functions that
61006d4ba38SDimitry Andric /// are not emitted.
61106d4ba38SDimitry Andric struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
EmptyCoverageMappingBuilder__anon015dba650211::EmptyCoverageMappingBuilder61206d4ba38SDimitry Andric   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
61306d4ba38SDimitry Andric                               const LangOptions &LangOpts)
61406d4ba38SDimitry Andric       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
61506d4ba38SDimitry Andric 
VisitDecl__anon015dba650211::EmptyCoverageMappingBuilder61606d4ba38SDimitry Andric   void VisitDecl(const Decl *D) {
61706d4ba38SDimitry Andric     if (!D->hasBody())
61806d4ba38SDimitry Andric       return;
61906d4ba38SDimitry Andric     auto Body = D->getBody();
6202b6b257fSDimitry Andric     SourceLocation Start = getStart(Body);
6212b6b257fSDimitry Andric     SourceLocation End = getEnd(Body);
6222b6b257fSDimitry Andric     if (!SM.isWrittenInSameFile(Start, End)) {
6232b6b257fSDimitry Andric       // Walk up to find the common ancestor.
6242b6b257fSDimitry Andric       // Correct the locations accordingly.
6252b6b257fSDimitry Andric       FileID StartFileID = SM.getFileID(Start);
6262b6b257fSDimitry Andric       FileID EndFileID = SM.getFileID(End);
6272b6b257fSDimitry Andric       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
6282b6b257fSDimitry Andric         Start = getIncludeOrExpansionLoc(Start);
6292b6b257fSDimitry Andric         assert(Start.isValid() &&
6302b6b257fSDimitry Andric                "Declaration start location not nested within a known region");
6312b6b257fSDimitry Andric         StartFileID = SM.getFileID(Start);
6322b6b257fSDimitry Andric       }
6332b6b257fSDimitry Andric       while (StartFileID != EndFileID) {
6342b6b257fSDimitry Andric         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
6352b6b257fSDimitry Andric         assert(End.isValid() &&
6362b6b257fSDimitry Andric                "Declaration end location not nested within a known region");
6372b6b257fSDimitry Andric         EndFileID = SM.getFileID(End);
6382b6b257fSDimitry Andric       }
6392b6b257fSDimitry Andric     }
6402b6b257fSDimitry Andric     SourceRegions.emplace_back(Counter(), Start, End);
64106d4ba38SDimitry Andric   }
64206d4ba38SDimitry Andric 
64348675466SDimitry Andric   /// Write the mapping data to the output stream
write__anon015dba650211::EmptyCoverageMappingBuilder64406d4ba38SDimitry Andric   void write(llvm::raw_ostream &OS) {
64506d4ba38SDimitry Andric     SmallVector<unsigned, 16> FileIDMapping;
6465e20cdd8SDimitry Andric     gatherFileIDs(FileIDMapping);
647bab175ecSDimitry Andric     emitSourceRegions(SourceRegionFilter());
64806d4ba38SDimitry Andric 
649631f6b77SDimitry Andric     if (MappingRegions.empty())
650631f6b77SDimitry Andric       return;
651631f6b77SDimitry Andric 
652e3b55780SDimitry Andric     CoverageMappingWriter Writer(FileIDMapping, std::nullopt, MappingRegions);
65306d4ba38SDimitry Andric     Writer.write(OS);
65406d4ba38SDimitry Andric   }
65506d4ba38SDimitry Andric };
65606d4ba38SDimitry Andric 
657aca2e42cSDimitry Andric /// A wrapper object for maintaining stacks to track the resursive AST visitor
658aca2e42cSDimitry Andric /// walks for the purpose of assigning IDs to leaf-level conditions measured by
659aca2e42cSDimitry Andric /// MC/DC. The object is created with a reference to the MCDCBitmapMap that was
660aca2e42cSDimitry Andric /// created during the initial AST walk. The presence of a bitmap associated
661aca2e42cSDimitry Andric /// with a boolean expression (top-level logical operator nest) indicates that
662aca2e42cSDimitry Andric /// the boolean expression qualified for MC/DC.  The resulting condition IDs
663aca2e42cSDimitry Andric /// are preserved in a map reference that is also provided during object
664aca2e42cSDimitry Andric /// creation.
665aca2e42cSDimitry Andric struct MCDCCoverageBuilder {
666aca2e42cSDimitry Andric 
667aca2e42cSDimitry Andric   /// The AST walk recursively visits nested logical-AND or logical-OR binary
668aca2e42cSDimitry Andric   /// operator nodes and then visits their LHS and RHS children nodes.  As this
669aca2e42cSDimitry Andric   /// happens, the algorithm will assign IDs to each operator's LHS and RHS side
670aca2e42cSDimitry Andric   /// as the walk moves deeper into the nest.  At each level of the recursive
671aca2e42cSDimitry Andric   /// nest, the LHS and RHS may actually correspond to larger subtrees (not
672aca2e42cSDimitry Andric   /// leaf-conditions). If this is the case, when that node is visited, the ID
673aca2e42cSDimitry Andric   /// assigned to the subtree is re-assigned to its LHS, and a new ID is given
674aca2e42cSDimitry Andric   /// to its RHS. At the end of the walk, all leaf-level conditions will have a
675aca2e42cSDimitry Andric   /// unique ID -- keep in mind that the final set of IDs may not be in
676aca2e42cSDimitry Andric   /// numerical order from left to right.
677aca2e42cSDimitry Andric   ///
678aca2e42cSDimitry Andric   /// Example: "x = (A && B) || (C && D) || (D && F)"
679aca2e42cSDimitry Andric   ///
680aca2e42cSDimitry Andric   ///      Visit Depth1:
681aca2e42cSDimitry Andric   ///              (A && B) || (C && D) || (D && F)
682aca2e42cSDimitry Andric   ///              ^-------LHS--------^    ^-RHS--^
683aca2e42cSDimitry Andric   ///                      ID=1              ID=2
684aca2e42cSDimitry Andric   ///
685aca2e42cSDimitry Andric   ///      Visit LHS-Depth2:
686aca2e42cSDimitry Andric   ///              (A && B) || (C && D)
687aca2e42cSDimitry Andric   ///              ^-LHS--^    ^-RHS--^
688aca2e42cSDimitry Andric   ///                ID=1        ID=3
689aca2e42cSDimitry Andric   ///
690aca2e42cSDimitry Andric   ///      Visit LHS-Depth3:
691aca2e42cSDimitry Andric   ///               (A && B)
692aca2e42cSDimitry Andric   ///               LHS   RHS
693aca2e42cSDimitry Andric   ///               ID=1  ID=4
694aca2e42cSDimitry Andric   ///
695aca2e42cSDimitry Andric   ///      Visit RHS-Depth3:
696aca2e42cSDimitry Andric   ///                         (C && D)
697aca2e42cSDimitry Andric   ///                         LHS   RHS
698aca2e42cSDimitry Andric   ///                         ID=3  ID=5
699aca2e42cSDimitry Andric   ///
700aca2e42cSDimitry Andric   ///      Visit RHS-Depth2:              (D && F)
701aca2e42cSDimitry Andric   ///                                     LHS   RHS
702aca2e42cSDimitry Andric   ///                                     ID=2  ID=6
703aca2e42cSDimitry Andric   ///
704aca2e42cSDimitry Andric   ///      Visit Depth1:
705aca2e42cSDimitry Andric   ///              (A && B)  || (C && D)  || (D && F)
706aca2e42cSDimitry Andric   ///              ID=1  ID=4   ID=3  ID=5   ID=2  ID=6
707aca2e42cSDimitry Andric   ///
708aca2e42cSDimitry Andric   /// A node ID of '0' always means MC/DC isn't being tracked.
709aca2e42cSDimitry Andric   ///
7104df029ccSDimitry Andric   /// As the AST walk proceeds recursively, the algorithm will also use a stack
711aca2e42cSDimitry Andric   /// to track the IDs of logical-AND and logical-OR operations on the RHS so
712aca2e42cSDimitry Andric   /// that it can be determined which nodes are executed next, depending on how
713aca2e42cSDimitry Andric   /// a LHS or RHS of a logical-AND or logical-OR is evaluated.  This
714aca2e42cSDimitry Andric   /// information relies on the assigned IDs and are embedded within the
715aca2e42cSDimitry Andric   /// coverage region IDs of each branch region associated with a leaf-level
716aca2e42cSDimitry Andric   /// condition. This information helps the visualization tool reconstruct all
7174df029ccSDimitry Andric   /// possible test vectors for the purposes of MC/DC analysis. If a "next" node
718aca2e42cSDimitry Andric   /// ID is '0', it means it's the end of the test vector. The following rules
719aca2e42cSDimitry Andric   /// are used:
720aca2e42cSDimitry Andric   ///
721aca2e42cSDimitry Andric   /// For logical-AND ("LHS && RHS"):
722aca2e42cSDimitry Andric   /// - If LHS is TRUE, execution goes to the RHS node.
723aca2e42cSDimitry Andric   /// - If LHS is FALSE, execution goes to the LHS node of the next logical-OR.
724aca2e42cSDimitry Andric   ///   If that does not exist, execution exits (ID == 0).
725aca2e42cSDimitry Andric   ///
726aca2e42cSDimitry Andric   /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND.
727aca2e42cSDimitry Andric   ///   If that does not exist, execution exits (ID == 0).
728aca2e42cSDimitry Andric   /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR.
729aca2e42cSDimitry Andric   ///   If that does not exist, execution exits (ID == 0).
730aca2e42cSDimitry Andric   ///
731aca2e42cSDimitry Andric   /// For logical-OR ("LHS || RHS"):
732aca2e42cSDimitry Andric   /// - If LHS is TRUE, execution goes to the LHS node of the next logical-AND.
733aca2e42cSDimitry Andric   ///   If that does not exist, execution exits (ID == 0).
734aca2e42cSDimitry Andric   /// - If LHS is FALSE, execution goes to the RHS node.
735aca2e42cSDimitry Andric   ///
736aca2e42cSDimitry Andric   /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND.
737aca2e42cSDimitry Andric   ///   If that does not exist, execution exits (ID == 0).
738aca2e42cSDimitry Andric   /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR.
739aca2e42cSDimitry Andric   ///   If that does not exist, execution exits (ID == 0).
740aca2e42cSDimitry Andric   ///
741aca2e42cSDimitry Andric   /// Finally, the condition IDs are also used when instrumenting the code to
742aca2e42cSDimitry Andric   /// indicate a unique offset into a temporary bitmap that represents the true
743aca2e42cSDimitry Andric   /// or false evaluation of that particular condition.
744aca2e42cSDimitry Andric   ///
745aca2e42cSDimitry Andric   /// NOTE regarding the use of CodeGenFunction::stripCond(). Even though, for
746aca2e42cSDimitry Andric   /// simplicity, parentheses and unary logical-NOT operators are considered
747aca2e42cSDimitry Andric   /// part of their underlying condition for both MC/DC and branch coverage, the
748aca2e42cSDimitry Andric   /// condition IDs themselves are assigned and tracked using the underlying
749aca2e42cSDimitry Andric   /// condition itself.  This is done solely for consistency since parentheses
750aca2e42cSDimitry Andric   /// and logical-NOTs are ignored when checking whether the condition is
751aca2e42cSDimitry Andric   /// actually an instrumentable condition. This can also make debugging a bit
752aca2e42cSDimitry Andric   /// easier.
753aca2e42cSDimitry Andric 
754aca2e42cSDimitry Andric private:
755aca2e42cSDimitry Andric   CodeGenModule &CGM;
756aca2e42cSDimitry Andric 
757ac9a064cSDimitry Andric   llvm::SmallVector<mcdc::ConditionIDs> DecisionStack;
758ac9a064cSDimitry Andric   MCDC::State &MCDCState;
759ac9a064cSDimitry Andric   const Stmt *DecisionStmt = nullptr;
760ac9a064cSDimitry Andric   mcdc::ConditionID NextID = 0;
761aca2e42cSDimitry Andric   bool NotMapped = false;
762aca2e42cSDimitry Andric 
763ac9a064cSDimitry Andric   /// Represent a sentinel value as a pair of final decisions for the bottom
764ac9a064cSDimitry Andric   // of DecisionStack.
765ac9a064cSDimitry Andric   static constexpr mcdc::ConditionIDs DecisionStackSentinel{-1, -1};
7664df029ccSDimitry Andric 
767aca2e42cSDimitry Andric   /// Is this a logical-AND operation?
isLAnd__anon015dba650211::MCDCCoverageBuilder768aca2e42cSDimitry Andric   bool isLAnd(const BinaryOperator *E) const {
769aca2e42cSDimitry Andric     return E->getOpcode() == BO_LAnd;
770aca2e42cSDimitry Andric   }
771aca2e42cSDimitry Andric 
772aca2e42cSDimitry Andric public:
MCDCCoverageBuilder__anon015dba650211::MCDCCoverageBuilder773ac9a064cSDimitry Andric   MCDCCoverageBuilder(CodeGenModule &CGM, MCDC::State &MCDCState)
774ac9a064cSDimitry Andric       : CGM(CGM), DecisionStack(1, DecisionStackSentinel),
775ac9a064cSDimitry Andric         MCDCState(MCDCState) {}
776aca2e42cSDimitry Andric 
7774df029ccSDimitry Andric   /// Return whether the build of the control flow map is at the top-level
7784df029ccSDimitry Andric   /// (root) of a logical operator nest in a boolean expression prior to the
7794df029ccSDimitry Andric   /// assignment of condition IDs.
isIdle__anon015dba650211::MCDCCoverageBuilder780ac9a064cSDimitry Andric   bool isIdle() const { return (NextID == 0 && !NotMapped); }
781aca2e42cSDimitry Andric 
7824df029ccSDimitry Andric   /// Return whether any IDs have been assigned in the build of the control
7834df029ccSDimitry Andric   /// flow map, indicating that the map is being generated for this boolean
7844df029ccSDimitry Andric   /// expression.
isBuilding__anon015dba650211::MCDCCoverageBuilder785ac9a064cSDimitry Andric   bool isBuilding() const { return (NextID > 0); }
7864df029ccSDimitry Andric 
7874df029ccSDimitry Andric   /// Set the given condition's ID.
setCondID__anon015dba650211::MCDCCoverageBuilder788ac9a064cSDimitry Andric   void setCondID(const Expr *Cond, mcdc::ConditionID ID) {
789ac9a064cSDimitry Andric     MCDCState.BranchByStmt[CodeGenFunction::stripCond(Cond)] = {ID,
790ac9a064cSDimitry Andric                                                                 DecisionStmt};
791aca2e42cSDimitry Andric   }
792aca2e42cSDimitry Andric 
793aca2e42cSDimitry Andric   /// Return the ID of a given condition.
getCondID__anon015dba650211::MCDCCoverageBuilder794ac9a064cSDimitry Andric   mcdc::ConditionID getCondID(const Expr *Cond) const {
795ac9a064cSDimitry Andric     auto I = MCDCState.BranchByStmt.find(CodeGenFunction::stripCond(Cond));
796ac9a064cSDimitry Andric     if (I == MCDCState.BranchByStmt.end())
797ac9a064cSDimitry Andric       return -1;
798aca2e42cSDimitry Andric     else
799ac9a064cSDimitry Andric       return I->second.ID;
800aca2e42cSDimitry Andric   }
801aca2e42cSDimitry Andric 
8024df029ccSDimitry Andric   /// Return the LHS Decision ([0,0] if not set).
back__anon015dba650211::MCDCCoverageBuilder803ac9a064cSDimitry Andric   const mcdc::ConditionIDs &back() const { return DecisionStack.back(); }
8044df029ccSDimitry Andric 
805aca2e42cSDimitry Andric   /// Push the binary operator statement to track the nest level and assign IDs
806aca2e42cSDimitry Andric   /// to the operator's LHS and RHS.  The RHS may be a larger subtree that is
807aca2e42cSDimitry Andric   /// broken up on successive levels.
pushAndAssignIDs__anon015dba650211::MCDCCoverageBuilder808aca2e42cSDimitry Andric   void pushAndAssignIDs(const BinaryOperator *E) {
809aca2e42cSDimitry Andric     if (!CGM.getCodeGenOpts().MCDCCoverage)
810aca2e42cSDimitry Andric       return;
811aca2e42cSDimitry Andric 
812aca2e42cSDimitry Andric     // If binary expression is disqualified, don't do mapping.
813ac9a064cSDimitry Andric     if (!isBuilding() &&
814ac9a064cSDimitry Andric         !MCDCState.DecisionByStmt.contains(CodeGenFunction::stripCond(E)))
815aca2e42cSDimitry Andric       NotMapped = true;
816aca2e42cSDimitry Andric 
817aca2e42cSDimitry Andric     // Don't go any further if we don't need to map condition IDs.
818aca2e42cSDimitry Andric     if (NotMapped)
819aca2e42cSDimitry Andric       return;
820aca2e42cSDimitry Andric 
821ac9a064cSDimitry Andric     if (NextID == 0) {
822ac9a064cSDimitry Andric       DecisionStmt = E;
823ac9a064cSDimitry Andric       assert(MCDCState.DecisionByStmt.contains(E));
824ac9a064cSDimitry Andric     }
825ac9a064cSDimitry Andric 
826ac9a064cSDimitry Andric     const mcdc::ConditionIDs &ParentDecision = DecisionStack.back();
8274df029ccSDimitry Andric 
828aca2e42cSDimitry Andric     // If the operator itself has an assigned ID, this means it represents a
8294df029ccSDimitry Andric     // larger subtree.  In this case, assign that ID to its LHS node.  Its RHS
8304df029ccSDimitry Andric     // will receive a new ID below. Otherwise, assign ID+1 to LHS.
831ac9a064cSDimitry Andric     if (MCDCState.BranchByStmt.contains(CodeGenFunction::stripCond(E)))
8324df029ccSDimitry Andric       setCondID(E->getLHS(), getCondID(E));
8334df029ccSDimitry Andric     else
8344df029ccSDimitry Andric       setCondID(E->getLHS(), NextID++);
835aca2e42cSDimitry Andric 
8364df029ccSDimitry Andric     // Assign a ID+1 for the RHS.
837ac9a064cSDimitry Andric     mcdc::ConditionID RHSid = NextID++;
8384df029ccSDimitry Andric     setCondID(E->getRHS(), RHSid);
8394df029ccSDimitry Andric 
8404df029ccSDimitry Andric     // Push the LHS decision IDs onto the DecisionStack.
8414df029ccSDimitry Andric     if (isLAnd(E))
842ac9a064cSDimitry Andric       DecisionStack.push_back({ParentDecision[false], RHSid});
8434df029ccSDimitry Andric     else
844ac9a064cSDimitry Andric       DecisionStack.push_back({RHSid, ParentDecision[true]});
845aca2e42cSDimitry Andric   }
846aca2e42cSDimitry Andric 
8474df029ccSDimitry Andric   /// Pop and return the LHS Decision ([0,0] if not set).
pop__anon015dba650211::MCDCCoverageBuilder848ac9a064cSDimitry Andric   mcdc::ConditionIDs pop() {
8494df029ccSDimitry Andric     if (!CGM.getCodeGenOpts().MCDCCoverage || NotMapped)
850ac9a064cSDimitry Andric       return DecisionStackSentinel;
851aca2e42cSDimitry Andric 
8524df029ccSDimitry Andric     assert(DecisionStack.size() > 1);
853ac9a064cSDimitry Andric     return DecisionStack.pop_back_val();
854aca2e42cSDimitry Andric   }
855aca2e42cSDimitry Andric 
8564df029ccSDimitry Andric   /// Return the total number of conditions and reset the state. The number of
8574df029ccSDimitry Andric   /// conditions is zero if the expression isn't mapped.
getTotalConditionsAndReset__anon015dba650211::MCDCCoverageBuilder8584df029ccSDimitry Andric   unsigned getTotalConditionsAndReset(const BinaryOperator *E) {
859aca2e42cSDimitry Andric     if (!CGM.getCodeGenOpts().MCDCCoverage)
860aca2e42cSDimitry Andric       return 0;
861aca2e42cSDimitry Andric 
8624df029ccSDimitry Andric     assert(!isIdle());
8634df029ccSDimitry Andric     assert(DecisionStack.size() == 1);
864aca2e42cSDimitry Andric 
865aca2e42cSDimitry Andric     // Reset state if not doing mapping.
8664df029ccSDimitry Andric     if (NotMapped) {
867aca2e42cSDimitry Andric       NotMapped = false;
868ac9a064cSDimitry Andric       assert(NextID == 0);
869aca2e42cSDimitry Andric       return 0;
870aca2e42cSDimitry Andric     }
871aca2e42cSDimitry Andric 
8724df029ccSDimitry Andric     // Set number of conditions and reset.
873ac9a064cSDimitry Andric     unsigned TotalConds = NextID;
874aca2e42cSDimitry Andric 
875aca2e42cSDimitry Andric     // Reset ID back to beginning.
876ac9a064cSDimitry Andric     NextID = 0;
8774df029ccSDimitry Andric 
878aca2e42cSDimitry Andric     return TotalConds;
879aca2e42cSDimitry Andric   }
880aca2e42cSDimitry Andric };
881aca2e42cSDimitry Andric 
88248675466SDimitry Andric /// A StmtVisitor that creates coverage mapping regions which map
88306d4ba38SDimitry Andric /// from the source code locations to the PGO counters.
88406d4ba38SDimitry Andric struct CounterCoverageMappingBuilder
88506d4ba38SDimitry Andric     : public CoverageMappingBuilder,
88606d4ba38SDimitry Andric       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
88748675466SDimitry Andric   /// The map of statements to count values.
88806d4ba38SDimitry Andric   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
88906d4ba38SDimitry Andric 
890ac9a064cSDimitry Andric   MCDC::State &MCDCState;
891aca2e42cSDimitry Andric 
89248675466SDimitry Andric   /// A stack of currently live regions.
893aca2e42cSDimitry Andric   llvm::SmallVector<SourceMappingRegion> RegionStack;
894aca2e42cSDimitry Andric 
895ac9a064cSDimitry Andric   /// Set if the Expr should be handled as a leaf even if it is kind of binary
896ac9a064cSDimitry Andric   /// logical ops (&&, ||).
897ac9a064cSDimitry Andric   llvm::DenseSet<const Stmt *> LeafExprSet;
898ac9a064cSDimitry Andric 
899aca2e42cSDimitry Andric   /// An object to manage MCDC regions.
900aca2e42cSDimitry Andric   MCDCCoverageBuilder MCDCBuilder;
90106d4ba38SDimitry Andric 
90206d4ba38SDimitry Andric   CounterExpressionBuilder Builder;
90306d4ba38SDimitry Andric 
90448675466SDimitry Andric   /// A location in the most recently visited file or macro.
9055e20cdd8SDimitry Andric   ///
9065e20cdd8SDimitry Andric   /// This is used to adjust the active source regions appropriately when
9075e20cdd8SDimitry Andric   /// expressions cross file or macro boundaries.
9085e20cdd8SDimitry Andric   SourceLocation MostRecentLocation;
9095e20cdd8SDimitry Andric 
910344a3780SDimitry Andric   /// Whether the visitor at a terminate statement.
911344a3780SDimitry Andric   bool HasTerminateStmt = false;
912344a3780SDimitry Andric 
913344a3780SDimitry Andric   /// Gap region counter after terminate statement.
914344a3780SDimitry Andric   Counter GapRegionCounter;
915461a67faSDimitry Andric 
91648675466SDimitry Andric   /// Return a counter for the subtraction of \c RHS from \c LHS
subtractCounters__anon015dba650211::CounterCoverageMappingBuilder917145449b1SDimitry Andric   Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
918ac9a064cSDimitry Andric     assert(!llvm::EnableSingleByteCoverage &&
919ac9a064cSDimitry Andric            "cannot add counters when single byte coverage mode is enabled");
920145449b1SDimitry Andric     return Builder.subtract(LHS, RHS, Simplify);
92106d4ba38SDimitry Andric   }
92206d4ba38SDimitry Andric 
92348675466SDimitry Andric   /// Return a counter for the sum of \c LHS and \c RHS.
addCounters__anon015dba650211::CounterCoverageMappingBuilder924145449b1SDimitry Andric   Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) {
925ac9a064cSDimitry Andric     assert(!llvm::EnableSingleByteCoverage &&
926ac9a064cSDimitry Andric            "cannot add counters when single byte coverage mode is enabled");
927145449b1SDimitry Andric     return Builder.add(LHS, RHS, Simplify);
92806d4ba38SDimitry Andric   }
92906d4ba38SDimitry Andric 
addCounters__anon015dba650211::CounterCoverageMappingBuilder930145449b1SDimitry Andric   Counter addCounters(Counter C1, Counter C2, Counter C3,
931145449b1SDimitry Andric                       bool Simplify = true) {
932ac9a064cSDimitry Andric     assert(!llvm::EnableSingleByteCoverage &&
933ac9a064cSDimitry Andric            "cannot add counters when single byte coverage mode is enabled");
934145449b1SDimitry Andric     return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
9355e20cdd8SDimitry Andric   }
9365e20cdd8SDimitry Andric 
93748675466SDimitry Andric   /// Return the region counter for the given statement.
9385e20cdd8SDimitry Andric   ///
93906d4ba38SDimitry Andric   /// This should only be called on statements that have a dedicated counter.
getRegionCounter__anon015dba650211::CounterCoverageMappingBuilder9405e20cdd8SDimitry Andric   Counter getRegionCounter(const Stmt *S) {
9415e20cdd8SDimitry Andric     return Counter::getCounter(CounterMap[S]);
94206d4ba38SDimitry Andric   }
94306d4ba38SDimitry Andric 
94448675466SDimitry Andric   /// Push a region onto the stack.
9455e20cdd8SDimitry Andric   ///
9465e20cdd8SDimitry Andric   /// Returns the index on the stack where the region was pushed. This can be
9475e20cdd8SDimitry Andric   /// used with popRegions to exit a "scope", ending the region that was pushed.
pushRegion__anon015dba650211::CounterCoverageMappingBuilder948e3b55780SDimitry Andric   size_t pushRegion(Counter Count,
949e3b55780SDimitry Andric                     std::optional<SourceLocation> StartLoc = std::nullopt,
950e3b55780SDimitry Andric                     std::optional<SourceLocation> EndLoc = std::nullopt,
951aca2e42cSDimitry Andric                     std::optional<Counter> FalseCount = std::nullopt,
952ac9a064cSDimitry Andric                     const mcdc::Parameters &BranchParams = std::monostate()) {
953b60736ecSDimitry Andric 
954145449b1SDimitry Andric     if (StartLoc && !FalseCount) {
9555e20cdd8SDimitry Andric       MostRecentLocation = *StartLoc;
956461a67faSDimitry Andric     }
957b60736ecSDimitry Andric 
9587fa27ce4SDimitry Andric     // If either of these locations is invalid, something elsewhere in the
9597fa27ce4SDimitry Andric     // compiler has broken.
9607fa27ce4SDimitry Andric     assert((!StartLoc || StartLoc->isValid()) && "Start location is not valid");
9617fa27ce4SDimitry Andric     assert((!EndLoc || EndLoc->isValid()) && "End location is not valid");
9627fa27ce4SDimitry Andric 
9637fa27ce4SDimitry Andric     // However, we can still recover without crashing.
9647fa27ce4SDimitry Andric     // If either location is invalid, set it to std::nullopt to avoid
9657fa27ce4SDimitry Andric     // letting users of RegionStack think that region has a valid start/end
9667fa27ce4SDimitry Andric     // location.
9677fa27ce4SDimitry Andric     if (StartLoc && StartLoc->isInvalid())
9687fa27ce4SDimitry Andric       StartLoc = std::nullopt;
9697fa27ce4SDimitry Andric     if (EndLoc && EndLoc->isInvalid())
9707fa27ce4SDimitry Andric       EndLoc = std::nullopt;
971ac9a064cSDimitry Andric     RegionStack.emplace_back(Count, FalseCount, BranchParams, StartLoc, EndLoc);
972aca2e42cSDimitry Andric 
973aca2e42cSDimitry Andric     return RegionStack.size() - 1;
974aca2e42cSDimitry Andric   }
975aca2e42cSDimitry Andric 
pushRegion__anon015dba650211::CounterCoverageMappingBuilder976ac9a064cSDimitry Andric   size_t pushRegion(const mcdc::DecisionParameters &DecisionParams,
977aca2e42cSDimitry Andric                     std::optional<SourceLocation> StartLoc = std::nullopt,
978aca2e42cSDimitry Andric                     std::optional<SourceLocation> EndLoc = std::nullopt) {
979aca2e42cSDimitry Andric 
980ac9a064cSDimitry Andric     RegionStack.emplace_back(DecisionParams, StartLoc, EndLoc);
98106d4ba38SDimitry Andric 
9825e20cdd8SDimitry Andric     return RegionStack.size() - 1;
98306d4ba38SDimitry Andric   }
98406d4ba38SDimitry Andric 
locationDepth__anon015dba650211::CounterCoverageMappingBuilder985676fbe81SDimitry Andric   size_t locationDepth(SourceLocation Loc) {
986676fbe81SDimitry Andric     size_t Depth = 0;
987676fbe81SDimitry Andric     while (Loc.isValid()) {
988676fbe81SDimitry Andric       Loc = getIncludeOrExpansionLoc(Loc);
989676fbe81SDimitry Andric       Depth++;
990676fbe81SDimitry Andric     }
991676fbe81SDimitry Andric     return Depth;
992676fbe81SDimitry Andric   }
993676fbe81SDimitry Andric 
99448675466SDimitry Andric   /// Pop regions from the stack into the function's list of regions.
9955e20cdd8SDimitry Andric   ///
9965e20cdd8SDimitry Andric   /// Adds all regions from \c ParentIndex to the top of the stack to the
9975e20cdd8SDimitry Andric   /// function's \c SourceRegions.
popRegions__anon015dba650211::CounterCoverageMappingBuilder9985e20cdd8SDimitry Andric   void popRegions(size_t ParentIndex) {
9995e20cdd8SDimitry Andric     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
10005e20cdd8SDimitry Andric     while (RegionStack.size() > ParentIndex) {
10015e20cdd8SDimitry Andric       SourceMappingRegion &Region = RegionStack.back();
10027fa27ce4SDimitry Andric       if (Region.hasStartLoc() &&
10037fa27ce4SDimitry Andric           (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
1004676fbe81SDimitry Andric         SourceLocation StartLoc = Region.getBeginLoc();
10055e20cdd8SDimitry Andric         SourceLocation EndLoc = Region.hasEndLoc()
10065e20cdd8SDimitry Andric                                     ? Region.getEndLoc()
10075e20cdd8SDimitry Andric                                     : RegionStack[ParentIndex].getEndLoc();
1008b60736ecSDimitry Andric         bool isBranch = Region.isBranch();
1009676fbe81SDimitry Andric         size_t StartDepth = locationDepth(StartLoc);
1010676fbe81SDimitry Andric         size_t EndDepth = locationDepth(EndLoc);
10115e20cdd8SDimitry Andric         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
1012676fbe81SDimitry Andric           bool UnnestStart = StartDepth >= EndDepth;
1013676fbe81SDimitry Andric           bool UnnestEnd = EndDepth >= StartDepth;
1014676fbe81SDimitry Andric           if (UnnestEnd) {
1015b60736ecSDimitry Andric             // The region ends in a nested file or macro expansion. If the
1016b60736ecSDimitry Andric             // region is not a branch region, create a separate region for each
1017b60736ecSDimitry Andric             // expansion, and for all regions, update the EndLoc. Branch
1018b60736ecSDimitry Andric             // regions should not be split in order to keep a straightforward
1019b60736ecSDimitry Andric             // correspondance between the region and its associated branch
1020b60736ecSDimitry Andric             // condition, even if the condition spans multiple depths.
10215e20cdd8SDimitry Andric             SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
10225e20cdd8SDimitry Andric             assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
10235e20cdd8SDimitry Andric 
1024b60736ecSDimitry Andric             if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
1025b60736ecSDimitry Andric               SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
1026b60736ecSDimitry Andric                                          EndLoc);
10275e20cdd8SDimitry Andric 
10285e20cdd8SDimitry Andric             EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
102945b53394SDimitry Andric             if (EndLoc.isInvalid())
1030b60736ecSDimitry Andric               llvm::report_fatal_error(
1031b60736ecSDimitry Andric                   "File exit not handled before popRegions");
1032676fbe81SDimitry Andric             EndDepth--;
10335e20cdd8SDimitry Andric           }
1034676fbe81SDimitry Andric           if (UnnestStart) {
1035b60736ecSDimitry Andric             // The region ends in a nested file or macro expansion. If the
1036b60736ecSDimitry Andric             // region is not a branch region, create a separate region for each
1037b60736ecSDimitry Andric             // expansion, and for all regions, update the StartLoc. Branch
1038b60736ecSDimitry Andric             // regions should not be split in order to keep a straightforward
1039b60736ecSDimitry Andric             // correspondance between the region and its associated branch
1040b60736ecSDimitry Andric             // condition, even if the condition spans multiple depths.
1041676fbe81SDimitry Andric             SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
1042676fbe81SDimitry Andric             assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
1043676fbe81SDimitry Andric 
1044b60736ecSDimitry Andric             if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
1045b60736ecSDimitry Andric               SourceRegions.emplace_back(Region.getCounter(), StartLoc,
1046b60736ecSDimitry Andric                                          NestedLoc);
1047676fbe81SDimitry Andric 
1048676fbe81SDimitry Andric             StartLoc = getIncludeOrExpansionLoc(StartLoc);
1049676fbe81SDimitry Andric             if (StartLoc.isInvalid())
1050b60736ecSDimitry Andric               llvm::report_fatal_error(
1051b60736ecSDimitry Andric                   "File exit not handled before popRegions");
1052676fbe81SDimitry Andric             StartDepth--;
1053676fbe81SDimitry Andric           }
1054676fbe81SDimitry Andric         }
1055676fbe81SDimitry Andric         Region.setStartLoc(StartLoc);
10565e20cdd8SDimitry Andric         Region.setEndLoc(EndLoc);
10575e20cdd8SDimitry Andric 
1058b60736ecSDimitry Andric         if (!isBranch) {
10595e20cdd8SDimitry Andric           MostRecentLocation = EndLoc;
1060b60736ecSDimitry Andric           // If this region happens to span an entire expansion, we need to
1061b60736ecSDimitry Andric           // make sure we don't overlap the parent region with it.
10625e20cdd8SDimitry Andric           if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
10635e20cdd8SDimitry Andric               EndLoc == getEndOfFileOrMacro(EndLoc))
10645e20cdd8SDimitry Andric             MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
1065b60736ecSDimitry Andric         }
10665e20cdd8SDimitry Andric 
1067676fbe81SDimitry Andric         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
1068461a67faSDimitry Andric         assert(SpellingRegion(SM, Region).isInSourceOrder());
106945b53394SDimitry Andric         SourceRegions.push_back(Region);
10705e20cdd8SDimitry Andric       }
10715e20cdd8SDimitry Andric       RegionStack.pop_back();
10725e20cdd8SDimitry Andric     }
107306d4ba38SDimitry Andric   }
107406d4ba38SDimitry Andric 
107548675466SDimitry Andric   /// Return the currently active region.
getRegion__anon015dba650211::CounterCoverageMappingBuilder10765e20cdd8SDimitry Andric   SourceMappingRegion &getRegion() {
10775e20cdd8SDimitry Andric     assert(!RegionStack.empty() && "statement has no region");
10785e20cdd8SDimitry Andric     return RegionStack.back();
107906d4ba38SDimitry Andric   }
108006d4ba38SDimitry Andric 
1081676fbe81SDimitry Andric   /// Propagate counts through the children of \p S if \p VisitChildren is true.
1082676fbe81SDimitry Andric   /// Otherwise, only emit a count for \p S itself.
propagateCounts__anon015dba650211::CounterCoverageMappingBuilder1083676fbe81SDimitry Andric   Counter propagateCounts(Counter TopCount, const Stmt *S,
1084676fbe81SDimitry Andric                           bool VisitChildren = true) {
1085461a67faSDimitry Andric     SourceLocation StartLoc = getStart(S);
1086461a67faSDimitry Andric     SourceLocation EndLoc = getEnd(S);
1087461a67faSDimitry Andric     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
1088676fbe81SDimitry Andric     if (VisitChildren)
10895e20cdd8SDimitry Andric       Visit(S);
10905e20cdd8SDimitry Andric     Counter ExitCount = getRegion().getCounter();
10915e20cdd8SDimitry Andric     popRegions(Index);
10922b6b257fSDimitry Andric 
10932b6b257fSDimitry Andric     // The statement may be spanned by an expansion. Make sure we handle a file
10942b6b257fSDimitry Andric     // exit out of this expansion before moving to the next statement.
1095676fbe81SDimitry Andric     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
1096461a67faSDimitry Andric       MostRecentLocation = EndLoc;
10972b6b257fSDimitry Andric 
10985e20cdd8SDimitry Andric     return ExitCount;
109906d4ba38SDimitry Andric   }
110006d4ba38SDimitry Andric 
1101b60736ecSDimitry Andric   /// Determine whether the given condition can be constant folded.
ConditionFoldsToBool__anon015dba650211::CounterCoverageMappingBuilder1102b60736ecSDimitry Andric   bool ConditionFoldsToBool(const Expr *Cond) {
1103b60736ecSDimitry Andric     Expr::EvalResult Result;
1104b60736ecSDimitry Andric     return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
1105b60736ecSDimitry Andric   }
1106b60736ecSDimitry Andric 
1107b60736ecSDimitry Andric   /// Create a Branch Region around an instrumentable condition for coverage
1108b60736ecSDimitry Andric   /// and add it to the function's SourceRegions.  A branch region tracks a
1109b60736ecSDimitry Andric   /// "True" counter and a "False" counter for boolean expressions that
1110b60736ecSDimitry Andric   /// result in the generation of a branch.
createBranchRegion__anon015dba650211::CounterCoverageMappingBuilder1111ac9a064cSDimitry Andric   void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt,
1112ac9a064cSDimitry Andric                           const mcdc::ConditionIDs &Conds = {}) {
1113b60736ecSDimitry Andric     // Check for NULL conditions.
1114b60736ecSDimitry Andric     if (!C)
1115b60736ecSDimitry Andric       return;
1116b60736ecSDimitry Andric 
1117b60736ecSDimitry Andric     // Ensure we are an instrumentable condition (i.e. no "&&" or "||").  Push
1118b60736ecSDimitry Andric     // region onto RegionStack but immediately pop it (which adds it to the
1119b60736ecSDimitry Andric     // function's SourceRegions) because it doesn't apply to any other source
1120b60736ecSDimitry Andric     // code other than the Condition.
1121ac9a064cSDimitry Andric     // With !SystemHeadersCoverage, binary logical ops in system headers may be
1122ac9a064cSDimitry Andric     // treated as instrumentable conditions.
1123ac9a064cSDimitry Andric     if (CodeGenFunction::isInstrumentedCondition(C) ||
1124ac9a064cSDimitry Andric         LeafExprSet.count(CodeGenFunction::stripCond(C))) {
1125ac9a064cSDimitry Andric       mcdc::Parameters BranchParams;
1126ac9a064cSDimitry Andric       mcdc::ConditionID ID = MCDCBuilder.getCondID(C);
1127ac9a064cSDimitry Andric       if (ID >= 0)
1128ac9a064cSDimitry Andric         BranchParams = mcdc::BranchParameters{ID, Conds};
11294df029ccSDimitry Andric 
1130b60736ecSDimitry Andric       // If a condition can fold to true or false, the corresponding branch
1131b60736ecSDimitry Andric       // will be removed.  Create a region with both counters hard-coded to
1132b60736ecSDimitry Andric       // zero. This allows us to visualize them in a special way.
1133b60736ecSDimitry Andric       // Alternatively, we can prevent any optimization done via
1134b60736ecSDimitry Andric       // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
1135b60736ecSDimitry Andric       // CodeGenFunction.c always returns false, but that is very heavy-handed.
1136b60736ecSDimitry Andric       if (ConditionFoldsToBool(C))
1137b60736ecSDimitry Andric         popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
1138ac9a064cSDimitry Andric                               Counter::getZero(), BranchParams));
1139b60736ecSDimitry Andric       else
1140b60736ecSDimitry Andric         // Otherwise, create a region with the True counter and False counter.
1141ac9a064cSDimitry Andric         popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt,
1142ac9a064cSDimitry Andric                               BranchParams));
1143b60736ecSDimitry Andric     }
1144b60736ecSDimitry Andric   }
1145b60736ecSDimitry Andric 
1146aca2e42cSDimitry Andric   /// Create a Decision Region with a BitmapIdx and number of Conditions. This
1147aca2e42cSDimitry Andric   /// type of region "contains" branch regions, one for each of the conditions.
1148aca2e42cSDimitry Andric   /// The visualization tool will group everything together.
createDecisionRegion__anon015dba650211::CounterCoverageMappingBuilder1149ac9a064cSDimitry Andric   void createDecisionRegion(const Expr *C,
1150ac9a064cSDimitry Andric                             const mcdc::DecisionParameters &DecisionParams) {
1151ac9a064cSDimitry Andric     popRegions(pushRegion(DecisionParams, getStart(C), getEnd(C)));
1152aca2e42cSDimitry Andric   }
1153aca2e42cSDimitry Andric 
1154b60736ecSDimitry Andric   /// Create a Branch Region around a SwitchCase for code coverage
1155b60736ecSDimitry Andric   /// and add it to the function's SourceRegions.
createSwitchCaseRegion__anon015dba650211::CounterCoverageMappingBuilder1156b60736ecSDimitry Andric   void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt,
1157b60736ecSDimitry Andric                               Counter FalseCnt) {
1158b60736ecSDimitry Andric     // Push region onto RegionStack but immediately pop it (which adds it to
1159b60736ecSDimitry Andric     // the function's SourceRegions) because it doesn't apply to any other
1160b60736ecSDimitry Andric     // source other than the SwitchCase.
1161b60736ecSDimitry Andric     popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
1162b60736ecSDimitry Andric   }
1163b60736ecSDimitry Andric 
116448675466SDimitry Andric   /// Check whether a region with bounds \c StartLoc and \c EndLoc
11652b6b257fSDimitry Andric   /// is already added to \c SourceRegions.
isRegionAlreadyAdded__anon015dba650211::CounterCoverageMappingBuilder1166b60736ecSDimitry Andric   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
1167b60736ecSDimitry Andric                             bool isBranch = false) {
1168c0981da4SDimitry Andric     return llvm::any_of(
1169c0981da4SDimitry Andric         llvm::reverse(SourceRegions), [&](const SourceMappingRegion &Region) {
1170676fbe81SDimitry Andric           return Region.getBeginLoc() == StartLoc &&
1171c0981da4SDimitry Andric                  Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
11722b6b257fSDimitry Andric         });
11732b6b257fSDimitry Andric   }
11742b6b257fSDimitry Andric 
117548675466SDimitry Andric   /// Adjust the most recently visited location to \c EndLoc.
11765e20cdd8SDimitry Andric   ///
11775e20cdd8SDimitry Andric   /// This should be used after visiting any statements in non-source order.
adjustForOutOfOrderTraversal__anon015dba650211::CounterCoverageMappingBuilder11785e20cdd8SDimitry Andric   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
11795e20cdd8SDimitry Andric     MostRecentLocation = EndLoc;
11802b6b257fSDimitry Andric     // The code region for a whole macro is created in handleFileExit() when
11812b6b257fSDimitry Andric     // it detects exiting of the virtual file of that macro. If we visited
11822b6b257fSDimitry Andric     // statements in non-source order, we might already have such a region
11832b6b257fSDimitry Andric     // added, for example, if a body of a loop is divided among multiple
11842b6b257fSDimitry Andric     // macros. Avoid adding duplicate regions in such case.
11855e20cdd8SDimitry Andric     if (getRegion().hasEndLoc() &&
11862b6b257fSDimitry Andric         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
11872b6b257fSDimitry Andric         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
1188b60736ecSDimitry Andric                              MostRecentLocation, getRegion().isBranch()))
11895e20cdd8SDimitry Andric       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
119006d4ba38SDimitry Andric   }
119106d4ba38SDimitry Andric 
119248675466SDimitry Andric   /// Adjust regions and state when \c NewLoc exits a file.
11935e20cdd8SDimitry Andric   ///
11945e20cdd8SDimitry Andric   /// If moving from our most recently tracked location to \c NewLoc exits any
11955e20cdd8SDimitry Andric   /// files, this adjusts our current region stack and creates the file regions
11965e20cdd8SDimitry Andric   /// for the exited file.
handleFileExit__anon015dba650211::CounterCoverageMappingBuilder11975e20cdd8SDimitry Andric   void handleFileExit(SourceLocation NewLoc) {
1198c192b3dcSDimitry Andric     if (NewLoc.isInvalid() ||
1199c192b3dcSDimitry Andric         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
12005e20cdd8SDimitry Andric       return;
12015e20cdd8SDimitry Andric 
12025e20cdd8SDimitry Andric     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
12035e20cdd8SDimitry Andric     // find the common ancestor.
12045e20cdd8SDimitry Andric     SourceLocation LCA = NewLoc;
12055e20cdd8SDimitry Andric     FileID ParentFile = SM.getFileID(LCA);
12065e20cdd8SDimitry Andric     while (!isNestedIn(MostRecentLocation, ParentFile)) {
12075e20cdd8SDimitry Andric       LCA = getIncludeOrExpansionLoc(LCA);
12085e20cdd8SDimitry Andric       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
12095e20cdd8SDimitry Andric         // Since there isn't a common ancestor, no file was exited. We just need
12105e20cdd8SDimitry Andric         // to adjust our location to the new file.
12115e20cdd8SDimitry Andric         MostRecentLocation = NewLoc;
12125e20cdd8SDimitry Andric         return;
12135e20cdd8SDimitry Andric       }
12145e20cdd8SDimitry Andric       ParentFile = SM.getFileID(LCA);
121506d4ba38SDimitry Andric     }
121606d4ba38SDimitry Andric 
12175e20cdd8SDimitry Andric     llvm::SmallSet<SourceLocation, 8> StartLocs;
1218e3b55780SDimitry Andric     std::optional<Counter> ParentCounter;
121945b53394SDimitry Andric     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
122045b53394SDimitry Andric       if (!I.hasStartLoc())
12215e20cdd8SDimitry Andric         continue;
1222676fbe81SDimitry Andric       SourceLocation Loc = I.getBeginLoc();
12235e20cdd8SDimitry Andric       if (!isNestedIn(Loc, ParentFile)) {
122445b53394SDimitry Andric         ParentCounter = I.getCounter();
12255e20cdd8SDimitry Andric         break;
122606d4ba38SDimitry Andric       }
12275e20cdd8SDimitry Andric 
12285e20cdd8SDimitry Andric       while (!SM.isInFileID(Loc, ParentFile)) {
12295e20cdd8SDimitry Andric         // The most nested region for each start location is the one with the
12305e20cdd8SDimitry Andric         // correct count. We avoid creating redundant regions by stopping once
12315e20cdd8SDimitry Andric         // we've seen this region.
1232b60736ecSDimitry Andric         if (StartLocs.insert(Loc).second) {
1233b60736ecSDimitry Andric           if (I.isBranch())
1234ac9a064cSDimitry Andric             SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(),
1235ac9a064cSDimitry Andric                                        I.getMCDCParams(), Loc,
1236ac9a064cSDimitry Andric                                        getEndOfFileOrMacro(Loc), I.isBranch());
1237b60736ecSDimitry Andric           else
123845b53394SDimitry Andric             SourceRegions.emplace_back(I.getCounter(), Loc,
12395e20cdd8SDimitry Andric                                        getEndOfFileOrMacro(Loc));
1240b60736ecSDimitry Andric         }
12415e20cdd8SDimitry Andric         Loc = getIncludeOrExpansionLoc(Loc);
124206d4ba38SDimitry Andric       }
124345b53394SDimitry Andric       I.setStartLoc(getPreciseTokenLocEnd(Loc));
12445e20cdd8SDimitry Andric     }
12455e20cdd8SDimitry Andric 
12465e20cdd8SDimitry Andric     if (ParentCounter) {
12475e20cdd8SDimitry Andric       // If the file is contained completely by another region and doesn't
12485e20cdd8SDimitry Andric       // immediately start its own region, the whole file gets a region
12495e20cdd8SDimitry Andric       // corresponding to the parent.
12505e20cdd8SDimitry Andric       SourceLocation Loc = MostRecentLocation;
12515e20cdd8SDimitry Andric       while (isNestedIn(Loc, ParentFile)) {
12525e20cdd8SDimitry Andric         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
1253461a67faSDimitry Andric         if (StartLocs.insert(FileStart).second) {
12545e20cdd8SDimitry Andric           SourceRegions.emplace_back(*ParentCounter, FileStart,
12555e20cdd8SDimitry Andric                                      getEndOfFileOrMacro(Loc));
1256461a67faSDimitry Andric           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
1257461a67faSDimitry Andric         }
12585e20cdd8SDimitry Andric         Loc = getIncludeOrExpansionLoc(Loc);
12595e20cdd8SDimitry Andric       }
12605e20cdd8SDimitry Andric     }
12615e20cdd8SDimitry Andric 
12625e20cdd8SDimitry Andric     MostRecentLocation = NewLoc;
12635e20cdd8SDimitry Andric   }
12645e20cdd8SDimitry Andric 
126548675466SDimitry Andric   /// Ensure that \c S is included in the current region.
extendRegion__anon015dba650211::CounterCoverageMappingBuilder12665e20cdd8SDimitry Andric   void extendRegion(const Stmt *S) {
12675e20cdd8SDimitry Andric     SourceMappingRegion &Region = getRegion();
12685e20cdd8SDimitry Andric     SourceLocation StartLoc = getStart(S);
12695e20cdd8SDimitry Andric 
12705e20cdd8SDimitry Andric     handleFileExit(StartLoc);
12715e20cdd8SDimitry Andric     if (!Region.hasStartLoc())
12725e20cdd8SDimitry Andric       Region.setStartLoc(StartLoc);
12735e20cdd8SDimitry Andric   }
12745e20cdd8SDimitry Andric 
127548675466SDimitry Andric   /// Mark \c S as a terminator, starting a zero region.
terminateRegion__anon015dba650211::CounterCoverageMappingBuilder12765e20cdd8SDimitry Andric   void terminateRegion(const Stmt *S) {
12775e20cdd8SDimitry Andric     extendRegion(S);
12785e20cdd8SDimitry Andric     SourceMappingRegion &Region = getRegion();
1279461a67faSDimitry Andric     SourceLocation EndLoc = getEnd(S);
12805e20cdd8SDimitry Andric     if (!Region.hasEndLoc())
1281461a67faSDimitry Andric       Region.setEndLoc(EndLoc);
12825e20cdd8SDimitry Andric     pushRegion(Counter::getZero());
1283344a3780SDimitry Andric     HasTerminateStmt = true;
1284461a67faSDimitry Andric   }
1285461a67faSDimitry Andric 
1286461a67faSDimitry Andric   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
findGapAreaBetween__anon015dba650211::CounterCoverageMappingBuilder1287e3b55780SDimitry Andric   std::optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
1288461a67faSDimitry Andric                                                 SourceLocation BeforeLoc) {
1289ac9a064cSDimitry Andric     // Some statements (like AttributedStmt and ImplicitValueInitExpr) don't
1290ac9a064cSDimitry Andric     // have valid source locations. Do not emit a gap region if this is the case
1291ac9a064cSDimitry Andric     // in either AfterLoc end or BeforeLoc end.
1292ac9a064cSDimitry Andric     if (AfterLoc.isInvalid() || BeforeLoc.isInvalid())
1293ac9a064cSDimitry Andric       return std::nullopt;
1294ac9a064cSDimitry Andric 
1295344a3780SDimitry Andric     // If AfterLoc is in function-like macro, use the right parenthesis
1296344a3780SDimitry Andric     // location.
1297344a3780SDimitry Andric     if (AfterLoc.isMacroID()) {
1298344a3780SDimitry Andric       FileID FID = SM.getFileID(AfterLoc);
1299344a3780SDimitry Andric       const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
1300344a3780SDimitry Andric       if (EI->isFunctionMacroExpansion())
1301344a3780SDimitry Andric         AfterLoc = EI->getExpansionLocEnd();
1302344a3780SDimitry Andric     }
1303344a3780SDimitry Andric 
1304344a3780SDimitry Andric     size_t StartDepth = locationDepth(AfterLoc);
1305344a3780SDimitry Andric     size_t EndDepth = locationDepth(BeforeLoc);
1306344a3780SDimitry Andric     while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
1307344a3780SDimitry Andric       bool UnnestStart = StartDepth >= EndDepth;
1308344a3780SDimitry Andric       bool UnnestEnd = EndDepth >= StartDepth;
1309344a3780SDimitry Andric       if (UnnestEnd) {
1310344a3780SDimitry Andric         assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1311344a3780SDimitry Andric                                       BeforeLoc));
1312344a3780SDimitry Andric 
1313344a3780SDimitry Andric         BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1314344a3780SDimitry Andric         assert(BeforeLoc.isValid());
1315344a3780SDimitry Andric         EndDepth--;
1316344a3780SDimitry Andric       }
1317344a3780SDimitry Andric       if (UnnestStart) {
1318344a3780SDimitry Andric         assert(SM.isWrittenInSameFile(AfterLoc,
1319344a3780SDimitry Andric                                       getEndOfFileOrMacro(AfterLoc)));
1320344a3780SDimitry Andric 
1321344a3780SDimitry Andric         AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
1322344a3780SDimitry Andric         assert(AfterLoc.isValid());
1323344a3780SDimitry Andric         AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1324344a3780SDimitry Andric         assert(AfterLoc.isValid());
1325344a3780SDimitry Andric         StartDepth--;
1326344a3780SDimitry Andric       }
1327344a3780SDimitry Andric     }
1328344a3780SDimitry Andric     AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1329461a67faSDimitry Andric     // If the start and end locations of the gap are both within the same macro
1330461a67faSDimitry Andric     // file, the range may not be in source order.
1331461a67faSDimitry Andric     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
1332e3b55780SDimitry Andric       return std::nullopt;
1333344a3780SDimitry Andric     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
1334344a3780SDimitry Andric         !SpellingRegion(SM, AfterLoc, BeforeLoc).isInSourceOrder())
1335e3b55780SDimitry Andric       return std::nullopt;
1336461a67faSDimitry Andric     return {{AfterLoc, BeforeLoc}};
1337461a67faSDimitry Andric   }
1338461a67faSDimitry Andric 
1339461a67faSDimitry Andric   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
fillGapAreaWithCount__anon015dba650211::CounterCoverageMappingBuilder1340461a67faSDimitry Andric   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
1341461a67faSDimitry Andric                             Counter Count) {
1342461a67faSDimitry Andric     if (StartLoc == EndLoc)
1343461a67faSDimitry Andric       return;
1344461a67faSDimitry Andric     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
1345461a67faSDimitry Andric     handleFileExit(StartLoc);
1346461a67faSDimitry Andric     size_t Index = pushRegion(Count, StartLoc, EndLoc);
1347461a67faSDimitry Andric     getRegion().setGap(true);
1348461a67faSDimitry Andric     handleFileExit(EndLoc);
1349461a67faSDimitry Andric     popRegions(Index);
13505e20cdd8SDimitry Andric   }
135106d4ba38SDimitry Andric 
13524df029ccSDimitry Andric   /// Find a valid range starting with \p StartingLoc and ending before \p
13534df029ccSDimitry Andric   /// BeforeLoc.
findAreaStartingFromTo__anon015dba650211::CounterCoverageMappingBuilder13544df029ccSDimitry Andric   std::optional<SourceRange> findAreaStartingFromTo(SourceLocation StartingLoc,
13554df029ccSDimitry Andric                                                     SourceLocation BeforeLoc) {
13564df029ccSDimitry Andric     // If StartingLoc is in function-like macro, use its start location.
13574df029ccSDimitry Andric     if (StartingLoc.isMacroID()) {
13584df029ccSDimitry Andric       FileID FID = SM.getFileID(StartingLoc);
13594df029ccSDimitry Andric       const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
13604df029ccSDimitry Andric       if (EI->isFunctionMacroExpansion())
13614df029ccSDimitry Andric         StartingLoc = EI->getExpansionLocStart();
13624df029ccSDimitry Andric     }
13634df029ccSDimitry Andric 
13644df029ccSDimitry Andric     size_t StartDepth = locationDepth(StartingLoc);
13654df029ccSDimitry Andric     size_t EndDepth = locationDepth(BeforeLoc);
13664df029ccSDimitry Andric     while (!SM.isWrittenInSameFile(StartingLoc, BeforeLoc)) {
13674df029ccSDimitry Andric       bool UnnestStart = StartDepth >= EndDepth;
13684df029ccSDimitry Andric       bool UnnestEnd = EndDepth >= StartDepth;
13694df029ccSDimitry Andric       if (UnnestEnd) {
13704df029ccSDimitry Andric         assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
13714df029ccSDimitry Andric                                       BeforeLoc));
13724df029ccSDimitry Andric 
13734df029ccSDimitry Andric         BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
13744df029ccSDimitry Andric         assert(BeforeLoc.isValid());
13754df029ccSDimitry Andric         EndDepth--;
13764df029ccSDimitry Andric       }
13774df029ccSDimitry Andric       if (UnnestStart) {
13784df029ccSDimitry Andric         assert(SM.isWrittenInSameFile(StartingLoc,
13794df029ccSDimitry Andric                                       getStartOfFileOrMacro(StartingLoc)));
13804df029ccSDimitry Andric 
13814df029ccSDimitry Andric         StartingLoc = getIncludeOrExpansionLoc(StartingLoc);
13824df029ccSDimitry Andric         assert(StartingLoc.isValid());
13834df029ccSDimitry Andric         StartDepth--;
13844df029ccSDimitry Andric       }
13854df029ccSDimitry Andric     }
13864df029ccSDimitry Andric     // If the start and end locations of the gap are both within the same macro
13874df029ccSDimitry Andric     // file, the range may not be in source order.
13884df029ccSDimitry Andric     if (StartingLoc.isMacroID() || BeforeLoc.isMacroID())
13894df029ccSDimitry Andric       return std::nullopt;
13904df029ccSDimitry Andric     if (!SM.isWrittenInSameFile(StartingLoc, BeforeLoc) ||
13914df029ccSDimitry Andric         !SpellingRegion(SM, StartingLoc, BeforeLoc).isInSourceOrder())
13924df029ccSDimitry Andric       return std::nullopt;
13934df029ccSDimitry Andric     return {{StartingLoc, BeforeLoc}};
13944df029ccSDimitry Andric   }
13954df029ccSDimitry Andric 
markSkipped__anon015dba650211::CounterCoverageMappingBuilder13964df029ccSDimitry Andric   void markSkipped(SourceLocation StartLoc, SourceLocation BeforeLoc) {
13974df029ccSDimitry Andric     const auto Skipped = findAreaStartingFromTo(StartLoc, BeforeLoc);
13984df029ccSDimitry Andric 
13994df029ccSDimitry Andric     if (!Skipped)
14004df029ccSDimitry Andric       return;
14014df029ccSDimitry Andric 
14024df029ccSDimitry Andric     const auto NewStartLoc = Skipped->getBegin();
14034df029ccSDimitry Andric     const auto EndLoc = Skipped->getEnd();
14044df029ccSDimitry Andric 
14054df029ccSDimitry Andric     if (NewStartLoc == EndLoc)
14064df029ccSDimitry Andric       return;
14074df029ccSDimitry Andric     assert(SpellingRegion(SM, NewStartLoc, EndLoc).isInSourceOrder());
14084df029ccSDimitry Andric     handleFileExit(NewStartLoc);
1409ac9a064cSDimitry Andric     size_t Index = pushRegion(Counter{}, NewStartLoc, EndLoc);
14104df029ccSDimitry Andric     getRegion().setSkipped(true);
14114df029ccSDimitry Andric     handleFileExit(EndLoc);
14124df029ccSDimitry Andric     popRegions(Index);
14134df029ccSDimitry Andric   }
14144df029ccSDimitry Andric 
141548675466SDimitry Andric   /// Keep counts of breaks and continues inside loops.
141606d4ba38SDimitry Andric   struct BreakContinue {
141706d4ba38SDimitry Andric     Counter BreakCount;
141806d4ba38SDimitry Andric     Counter ContinueCount;
141906d4ba38SDimitry Andric   };
142006d4ba38SDimitry Andric   SmallVector<BreakContinue, 8> BreakContinueStack;
142106d4ba38SDimitry Andric 
CounterCoverageMappingBuilder__anon015dba650211::CounterCoverageMappingBuilder142206d4ba38SDimitry Andric   CounterCoverageMappingBuilder(
142306d4ba38SDimitry Andric       CoverageMappingModuleGen &CVM,
1424aca2e42cSDimitry Andric       llvm::DenseMap<const Stmt *, unsigned> &CounterMap,
1425ac9a064cSDimitry Andric       MCDC::State &MCDCState, SourceManager &SM, const LangOptions &LangOpts)
1426aca2e42cSDimitry Andric       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
1427ac9a064cSDimitry Andric         MCDCState(MCDCState), MCDCBuilder(CVM.getCodeGenModule(), MCDCState) {}
142806d4ba38SDimitry Andric 
142948675466SDimitry Andric   /// Write the mapping data to the output stream
write__anon015dba650211::CounterCoverageMappingBuilder143006d4ba38SDimitry Andric   void write(llvm::raw_ostream &OS) {
143106d4ba38SDimitry Andric     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
14325e20cdd8SDimitry Andric     gatherFileIDs(VirtualFileMapping);
1433bab175ecSDimitry Andric     SourceRegionFilter Filter = emitExpansionRegions();
1434bab175ecSDimitry Andric     emitSourceRegions(Filter);
143506d4ba38SDimitry Andric     gatherSkippedRegions();
143606d4ba38SDimitry Andric 
1437631f6b77SDimitry Andric     if (MappingRegions.empty())
1438631f6b77SDimitry Andric       return;
1439631f6b77SDimitry Andric 
14405e20cdd8SDimitry Andric     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
14415e20cdd8SDimitry Andric                                  MappingRegions);
144206d4ba38SDimitry Andric     Writer.write(OS);
144306d4ba38SDimitry Andric   }
144406d4ba38SDimitry Andric 
VisitStmt__anon015dba650211::CounterCoverageMappingBuilder144506d4ba38SDimitry Andric   void VisitStmt(const Stmt *S) {
1446676fbe81SDimitry Andric     if (S->getBeginLoc().isValid())
14475e20cdd8SDimitry Andric       extendRegion(S);
1448344a3780SDimitry Andric     const Stmt *LastStmt = nullptr;
1449344a3780SDimitry Andric     bool SaveTerminateStmt = HasTerminateStmt;
1450344a3780SDimitry Andric     HasTerminateStmt = false;
1451344a3780SDimitry Andric     GapRegionCounter = Counter::getZero();
1452c192b3dcSDimitry Andric     for (const Stmt *Child : S->children())
1453344a3780SDimitry Andric       if (Child) {
1454344a3780SDimitry Andric         // If last statement contains terminate statements, add a gap area
1455ac9a064cSDimitry Andric         // between the two statements.
1456ac9a064cSDimitry Andric         if (LastStmt && HasTerminateStmt) {
1457344a3780SDimitry Andric           auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
1458344a3780SDimitry Andric           if (Gap)
1459344a3780SDimitry Andric             fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
1460344a3780SDimitry Andric                                  GapRegionCounter);
1461344a3780SDimitry Andric           SaveTerminateStmt = true;
1462344a3780SDimitry Andric           HasTerminateStmt = false;
1463344a3780SDimitry Andric         }
1464c192b3dcSDimitry Andric         this->Visit(Child);
1465344a3780SDimitry Andric         LastStmt = Child;
1466344a3780SDimitry Andric       }
1467344a3780SDimitry Andric     if (SaveTerminateStmt)
1468344a3780SDimitry Andric       HasTerminateStmt = true;
14695e20cdd8SDimitry Andric     handleFileExit(getEnd(S));
147006d4ba38SDimitry Andric   }
147106d4ba38SDimitry Andric 
VisitDecl__anon015dba650211::CounterCoverageMappingBuilder147206d4ba38SDimitry Andric   void VisitDecl(const Decl *D) {
14735e20cdd8SDimitry Andric     Stmt *Body = D->getBody();
1474631f6b77SDimitry Andric 
14757fa27ce4SDimitry Andric     // Do not propagate region counts into system headers unless collecting
14767fa27ce4SDimitry Andric     // coverage from system headers is explicitly enabled.
14777fa27ce4SDimitry Andric     if (!SystemHeadersCoverage && Body &&
14787fa27ce4SDimitry Andric         SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
1479631f6b77SDimitry Andric       return;
1480631f6b77SDimitry Andric 
1481676fbe81SDimitry Andric     // Do not visit the artificial children nodes of defaulted methods. The
1482676fbe81SDimitry Andric     // lexer may not be able to report back precise token end locations for
1483676fbe81SDimitry Andric     // these children nodes (llvm.org/PR39822), and moreover users will not be
1484676fbe81SDimitry Andric     // able to see coverage for them.
1485b1c73532SDimitry Andric     Counter BodyCounter = getRegionCounter(Body);
1486676fbe81SDimitry Andric     bool Defaulted = false;
1487676fbe81SDimitry Andric     if (auto *Method = dyn_cast<CXXMethodDecl>(D))
1488676fbe81SDimitry Andric       Defaulted = Method->isDefaulted();
1489b1c73532SDimitry Andric     if (auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1490b1c73532SDimitry Andric       for (auto *Initializer : Ctor->inits()) {
1491b1c73532SDimitry Andric         if (Initializer->isWritten()) {
1492b1c73532SDimitry Andric           auto *Init = Initializer->getInit();
1493b1c73532SDimitry Andric           if (getStart(Init).isValid() && getEnd(Init).isValid())
1494b1c73532SDimitry Andric             propagateCounts(BodyCounter, Init);
1495b1c73532SDimitry Andric         }
1496b1c73532SDimitry Andric       }
1497b1c73532SDimitry Andric     }
1498676fbe81SDimitry Andric 
1499b1c73532SDimitry Andric     propagateCounts(BodyCounter, Body,
1500676fbe81SDimitry Andric                     /*VisitChildren=*/!Defaulted);
1501461a67faSDimitry Andric     assert(RegionStack.empty() && "Regions entered but never exited");
150206d4ba38SDimitry Andric   }
150306d4ba38SDimitry Andric 
VisitReturnStmt__anon015dba650211::CounterCoverageMappingBuilder150406d4ba38SDimitry Andric   void VisitReturnStmt(const ReturnStmt *S) {
15055e20cdd8SDimitry Andric     extendRegion(S);
150606d4ba38SDimitry Andric     if (S->getRetValue())
150706d4ba38SDimitry Andric       Visit(S->getRetValue());
15085e20cdd8SDimitry Andric     terminateRegion(S);
150906d4ba38SDimitry Andric   }
151006d4ba38SDimitry Andric 
VisitCoroutineBodyStmt__anon015dba650211::CounterCoverageMappingBuilder1511cfca06d7SDimitry Andric   void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
1512cfca06d7SDimitry Andric     extendRegion(S);
1513cfca06d7SDimitry Andric     Visit(S->getBody());
1514cfca06d7SDimitry Andric   }
1515cfca06d7SDimitry Andric 
VisitCoreturnStmt__anon015dba650211::CounterCoverageMappingBuilder1516cfca06d7SDimitry Andric   void VisitCoreturnStmt(const CoreturnStmt *S) {
1517cfca06d7SDimitry Andric     extendRegion(S);
1518cfca06d7SDimitry Andric     if (S->getOperand())
1519cfca06d7SDimitry Andric       Visit(S->getOperand());
1520cfca06d7SDimitry Andric     terminateRegion(S);
1521cfca06d7SDimitry Andric   }
1522cfca06d7SDimitry Andric 
VisitCoroutineSuspendExpr__anon015dba650211::CounterCoverageMappingBuilder1523ac9a064cSDimitry Andric   void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *E) {
1524ac9a064cSDimitry Andric     Visit(E->getOperand());
1525ac9a064cSDimitry Andric   }
1526ac9a064cSDimitry Andric 
VisitCXXThrowExpr__anon015dba650211::CounterCoverageMappingBuilder15275e20cdd8SDimitry Andric   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
15285e20cdd8SDimitry Andric     extendRegion(E);
15295e20cdd8SDimitry Andric     if (E->getSubExpr())
15305e20cdd8SDimitry Andric       Visit(E->getSubExpr());
15315e20cdd8SDimitry Andric     terminateRegion(E);
153206d4ba38SDimitry Andric   }
153306d4ba38SDimitry Andric 
VisitGotoStmt__anon015dba650211::CounterCoverageMappingBuilder15345e20cdd8SDimitry Andric   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
15355e20cdd8SDimitry Andric 
VisitLabelStmt__anon015dba650211::CounterCoverageMappingBuilder153606d4ba38SDimitry Andric   void VisitLabelStmt(const LabelStmt *S) {
1537461a67faSDimitry Andric     Counter LabelCount = getRegionCounter(S);
15385e20cdd8SDimitry Andric     SourceLocation Start = getStart(S);
15395e20cdd8SDimitry Andric     // We can't extendRegion here or we risk overlapping with our new region.
15405e20cdd8SDimitry Andric     handleFileExit(Start);
1541461a67faSDimitry Andric     pushRegion(LabelCount, Start);
154206d4ba38SDimitry Andric     Visit(S->getSubStmt());
154306d4ba38SDimitry Andric   }
154406d4ba38SDimitry Andric 
VisitBreakStmt__anon015dba650211::CounterCoverageMappingBuilder154506d4ba38SDimitry Andric   void VisitBreakStmt(const BreakStmt *S) {
154606d4ba38SDimitry Andric     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1547ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
154806d4ba38SDimitry Andric       BreakContinueStack.back().BreakCount = addCounters(
15495e20cdd8SDimitry Andric           BreakContinueStack.back().BreakCount, getRegion().getCounter());
1550461a67faSDimitry Andric     // FIXME: a break in a switch should terminate regions for all preceding
1551461a67faSDimitry Andric     // case statements, not just the most recent one.
15525e20cdd8SDimitry Andric     terminateRegion(S);
155306d4ba38SDimitry Andric   }
155406d4ba38SDimitry Andric 
VisitContinueStmt__anon015dba650211::CounterCoverageMappingBuilder155506d4ba38SDimitry Andric   void VisitContinueStmt(const ContinueStmt *S) {
155606d4ba38SDimitry Andric     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1557ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
155806d4ba38SDimitry Andric       BreakContinueStack.back().ContinueCount = addCounters(
15595e20cdd8SDimitry Andric           BreakContinueStack.back().ContinueCount, getRegion().getCounter());
15605e20cdd8SDimitry Andric     terminateRegion(S);
156106d4ba38SDimitry Andric   }
156206d4ba38SDimitry Andric 
VisitCallExpr__anon015dba650211::CounterCoverageMappingBuilder1563461a67faSDimitry Andric   void VisitCallExpr(const CallExpr *E) {
1564461a67faSDimitry Andric     VisitStmt(E);
1565461a67faSDimitry Andric 
1566461a67faSDimitry Andric     // Terminate the region when we hit a noreturn function.
1567461a67faSDimitry Andric     // (This is helpful dealing with switch statements.)
1568461a67faSDimitry Andric     QualType CalleeType = E->getCallee()->getType();
1569461a67faSDimitry Andric     if (getFunctionExtInfo(*CalleeType).getNoReturn())
1570461a67faSDimitry Andric       terminateRegion(E);
1571461a67faSDimitry Andric   }
1572461a67faSDimitry Andric 
VisitWhileStmt__anon015dba650211::CounterCoverageMappingBuilder157306d4ba38SDimitry Andric   void VisitWhileStmt(const WhileStmt *S) {
15745e20cdd8SDimitry Andric     extendRegion(S);
157506d4ba38SDimitry Andric 
15765e20cdd8SDimitry Andric     Counter ParentCount = getRegion().getCounter();
1577ac9a064cSDimitry Andric     Counter BodyCount = llvm::EnableSingleByteCoverage
1578ac9a064cSDimitry Andric                             ? getRegionCounter(S->getBody())
1579ac9a064cSDimitry Andric                             : getRegionCounter(S);
15805e20cdd8SDimitry Andric 
15815e20cdd8SDimitry Andric     // Handle the body first so that we can get the backedge count.
15825e20cdd8SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
15835e20cdd8SDimitry Andric     extendRegion(S->getBody());
15845e20cdd8SDimitry Andric     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
158506d4ba38SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
15865e20cdd8SDimitry Andric 
1587344a3780SDimitry Andric     bool BodyHasTerminateStmt = HasTerminateStmt;
1588344a3780SDimitry Andric     HasTerminateStmt = false;
1589344a3780SDimitry Andric 
15905e20cdd8SDimitry Andric     // Go back to handle the condition.
15915e20cdd8SDimitry Andric     Counter CondCount =
1592ac9a064cSDimitry Andric         llvm::EnableSingleByteCoverage
1593ac9a064cSDimitry Andric             ? getRegionCounter(S->getCond())
1594ac9a064cSDimitry Andric             : addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
15955e20cdd8SDimitry Andric     propagateCounts(CondCount, S->getCond());
15965e20cdd8SDimitry Andric     adjustForOutOfOrderTraversal(getEnd(S));
15975e20cdd8SDimitry Andric 
1598461a67faSDimitry Andric     // The body count applies to the area immediately after the increment.
1599344a3780SDimitry Andric     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1600461a67faSDimitry Andric     if (Gap)
1601461a67faSDimitry Andric       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1602461a67faSDimitry Andric 
16035e20cdd8SDimitry Andric     Counter OutCount =
1604ac9a064cSDimitry Andric         llvm::EnableSingleByteCoverage
1605ac9a064cSDimitry Andric             ? getRegionCounter(S)
1606ac9a064cSDimitry Andric             : addCounters(BC.BreakCount,
1607ac9a064cSDimitry Andric                           subtractCounters(CondCount, BodyCount));
1608ac9a064cSDimitry Andric 
1609344a3780SDimitry Andric     if (OutCount != ParentCount) {
16105e20cdd8SDimitry Andric       pushRegion(OutCount);
1611344a3780SDimitry Andric       GapRegionCounter = OutCount;
1612344a3780SDimitry Andric       if (BodyHasTerminateStmt)
1613344a3780SDimitry Andric         HasTerminateStmt = true;
1614344a3780SDimitry Andric     }
1615b60736ecSDimitry Andric 
1616b60736ecSDimitry Andric     // Create Branch Region around condition.
1617ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
1618b60736ecSDimitry Andric       createBranchRegion(S->getCond(), BodyCount,
1619b60736ecSDimitry Andric                          subtractCounters(CondCount, BodyCount));
162006d4ba38SDimitry Andric   }
162106d4ba38SDimitry Andric 
VisitDoStmt__anon015dba650211::CounterCoverageMappingBuilder162206d4ba38SDimitry Andric   void VisitDoStmt(const DoStmt *S) {
16235e20cdd8SDimitry Andric     extendRegion(S);
162406d4ba38SDimitry Andric 
16255e20cdd8SDimitry Andric     Counter ParentCount = getRegion().getCounter();
1626ac9a064cSDimitry Andric     Counter BodyCount = llvm::EnableSingleByteCoverage
1627ac9a064cSDimitry Andric                             ? getRegionCounter(S->getBody())
1628ac9a064cSDimitry Andric                             : getRegionCounter(S);
16295e20cdd8SDimitry Andric 
16305e20cdd8SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
16315e20cdd8SDimitry Andric     extendRegion(S->getBody());
1632ac9a064cSDimitry Andric 
1633ac9a064cSDimitry Andric     Counter BackedgeCount;
1634ac9a064cSDimitry Andric     if (llvm::EnableSingleByteCoverage)
1635ac9a064cSDimitry Andric       propagateCounts(BodyCount, S->getBody());
1636ac9a064cSDimitry Andric     else
1637ac9a064cSDimitry Andric       BackedgeCount =
16385e20cdd8SDimitry Andric           propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1639ac9a064cSDimitry Andric 
164006d4ba38SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
16415e20cdd8SDimitry Andric 
1642344a3780SDimitry Andric     bool BodyHasTerminateStmt = HasTerminateStmt;
1643344a3780SDimitry Andric     HasTerminateStmt = false;
1644344a3780SDimitry Andric 
1645ac9a064cSDimitry Andric     Counter CondCount = llvm::EnableSingleByteCoverage
1646ac9a064cSDimitry Andric                             ? getRegionCounter(S->getCond())
1647ac9a064cSDimitry Andric                             : addCounters(BackedgeCount, BC.ContinueCount);
16485e20cdd8SDimitry Andric     propagateCounts(CondCount, S->getCond());
16495e20cdd8SDimitry Andric 
16505e20cdd8SDimitry Andric     Counter OutCount =
1651ac9a064cSDimitry Andric         llvm::EnableSingleByteCoverage
1652ac9a064cSDimitry Andric             ? getRegionCounter(S)
1653ac9a064cSDimitry Andric             : addCounters(BC.BreakCount,
1654ac9a064cSDimitry Andric                           subtractCounters(CondCount, BodyCount));
1655344a3780SDimitry Andric     if (OutCount != ParentCount) {
16565e20cdd8SDimitry Andric       pushRegion(OutCount);
1657344a3780SDimitry Andric       GapRegionCounter = OutCount;
1658344a3780SDimitry Andric     }
1659b60736ecSDimitry Andric 
1660b60736ecSDimitry Andric     // Create Branch Region around condition.
1661ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
1662b60736ecSDimitry Andric       createBranchRegion(S->getCond(), BodyCount,
1663b60736ecSDimitry Andric                          subtractCounters(CondCount, BodyCount));
1664344a3780SDimitry Andric 
1665344a3780SDimitry Andric     if (BodyHasTerminateStmt)
1666344a3780SDimitry Andric       HasTerminateStmt = true;
166706d4ba38SDimitry Andric   }
166806d4ba38SDimitry Andric 
VisitForStmt__anon015dba650211::CounterCoverageMappingBuilder166906d4ba38SDimitry Andric   void VisitForStmt(const ForStmt *S) {
16705e20cdd8SDimitry Andric     extendRegion(S);
167106d4ba38SDimitry Andric     if (S->getInit())
167206d4ba38SDimitry Andric       Visit(S->getInit());
167306d4ba38SDimitry Andric 
16745e20cdd8SDimitry Andric     Counter ParentCount = getRegion().getCounter();
1675ac9a064cSDimitry Andric     Counter BodyCount = llvm::EnableSingleByteCoverage
1676ac9a064cSDimitry Andric                             ? getRegionCounter(S->getBody())
1677ac9a064cSDimitry Andric                             : getRegionCounter(S);
16785e20cdd8SDimitry Andric 
167948675466SDimitry Andric     // The loop increment may contain a break or continue.
168048675466SDimitry Andric     if (S->getInc())
168148675466SDimitry Andric       BreakContinueStack.emplace_back();
168248675466SDimitry Andric 
16835e20cdd8SDimitry Andric     // Handle the body first so that we can get the backedge count.
168448675466SDimitry Andric     BreakContinueStack.emplace_back();
16855e20cdd8SDimitry Andric     extendRegion(S->getBody());
16865e20cdd8SDimitry Andric     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
168748675466SDimitry Andric     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
168806d4ba38SDimitry Andric 
1689344a3780SDimitry Andric     bool BodyHasTerminateStmt = HasTerminateStmt;
1690344a3780SDimitry Andric     HasTerminateStmt = false;
1691344a3780SDimitry Andric 
169206d4ba38SDimitry Andric     // The increment is essentially part of the body but it needs to include
169306d4ba38SDimitry Andric     // the count for all the continue statements.
169448675466SDimitry Andric     BreakContinue IncrementBC;
169548675466SDimitry Andric     if (const Stmt *Inc = S->getInc()) {
1696ac9a064cSDimitry Andric       Counter IncCount;
1697ac9a064cSDimitry Andric       if (llvm::EnableSingleByteCoverage)
1698ac9a064cSDimitry Andric         IncCount = getRegionCounter(S->getInc());
1699ac9a064cSDimitry Andric       else
1700ac9a064cSDimitry Andric         IncCount = addCounters(BackedgeCount, BodyBC.ContinueCount);
1701ac9a064cSDimitry Andric       propagateCounts(IncCount, Inc);
170248675466SDimitry Andric       IncrementBC = BreakContinueStack.pop_back_val();
170348675466SDimitry Andric     }
17045e20cdd8SDimitry Andric 
17055e20cdd8SDimitry Andric     // Go back to handle the condition.
1706ac9a064cSDimitry Andric     Counter CondCount =
1707ac9a064cSDimitry Andric         llvm::EnableSingleByteCoverage
1708ac9a064cSDimitry Andric             ? getRegionCounter(S->getCond())
1709ac9a064cSDimitry Andric             : addCounters(
171048675466SDimitry Andric                   addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
171148675466SDimitry Andric                   IncrementBC.ContinueCount);
1712ac9a064cSDimitry Andric 
17135e20cdd8SDimitry Andric     if (const Expr *Cond = S->getCond()) {
17145e20cdd8SDimitry Andric       propagateCounts(CondCount, Cond);
17155e20cdd8SDimitry Andric       adjustForOutOfOrderTraversal(getEnd(S));
171606d4ba38SDimitry Andric     }
171706d4ba38SDimitry Andric 
1718461a67faSDimitry Andric     // The body count applies to the area immediately after the increment.
1719344a3780SDimitry Andric     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1720461a67faSDimitry Andric     if (Gap)
1721461a67faSDimitry Andric       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1722461a67faSDimitry Andric 
1723ac9a064cSDimitry Andric     Counter OutCount =
1724ac9a064cSDimitry Andric         llvm::EnableSingleByteCoverage
1725ac9a064cSDimitry Andric             ? getRegionCounter(S)
1726ac9a064cSDimitry Andric             : addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
172748675466SDimitry Andric                           subtractCounters(CondCount, BodyCount));
1728344a3780SDimitry Andric     if (OutCount != ParentCount) {
17295e20cdd8SDimitry Andric       pushRegion(OutCount);
1730344a3780SDimitry Andric       GapRegionCounter = OutCount;
1731344a3780SDimitry Andric       if (BodyHasTerminateStmt)
1732344a3780SDimitry Andric         HasTerminateStmt = true;
1733344a3780SDimitry Andric     }
1734b60736ecSDimitry Andric 
1735b60736ecSDimitry Andric     // Create Branch Region around condition.
1736ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
1737b60736ecSDimitry Andric       createBranchRegion(S->getCond(), BodyCount,
1738b60736ecSDimitry Andric                          subtractCounters(CondCount, BodyCount));
173906d4ba38SDimitry Andric   }
174006d4ba38SDimitry Andric 
VisitCXXForRangeStmt__anon015dba650211::CounterCoverageMappingBuilder174106d4ba38SDimitry Andric   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
17425e20cdd8SDimitry Andric     extendRegion(S);
1743676fbe81SDimitry Andric     if (S->getInit())
1744676fbe81SDimitry Andric       Visit(S->getInit());
17455e20cdd8SDimitry Andric     Visit(S->getLoopVarStmt());
174606d4ba38SDimitry Andric     Visit(S->getRangeStmt());
17475e20cdd8SDimitry Andric 
17485e20cdd8SDimitry Andric     Counter ParentCount = getRegion().getCounter();
1749ac9a064cSDimitry Andric     Counter BodyCount = llvm::EnableSingleByteCoverage
1750ac9a064cSDimitry Andric                             ? getRegionCounter(S->getBody())
1751ac9a064cSDimitry Andric                             : getRegionCounter(S);
17525e20cdd8SDimitry Andric 
175306d4ba38SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
17545e20cdd8SDimitry Andric     extendRegion(S->getBody());
17555e20cdd8SDimitry Andric     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
175606d4ba38SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
17575e20cdd8SDimitry Andric 
1758344a3780SDimitry Andric     bool BodyHasTerminateStmt = HasTerminateStmt;
1759344a3780SDimitry Andric     HasTerminateStmt = false;
1760344a3780SDimitry Andric 
1761461a67faSDimitry Andric     // The body count applies to the area immediately after the range.
1762344a3780SDimitry Andric     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1763461a67faSDimitry Andric     if (Gap)
1764461a67faSDimitry Andric       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1765461a67faSDimitry Andric 
1766ac9a064cSDimitry Andric     Counter OutCount;
1767ac9a064cSDimitry Andric     Counter LoopCount;
1768ac9a064cSDimitry Andric     if (llvm::EnableSingleByteCoverage)
1769ac9a064cSDimitry Andric       OutCount = getRegionCounter(S);
1770ac9a064cSDimitry Andric     else {
1771ac9a064cSDimitry Andric       LoopCount = addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1772ac9a064cSDimitry Andric       OutCount =
17735e20cdd8SDimitry Andric           addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1774ac9a064cSDimitry Andric     }
1775344a3780SDimitry Andric     if (OutCount != ParentCount) {
17765e20cdd8SDimitry Andric       pushRegion(OutCount);
1777344a3780SDimitry Andric       GapRegionCounter = OutCount;
1778344a3780SDimitry Andric       if (BodyHasTerminateStmt)
1779344a3780SDimitry Andric         HasTerminateStmt = true;
1780344a3780SDimitry Andric     }
1781b60736ecSDimitry Andric 
1782b60736ecSDimitry Andric     // Create Branch Region around condition.
1783ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
1784b60736ecSDimitry Andric       createBranchRegion(S->getCond(), BodyCount,
1785b60736ecSDimitry Andric                          subtractCounters(LoopCount, BodyCount));
178606d4ba38SDimitry Andric   }
178706d4ba38SDimitry Andric 
VisitObjCForCollectionStmt__anon015dba650211::CounterCoverageMappingBuilder178806d4ba38SDimitry Andric   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
17895e20cdd8SDimitry Andric     extendRegion(S);
179006d4ba38SDimitry Andric     Visit(S->getElement());
17915e20cdd8SDimitry Andric 
17925e20cdd8SDimitry Andric     Counter ParentCount = getRegion().getCounter();
17935e20cdd8SDimitry Andric     Counter BodyCount = getRegionCounter(S);
17945e20cdd8SDimitry Andric 
179506d4ba38SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
17965e20cdd8SDimitry Andric     extendRegion(S->getBody());
17975e20cdd8SDimitry Andric     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
179806d4ba38SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
17995e20cdd8SDimitry Andric 
1800461a67faSDimitry Andric     // The body count applies to the area immediately after the collection.
1801344a3780SDimitry Andric     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1802461a67faSDimitry Andric     if (Gap)
1803461a67faSDimitry Andric       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1804461a67faSDimitry Andric 
18055e20cdd8SDimitry Andric     Counter LoopCount =
18065e20cdd8SDimitry Andric         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
18075e20cdd8SDimitry Andric     Counter OutCount =
18085e20cdd8SDimitry Andric         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1809344a3780SDimitry Andric     if (OutCount != ParentCount) {
18105e20cdd8SDimitry Andric       pushRegion(OutCount);
1811344a3780SDimitry Andric       GapRegionCounter = OutCount;
1812344a3780SDimitry Andric     }
181306d4ba38SDimitry Andric   }
181406d4ba38SDimitry Andric 
VisitSwitchStmt__anon015dba650211::CounterCoverageMappingBuilder181506d4ba38SDimitry Andric   void VisitSwitchStmt(const SwitchStmt *S) {
18165e20cdd8SDimitry Andric     extendRegion(S);
1817bab175ecSDimitry Andric     if (S->getInit())
1818bab175ecSDimitry Andric       Visit(S->getInit());
181906d4ba38SDimitry Andric     Visit(S->getCond());
18205e20cdd8SDimitry Andric 
182106d4ba38SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
18225e20cdd8SDimitry Andric 
18235e20cdd8SDimitry Andric     const Stmt *Body = S->getBody();
18245e20cdd8SDimitry Andric     extendRegion(Body);
18255e20cdd8SDimitry Andric     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
18265e20cdd8SDimitry Andric       if (!CS->body_empty()) {
1827461a67faSDimitry Andric         // Make a region for the body of the switch.  If the body starts with
1828461a67faSDimitry Andric         // a case, that case will reuse this region; otherwise, this covers
1829461a67faSDimitry Andric         // the unreachable code at the beginning of the switch body.
1830706b4fc4SDimitry Andric         size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1831706b4fc4SDimitry Andric         getRegion().setGap(true);
1832344a3780SDimitry Andric         Visit(Body);
1833461a67faSDimitry Andric 
1834461a67faSDimitry Andric         // Set the end for the body of the switch, if it isn't already set.
1835461a67faSDimitry Andric         for (size_t i = RegionStack.size(); i != Index; --i) {
1836461a67faSDimitry Andric           if (!RegionStack[i - 1].hasEndLoc())
1837461a67faSDimitry Andric             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1838461a67faSDimitry Andric         }
1839461a67faSDimitry Andric 
18405e20cdd8SDimitry Andric         popRegions(Index);
184106d4ba38SDimitry Andric       }
18425e20cdd8SDimitry Andric     } else
18435e20cdd8SDimitry Andric       propagateCounts(Counter::getZero(), Body);
184406d4ba38SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
18455e20cdd8SDimitry Andric 
1846ac9a064cSDimitry Andric     if (!BreakContinueStack.empty() && !llvm::EnableSingleByteCoverage)
184706d4ba38SDimitry Andric       BreakContinueStack.back().ContinueCount = addCounters(
184806d4ba38SDimitry Andric           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
18495e20cdd8SDimitry Andric 
1850b60736ecSDimitry Andric     Counter ParentCount = getRegion().getCounter();
18515e20cdd8SDimitry Andric     Counter ExitCount = getRegionCounter(S);
18522b6b257fSDimitry Andric     SourceLocation ExitLoc = getEnd(S);
1853bab175ecSDimitry Andric     pushRegion(ExitCount);
1854344a3780SDimitry Andric     GapRegionCounter = ExitCount;
1855bab175ecSDimitry Andric 
1856bab175ecSDimitry Andric     // Ensure that handleFileExit recognizes when the end location is located
1857bab175ecSDimitry Andric     // in a different file.
1858bab175ecSDimitry Andric     MostRecentLocation = getStart(S);
18592b6b257fSDimitry Andric     handleFileExit(ExitLoc);
1860b60736ecSDimitry Andric 
1861ac9a064cSDimitry Andric     // When single byte coverage mode is enabled, do not create branch region by
1862ac9a064cSDimitry Andric     // early returning.
1863ac9a064cSDimitry Andric     if (llvm::EnableSingleByteCoverage)
1864ac9a064cSDimitry Andric       return;
1865ac9a064cSDimitry Andric 
1866b60736ecSDimitry Andric     // Create a Branch Region around each Case. Subtract the case's
1867b60736ecSDimitry Andric     // counter from the Parent counter to track the "False" branch count.
1868b60736ecSDimitry Andric     Counter CaseCountSum;
1869b60736ecSDimitry Andric     bool HasDefaultCase = false;
1870b60736ecSDimitry Andric     const SwitchCase *Case = S->getSwitchCaseList();
1871b60736ecSDimitry Andric     for (; Case; Case = Case->getNextSwitchCase()) {
1872b60736ecSDimitry Andric       HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1873145449b1SDimitry Andric       CaseCountSum =
1874145449b1SDimitry Andric           addCounters(CaseCountSum, getRegionCounter(Case), /*Simplify=*/false);
1875b60736ecSDimitry Andric       createSwitchCaseRegion(
1876b60736ecSDimitry Andric           Case, getRegionCounter(Case),
1877b60736ecSDimitry Andric           subtractCounters(ParentCount, getRegionCounter(Case)));
1878b60736ecSDimitry Andric     }
1879145449b1SDimitry Andric     // Simplify is skipped while building the counters above: it can get really
1880145449b1SDimitry Andric     // slow on top of switches with thousands of cases. Instead, trigger
1881145449b1SDimitry Andric     // simplification by adding zero to the last counter.
1882145449b1SDimitry Andric     CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
1883b60736ecSDimitry Andric 
1884b60736ecSDimitry Andric     // If no explicit default case exists, create a branch region to represent
1885b60736ecSDimitry Andric     // the hidden branch, which will be added later by the CodeGen. This region
1886b60736ecSDimitry Andric     // will be associated with the switch statement's condition.
1887b60736ecSDimitry Andric     if (!HasDefaultCase) {
1888b60736ecSDimitry Andric       Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
1889b60736ecSDimitry Andric       Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
1890b60736ecSDimitry Andric       createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
1891b60736ecSDimitry Andric     }
189206d4ba38SDimitry Andric   }
189306d4ba38SDimitry Andric 
VisitSwitchCase__anon015dba650211::CounterCoverageMappingBuilder18945e20cdd8SDimitry Andric   void VisitSwitchCase(const SwitchCase *S) {
18955e20cdd8SDimitry Andric     extendRegion(S);
189606d4ba38SDimitry Andric 
18975e20cdd8SDimitry Andric     SourceMappingRegion &Parent = getRegion();
1898ac9a064cSDimitry Andric     Counter Count = llvm::EnableSingleByteCoverage
1899ac9a064cSDimitry Andric                         ? getRegionCounter(S)
1900ac9a064cSDimitry Andric                         : addCounters(Parent.getCounter(), getRegionCounter(S));
19015e20cdd8SDimitry Andric 
19025e20cdd8SDimitry Andric     // Reuse the existing region if it starts at our label. This is typical of
19035e20cdd8SDimitry Andric     // the first case in a switch.
1904676fbe81SDimitry Andric     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
19055e20cdd8SDimitry Andric       Parent.setCounter(Count);
19065e20cdd8SDimitry Andric     else
19075e20cdd8SDimitry Andric       pushRegion(Count, getStart(S));
19085e20cdd8SDimitry Andric 
1909344a3780SDimitry Andric     GapRegionCounter = Count;
1910344a3780SDimitry Andric 
191145b53394SDimitry Andric     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
19125e20cdd8SDimitry Andric       Visit(CS->getLHS());
19135e20cdd8SDimitry Andric       if (const Expr *RHS = CS->getRHS())
19145e20cdd8SDimitry Andric         Visit(RHS);
19155e20cdd8SDimitry Andric     }
191606d4ba38SDimitry Andric     Visit(S->getSubStmt());
191706d4ba38SDimitry Andric   }
191806d4ba38SDimitry Andric 
coverIfConsteval__anon015dba650211::CounterCoverageMappingBuilder19194df029ccSDimitry Andric   void coverIfConsteval(const IfStmt *S) {
19204df029ccSDimitry Andric     assert(S->isConsteval());
19214df029ccSDimitry Andric 
19224df029ccSDimitry Andric     const auto *Then = S->getThen();
19234df029ccSDimitry Andric     const auto *Else = S->getElse();
19244df029ccSDimitry Andric 
19254df029ccSDimitry Andric     // It's better for llvm-cov to create a new region with same counter
19264df029ccSDimitry Andric     // so line-coverage can be properly calculated for lines containing
19274df029ccSDimitry Andric     // a skipped region (without it the line is marked uncovered)
19284df029ccSDimitry Andric     const Counter ParentCount = getRegion().getCounter();
19294df029ccSDimitry Andric 
19304df029ccSDimitry Andric     extendRegion(S);
19314df029ccSDimitry Andric 
19324df029ccSDimitry Andric     if (S->isNegatedConsteval()) {
19334df029ccSDimitry Andric       // ignore 'if consteval'
19344df029ccSDimitry Andric       markSkipped(S->getIfLoc(), getStart(Then));
19354df029ccSDimitry Andric       propagateCounts(ParentCount, Then);
19364df029ccSDimitry Andric 
19374df029ccSDimitry Andric       if (Else) {
19384df029ccSDimitry Andric         // ignore 'else <else>'
19394df029ccSDimitry Andric         markSkipped(getEnd(Then), getEnd(Else));
19404df029ccSDimitry Andric       }
19414df029ccSDimitry Andric     } else {
19424df029ccSDimitry Andric       assert(S->isNonNegatedConsteval());
19434df029ccSDimitry Andric       // ignore 'if consteval <then> [else]'
19444df029ccSDimitry Andric       markSkipped(S->getIfLoc(), Else ? getStart(Else) : getEnd(Then));
19454df029ccSDimitry Andric 
19464df029ccSDimitry Andric       if (Else)
19474df029ccSDimitry Andric         propagateCounts(ParentCount, Else);
19484df029ccSDimitry Andric     }
19494df029ccSDimitry Andric   }
19504df029ccSDimitry Andric 
coverIfConstexpr__anon015dba650211::CounterCoverageMappingBuilder19514df029ccSDimitry Andric   void coverIfConstexpr(const IfStmt *S) {
19524df029ccSDimitry Andric     assert(S->isConstexpr());
19534df029ccSDimitry Andric 
19544df029ccSDimitry Andric     // evaluate constant condition...
1955ac9a064cSDimitry Andric     const bool isTrue =
1956ac9a064cSDimitry Andric         S->getCond()
1957ac9a064cSDimitry Andric             ->EvaluateKnownConstInt(CVM.getCodeGenModule().getContext())
1958ac9a064cSDimitry Andric             .getBoolValue();
19594df029ccSDimitry Andric 
19604df029ccSDimitry Andric     extendRegion(S);
19614df029ccSDimitry Andric 
19624df029ccSDimitry Andric     // I'm using 'propagateCounts' later as new region is better and allows me
19634df029ccSDimitry Andric     // to properly calculate line coverage in llvm-cov utility
19644df029ccSDimitry Andric     const Counter ParentCount = getRegion().getCounter();
19654df029ccSDimitry Andric 
19664df029ccSDimitry Andric     // ignore 'if constexpr ('
19674df029ccSDimitry Andric     SourceLocation startOfSkipped = S->getIfLoc();
19684df029ccSDimitry Andric 
19694df029ccSDimitry Andric     if (const auto *Init = S->getInit()) {
19704df029ccSDimitry Andric       const auto start = getStart(Init);
19714df029ccSDimitry Andric       const auto end = getEnd(Init);
19724df029ccSDimitry Andric 
19734df029ccSDimitry Andric       // this check is to make sure typedef here which doesn't have valid source
19744df029ccSDimitry Andric       // location won't crash it
19754df029ccSDimitry Andric       if (start.isValid() && end.isValid()) {
19764df029ccSDimitry Andric         markSkipped(startOfSkipped, start);
19774df029ccSDimitry Andric         propagateCounts(ParentCount, Init);
19784df029ccSDimitry Andric         startOfSkipped = getEnd(Init);
19794df029ccSDimitry Andric       }
19804df029ccSDimitry Andric     }
19814df029ccSDimitry Andric 
19824df029ccSDimitry Andric     const auto *Then = S->getThen();
19834df029ccSDimitry Andric     const auto *Else = S->getElse();
19844df029ccSDimitry Andric 
19854df029ccSDimitry Andric     if (isTrue) {
19864df029ccSDimitry Andric       // ignore '<condition>)'
19874df029ccSDimitry Andric       markSkipped(startOfSkipped, getStart(Then));
19884df029ccSDimitry Andric       propagateCounts(ParentCount, Then);
19894df029ccSDimitry Andric 
19904df029ccSDimitry Andric       if (Else)
19914df029ccSDimitry Andric         // ignore 'else <else>'
19924df029ccSDimitry Andric         markSkipped(getEnd(Then), getEnd(Else));
19934df029ccSDimitry Andric     } else {
19944df029ccSDimitry Andric       // ignore '<condition>) <then> [else]'
19954df029ccSDimitry Andric       markSkipped(startOfSkipped, Else ? getStart(Else) : getEnd(Then));
19964df029ccSDimitry Andric 
19974df029ccSDimitry Andric       if (Else)
19984df029ccSDimitry Andric         propagateCounts(ParentCount, Else);
19994df029ccSDimitry Andric     }
20004df029ccSDimitry Andric   }
20014df029ccSDimitry Andric 
VisitIfStmt__anon015dba650211::CounterCoverageMappingBuilder200206d4ba38SDimitry Andric   void VisitIfStmt(const IfStmt *S) {
20034df029ccSDimitry Andric     // "if constexpr" and "if consteval" are not normal conditional statements,
20044df029ccSDimitry Andric     // their discarded statement should be skipped
20054df029ccSDimitry Andric     if (S->isConsteval())
20064df029ccSDimitry Andric       return coverIfConsteval(S);
20074df029ccSDimitry Andric     else if (S->isConstexpr())
20084df029ccSDimitry Andric       return coverIfConstexpr(S);
20094df029ccSDimitry Andric 
20105e20cdd8SDimitry Andric     extendRegion(S);
2011bab175ecSDimitry Andric     if (S->getInit())
2012bab175ecSDimitry Andric       Visit(S->getInit());
2013bab175ecSDimitry Andric 
20142e645aa5SDimitry Andric     // Extend into the condition before we propagate through it below - this is
20152e645aa5SDimitry Andric     // needed to handle macros that generate the "if" but not the condition.
20162e645aa5SDimitry Andric     extendRegion(S->getCond());
201706d4ba38SDimitry Andric 
20185e20cdd8SDimitry Andric     Counter ParentCount = getRegion().getCounter();
2019ac9a064cSDimitry Andric     Counter ThenCount = llvm::EnableSingleByteCoverage
2020ac9a064cSDimitry Andric                             ? getRegionCounter(S->getThen())
2021ac9a064cSDimitry Andric                             : getRegionCounter(S);
2022950076cdSDimitry Andric 
20235e20cdd8SDimitry Andric     // Emitting a counter for the condition makes it easier to interpret the
20245e20cdd8SDimitry Andric     // counter for the body when looking at the coverage.
20255e20cdd8SDimitry Andric     propagateCounts(ParentCount, S->getCond());
20265e20cdd8SDimitry Andric 
2027461a67faSDimitry Andric     // The 'then' count applies to the area immediately after the condition.
2028e3b55780SDimitry Andric     std::optional<SourceRange> Gap =
2029e3b55780SDimitry Andric         findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
2030461a67faSDimitry Andric     if (Gap)
2031461a67faSDimitry Andric       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
2032461a67faSDimitry Andric 
20335e20cdd8SDimitry Andric     extendRegion(S->getThen());
20345e20cdd8SDimitry Andric     Counter OutCount = propagateCounts(ThenCount, S->getThen());
2035ac9a064cSDimitry Andric 
2036ac9a064cSDimitry Andric     Counter ElseCount;
2037ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
2038ac9a064cSDimitry Andric       ElseCount = subtractCounters(ParentCount, ThenCount);
2039ac9a064cSDimitry Andric     else if (S->getElse())
2040ac9a064cSDimitry Andric       ElseCount = getRegionCounter(S->getElse());
2041950076cdSDimitry Andric 
20425e20cdd8SDimitry Andric     if (const Stmt *Else = S->getElse()) {
2043344a3780SDimitry Andric       bool ThenHasTerminateStmt = HasTerminateStmt;
2044344a3780SDimitry Andric       HasTerminateStmt = false;
2045461a67faSDimitry Andric       // The 'else' count applies to the area immediately after the 'then'.
2046e3b55780SDimitry Andric       std::optional<SourceRange> Gap =
2047e3b55780SDimitry Andric           findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
2048461a67faSDimitry Andric       if (Gap)
2049461a67faSDimitry Andric         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
2050461a67faSDimitry Andric       extendRegion(Else);
2051ac9a064cSDimitry Andric 
2052ac9a064cSDimitry Andric       Counter ElseOutCount = propagateCounts(ElseCount, Else);
2053ac9a064cSDimitry Andric       if (!llvm::EnableSingleByteCoverage)
2054ac9a064cSDimitry Andric         OutCount = addCounters(OutCount, ElseOutCount);
2055344a3780SDimitry Andric 
2056344a3780SDimitry Andric       if (ThenHasTerminateStmt)
2057344a3780SDimitry Andric         HasTerminateStmt = true;
2058ac9a064cSDimitry Andric     } else if (!llvm::EnableSingleByteCoverage)
20595e20cdd8SDimitry Andric       OutCount = addCounters(OutCount, ElseCount);
20605e20cdd8SDimitry Andric 
2061ac9a064cSDimitry Andric     if (llvm::EnableSingleByteCoverage)
2062ac9a064cSDimitry Andric       OutCount = getRegionCounter(S);
2063ac9a064cSDimitry Andric 
2064344a3780SDimitry Andric     if (OutCount != ParentCount) {
20655e20cdd8SDimitry Andric       pushRegion(OutCount);
2066344a3780SDimitry Andric       GapRegionCounter = OutCount;
2067344a3780SDimitry Andric     }
2068b60736ecSDimitry Andric 
2069ac9a064cSDimitry Andric     if (!S->isConsteval() && !llvm::EnableSingleByteCoverage)
2070b60736ecSDimitry Andric       // Create Branch Region around condition.
2071b60736ecSDimitry Andric       createBranchRegion(S->getCond(), ThenCount,
2072b60736ecSDimitry Andric                          subtractCounters(ParentCount, ThenCount));
207306d4ba38SDimitry Andric   }
207406d4ba38SDimitry Andric 
VisitCXXTryStmt__anon015dba650211::CounterCoverageMappingBuilder207506d4ba38SDimitry Andric   void VisitCXXTryStmt(const CXXTryStmt *S) {
20765e20cdd8SDimitry Andric     extendRegion(S);
20772b6b257fSDimitry Andric     // Handle macros that generate the "try" but not the rest.
20782b6b257fSDimitry Andric     extendRegion(S->getTryBlock());
20792b6b257fSDimitry Andric 
20802b6b257fSDimitry Andric     Counter ParentCount = getRegion().getCounter();
20812b6b257fSDimitry Andric     propagateCounts(ParentCount, S->getTryBlock());
20822b6b257fSDimitry Andric 
208306d4ba38SDimitry Andric     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
208406d4ba38SDimitry Andric       Visit(S->getHandler(I));
20855e20cdd8SDimitry Andric 
20865e20cdd8SDimitry Andric     Counter ExitCount = getRegionCounter(S);
20875e20cdd8SDimitry Andric     pushRegion(ExitCount);
208806d4ba38SDimitry Andric   }
208906d4ba38SDimitry Andric 
VisitCXXCatchStmt__anon015dba650211::CounterCoverageMappingBuilder209006d4ba38SDimitry Andric   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
20915e20cdd8SDimitry Andric     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
209206d4ba38SDimitry Andric   }
209306d4ba38SDimitry Andric 
VisitAbstractConditionalOperator__anon015dba650211::CounterCoverageMappingBuilder209406d4ba38SDimitry Andric   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
20955e20cdd8SDimitry Andric     extendRegion(E);
20965e20cdd8SDimitry Andric 
20975e20cdd8SDimitry Andric     Counter ParentCount = getRegion().getCounter();
2098ac9a064cSDimitry Andric     Counter TrueCount = llvm::EnableSingleByteCoverage
2099ac9a064cSDimitry Andric                             ? getRegionCounter(E->getTrueExpr())
2100ac9a064cSDimitry Andric                             : getRegionCounter(E);
21017fa27ce4SDimitry Andric     Counter OutCount;
210206d4ba38SDimitry Andric 
2103ac9a064cSDimitry Andric     if (const auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) {
2104ac9a064cSDimitry Andric       propagateCounts(ParentCount, BCO->getCommon());
2105ac9a064cSDimitry Andric       OutCount = TrueCount;
2106ac9a064cSDimitry Andric     } else {
2107ac9a064cSDimitry Andric       propagateCounts(ParentCount, E->getCond());
2108461a67faSDimitry Andric       // The 'then' count applies to the area immediately after the condition.
2109461a67faSDimitry Andric       auto Gap =
2110461a67faSDimitry Andric           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
2111461a67faSDimitry Andric       if (Gap)
2112461a67faSDimitry Andric         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
2113461a67faSDimitry Andric 
21145e20cdd8SDimitry Andric       extendRegion(E->getTrueExpr());
21157fa27ce4SDimitry Andric       OutCount = propagateCounts(TrueCount, E->getTrueExpr());
21165e20cdd8SDimitry Andric     }
2117461a67faSDimitry Andric 
21185e20cdd8SDimitry Andric     extendRegion(E->getFalseExpr());
2119ac9a064cSDimitry Andric     Counter FalseCount = llvm::EnableSingleByteCoverage
2120ac9a064cSDimitry Andric                              ? getRegionCounter(E->getFalseExpr())
2121ac9a064cSDimitry Andric                              : subtractCounters(ParentCount, TrueCount);
2122ac9a064cSDimitry Andric 
2123ac9a064cSDimitry Andric     Counter FalseOutCount = propagateCounts(FalseCount, E->getFalseExpr());
2124ac9a064cSDimitry Andric     if (llvm::EnableSingleByteCoverage)
2125ac9a064cSDimitry Andric       OutCount = getRegionCounter(E);
2126ac9a064cSDimitry Andric     else
2127ac9a064cSDimitry Andric       OutCount = addCounters(OutCount, FalseOutCount);
21287fa27ce4SDimitry Andric 
21297fa27ce4SDimitry Andric     if (OutCount != ParentCount) {
21307fa27ce4SDimitry Andric       pushRegion(OutCount);
21317fa27ce4SDimitry Andric       GapRegionCounter = OutCount;
21327fa27ce4SDimitry Andric     }
2133b60736ecSDimitry Andric 
2134b60736ecSDimitry Andric     // Create Branch Region around condition.
2135ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
2136b60736ecSDimitry Andric       createBranchRegion(E->getCond(), TrueCount,
2137b60736ecSDimitry Andric                          subtractCounters(ParentCount, TrueCount));
213806d4ba38SDimitry Andric   }
213906d4ba38SDimitry Andric 
createOrCancelDecision__anon015dba650211::CounterCoverageMappingBuilder2140ac9a064cSDimitry Andric   void createOrCancelDecision(const BinaryOperator *E, unsigned Since) {
2141ac9a064cSDimitry Andric     unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(E);
2142ac9a064cSDimitry Andric     if (NumConds == 0)
2143ac9a064cSDimitry Andric       return;
2144ac9a064cSDimitry Andric 
2145ac9a064cSDimitry Andric     // Extract [ID, Conds] to construct the graph.
2146ac9a064cSDimitry Andric     llvm::SmallVector<mcdc::ConditionIDs> CondIDs(NumConds);
2147ac9a064cSDimitry Andric     for (const auto &SR : ArrayRef(SourceRegions).slice(Since)) {
2148ac9a064cSDimitry Andric       if (SR.isMCDCBranch()) {
2149ac9a064cSDimitry Andric         auto [ID, Conds] = SR.getMCDCBranchParams();
2150ac9a064cSDimitry Andric         CondIDs[ID] = Conds;
2151ac9a064cSDimitry Andric       }
2152ac9a064cSDimitry Andric     }
2153ac9a064cSDimitry Andric 
2154ac9a064cSDimitry Andric     // Construct the graph and calculate `Indices`.
2155ac9a064cSDimitry Andric     mcdc::TVIdxBuilder Builder(CondIDs);
2156ac9a064cSDimitry Andric     unsigned NumTVs = Builder.NumTestVectors;
2157ac9a064cSDimitry Andric     unsigned MaxTVs = CVM.getCodeGenModule().getCodeGenOpts().MCDCMaxTVs;
2158ac9a064cSDimitry Andric     assert(MaxTVs < mcdc::TVIdxBuilder::HardMaxTVs);
2159ac9a064cSDimitry Andric 
2160ac9a064cSDimitry Andric     if (NumTVs > MaxTVs) {
2161ac9a064cSDimitry Andric       // NumTVs exceeds MaxTVs -- warn and cancel the Decision.
2162ac9a064cSDimitry Andric       cancelDecision(E, Since, NumTVs, MaxTVs);
2163ac9a064cSDimitry Andric       return;
2164ac9a064cSDimitry Andric     }
2165ac9a064cSDimitry Andric 
2166ac9a064cSDimitry Andric     // Update the state for CodeGenPGO
2167ac9a064cSDimitry Andric     assert(MCDCState.DecisionByStmt.contains(E));
2168ac9a064cSDimitry Andric     MCDCState.DecisionByStmt[E] = {
2169ac9a064cSDimitry Andric         MCDCState.BitmapBits, // Top
2170ac9a064cSDimitry Andric         std::move(Builder.Indices),
2171ac9a064cSDimitry Andric     };
2172ac9a064cSDimitry Andric 
2173ac9a064cSDimitry Andric     auto DecisionParams = mcdc::DecisionParameters{
2174ac9a064cSDimitry Andric         MCDCState.BitmapBits += NumTVs, // Tail
2175ac9a064cSDimitry Andric         NumConds,
2176ac9a064cSDimitry Andric     };
2177ac9a064cSDimitry Andric 
2178ac9a064cSDimitry Andric     // Create MCDC Decision Region.
2179ac9a064cSDimitry Andric     createDecisionRegion(E, DecisionParams);
2180ac9a064cSDimitry Andric   }
2181ac9a064cSDimitry Andric 
2182ac9a064cSDimitry Andric   // Warn and cancel the Decision.
cancelDecision__anon015dba650211::CounterCoverageMappingBuilder2183ac9a064cSDimitry Andric   void cancelDecision(const BinaryOperator *E, unsigned Since, int NumTVs,
2184ac9a064cSDimitry Andric                       int MaxTVs) {
2185ac9a064cSDimitry Andric     auto &Diag = CVM.getCodeGenModule().getDiags();
2186ac9a064cSDimitry Andric     unsigned DiagID =
2187ac9a064cSDimitry Andric         Diag.getCustomDiagID(DiagnosticsEngine::Warning,
2188ac9a064cSDimitry Andric                              "unsupported MC/DC boolean expression; "
2189ac9a064cSDimitry Andric                              "number of test vectors (%0) exceeds max (%1). "
2190ac9a064cSDimitry Andric                              "Expression will not be covered");
2191ac9a064cSDimitry Andric     Diag.Report(E->getBeginLoc(), DiagID) << NumTVs << MaxTVs;
2192ac9a064cSDimitry Andric 
2193ac9a064cSDimitry Andric     // Restore MCDCBranch to Branch.
2194ac9a064cSDimitry Andric     for (auto &SR : MutableArrayRef(SourceRegions).slice(Since)) {
2195ac9a064cSDimitry Andric       assert(!SR.isMCDCDecision() && "Decision shouldn't be seen here");
2196ac9a064cSDimitry Andric       if (SR.isMCDCBranch())
2197ac9a064cSDimitry Andric         SR.resetMCDCParams();
2198ac9a064cSDimitry Andric     }
2199ac9a064cSDimitry Andric 
2200ac9a064cSDimitry Andric     // Tell CodeGenPGO not to instrument.
2201ac9a064cSDimitry Andric     MCDCState.DecisionByStmt.erase(E);
2202ac9a064cSDimitry Andric   }
2203ac9a064cSDimitry Andric 
2204ac9a064cSDimitry Andric   /// Check if E belongs to system headers.
isExprInSystemHeader__anon015dba650211::CounterCoverageMappingBuilder2205ac9a064cSDimitry Andric   bool isExprInSystemHeader(const BinaryOperator *E) const {
2206ac9a064cSDimitry Andric     return (!SystemHeadersCoverage &&
2207ac9a064cSDimitry Andric             SM.isInSystemHeader(SM.getSpellingLoc(E->getOperatorLoc())) &&
2208ac9a064cSDimitry Andric             SM.isInSystemHeader(SM.getSpellingLoc(E->getBeginLoc())) &&
2209ac9a064cSDimitry Andric             SM.isInSystemHeader(SM.getSpellingLoc(E->getEndLoc())));
2210ac9a064cSDimitry Andric   }
2211ac9a064cSDimitry Andric 
VisitBinLAnd__anon015dba650211::CounterCoverageMappingBuilder221206d4ba38SDimitry Andric   void VisitBinLAnd(const BinaryOperator *E) {
2213ac9a064cSDimitry Andric     if (isExprInSystemHeader(E)) {
2214ac9a064cSDimitry Andric       LeafExprSet.insert(E);
2215ac9a064cSDimitry Andric       return;
2216ac9a064cSDimitry Andric     }
2217ac9a064cSDimitry Andric 
22184df029ccSDimitry Andric     bool IsRootNode = MCDCBuilder.isIdle();
22194df029ccSDimitry Andric 
2220ac9a064cSDimitry Andric     unsigned SourceRegionsSince = SourceRegions.size();
2221ac9a064cSDimitry Andric 
22224df029ccSDimitry Andric     // Keep track of Binary Operator and assign MCDC condition IDs.
2223aca2e42cSDimitry Andric     MCDCBuilder.pushAndAssignIDs(E);
2224aca2e42cSDimitry Andric 
2225461a67faSDimitry Andric     extendRegion(E->getLHS());
2226461a67faSDimitry Andric     propagateCounts(getRegion().getCounter(), E->getLHS());
2227461a67faSDimitry Andric     handleFileExit(getEnd(E->getLHS()));
22285e20cdd8SDimitry Andric 
22294df029ccSDimitry Andric     // Track LHS True/False Decision.
22304df029ccSDimitry Andric     const auto DecisionLHS = MCDCBuilder.pop();
22314df029ccSDimitry Andric 
2232b60736ecSDimitry Andric     // Counter tracks the right hand side of a logical and operator.
22335e20cdd8SDimitry Andric     extendRegion(E->getRHS());
22345e20cdd8SDimitry Andric     propagateCounts(getRegionCounter(E), E->getRHS());
2235b60736ecSDimitry Andric 
22364df029ccSDimitry Andric     // Track RHS True/False Decision.
22374df029ccSDimitry Andric     const auto DecisionRHS = MCDCBuilder.back();
22384df029ccSDimitry Andric 
2239b60736ecSDimitry Andric     // Extract the RHS's Execution Counter.
2240b60736ecSDimitry Andric     Counter RHSExecCnt = getRegionCounter(E);
2241b60736ecSDimitry Andric 
2242b60736ecSDimitry Andric     // Extract the RHS's "True" Instance Counter.
2243b60736ecSDimitry Andric     Counter RHSTrueCnt = getRegionCounter(E->getRHS());
2244b60736ecSDimitry Andric 
2245b60736ecSDimitry Andric     // Extract the Parent Region Counter.
2246b60736ecSDimitry Andric     Counter ParentCnt = getRegion().getCounter();
2247b60736ecSDimitry Andric 
2248b60736ecSDimitry Andric     // Create Branch Region around LHS condition.
2249ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
2250b60736ecSDimitry Andric       createBranchRegion(E->getLHS(), RHSExecCnt,
22514df029ccSDimitry Andric                          subtractCounters(ParentCnt, RHSExecCnt), DecisionLHS);
2252b60736ecSDimitry Andric 
2253b60736ecSDimitry Andric     // Create Branch Region around RHS condition.
2254ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
2255b60736ecSDimitry Andric       createBranchRegion(E->getRHS(), RHSTrueCnt,
22564df029ccSDimitry Andric                          subtractCounters(RHSExecCnt, RHSTrueCnt), DecisionRHS);
2257ac9a064cSDimitry Andric 
2258ac9a064cSDimitry Andric     // Create MCDC Decision Region if at top-level (root).
2259ac9a064cSDimitry Andric     if (IsRootNode)
2260ac9a064cSDimitry Andric       createOrCancelDecision(E, SourceRegionsSince);
226106d4ba38SDimitry Andric   }
226206d4ba38SDimitry Andric 
22637fa27ce4SDimitry Andric   // Determine whether the right side of OR operation need to be visited.
shouldVisitRHS__anon015dba650211::CounterCoverageMappingBuilder22647fa27ce4SDimitry Andric   bool shouldVisitRHS(const Expr *LHS) {
22657fa27ce4SDimitry Andric     bool LHSIsTrue = false;
22667fa27ce4SDimitry Andric     bool LHSIsConst = false;
22677fa27ce4SDimitry Andric     if (!LHS->isValueDependent())
22687fa27ce4SDimitry Andric       LHSIsConst = LHS->EvaluateAsBooleanCondition(
22697fa27ce4SDimitry Andric           LHSIsTrue, CVM.getCodeGenModule().getContext());
22707fa27ce4SDimitry Andric     return !LHSIsConst || (LHSIsConst && !LHSIsTrue);
22717fa27ce4SDimitry Andric   }
22727fa27ce4SDimitry Andric 
VisitBinLOr__anon015dba650211::CounterCoverageMappingBuilder227306d4ba38SDimitry Andric   void VisitBinLOr(const BinaryOperator *E) {
2274ac9a064cSDimitry Andric     if (isExprInSystemHeader(E)) {
2275ac9a064cSDimitry Andric       LeafExprSet.insert(E);
2276ac9a064cSDimitry Andric       return;
2277ac9a064cSDimitry Andric     }
2278ac9a064cSDimitry Andric 
22794df029ccSDimitry Andric     bool IsRootNode = MCDCBuilder.isIdle();
22804df029ccSDimitry Andric 
2281ac9a064cSDimitry Andric     unsigned SourceRegionsSince = SourceRegions.size();
2282ac9a064cSDimitry Andric 
22834df029ccSDimitry Andric     // Keep track of Binary Operator and assign MCDC condition IDs.
2284aca2e42cSDimitry Andric     MCDCBuilder.pushAndAssignIDs(E);
2285aca2e42cSDimitry Andric 
2286461a67faSDimitry Andric     extendRegion(E->getLHS());
22877fa27ce4SDimitry Andric     Counter OutCount = propagateCounts(getRegion().getCounter(), E->getLHS());
2288461a67faSDimitry Andric     handleFileExit(getEnd(E->getLHS()));
22895e20cdd8SDimitry Andric 
22904df029ccSDimitry Andric     // Track LHS True/False Decision.
22914df029ccSDimitry Andric     const auto DecisionLHS = MCDCBuilder.pop();
22924df029ccSDimitry Andric 
2293b60736ecSDimitry Andric     // Counter tracks the right hand side of a logical or operator.
22945e20cdd8SDimitry Andric     extendRegion(E->getRHS());
22955e20cdd8SDimitry Andric     propagateCounts(getRegionCounter(E), E->getRHS());
2296b60736ecSDimitry Andric 
22974df029ccSDimitry Andric     // Track RHS True/False Decision.
22984df029ccSDimitry Andric     const auto DecisionRHS = MCDCBuilder.back();
22994df029ccSDimitry Andric 
2300b60736ecSDimitry Andric     // Extract the RHS's Execution Counter.
2301b60736ecSDimitry Andric     Counter RHSExecCnt = getRegionCounter(E);
2302b60736ecSDimitry Andric 
2303b60736ecSDimitry Andric     // Extract the RHS's "False" Instance Counter.
2304b60736ecSDimitry Andric     Counter RHSFalseCnt = getRegionCounter(E->getRHS());
2305b60736ecSDimitry Andric 
23067fa27ce4SDimitry Andric     if (!shouldVisitRHS(E->getLHS())) {
23077fa27ce4SDimitry Andric       GapRegionCounter = OutCount;
23087fa27ce4SDimitry Andric     }
23097fa27ce4SDimitry Andric 
2310b60736ecSDimitry Andric     // Extract the Parent Region Counter.
2311b60736ecSDimitry Andric     Counter ParentCnt = getRegion().getCounter();
2312b60736ecSDimitry Andric 
2313b60736ecSDimitry Andric     // Create Branch Region around LHS condition.
2314ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
2315b60736ecSDimitry Andric       createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
23164df029ccSDimitry Andric                          RHSExecCnt, DecisionLHS);
2317b60736ecSDimitry Andric 
2318b60736ecSDimitry Andric     // Create Branch Region around RHS condition.
2319ac9a064cSDimitry Andric     if (!llvm::EnableSingleByteCoverage)
2320b60736ecSDimitry Andric       createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
23214df029ccSDimitry Andric                          RHSFalseCnt, DecisionRHS);
2322ac9a064cSDimitry Andric 
2323ac9a064cSDimitry Andric     // Create MCDC Decision Region if at top-level (root).
2324ac9a064cSDimitry Andric     if (IsRootNode)
2325ac9a064cSDimitry Andric       createOrCancelDecision(E, SourceRegionsSince);
232606d4ba38SDimitry Andric   }
232706d4ba38SDimitry Andric 
VisitLambdaExpr__anon015dba650211::CounterCoverageMappingBuilder23285e20cdd8SDimitry Andric   void VisitLambdaExpr(const LambdaExpr *LE) {
23295e20cdd8SDimitry Andric     // Lambdas are treated as their own functions for now, so we shouldn't
23305e20cdd8SDimitry Andric     // propagate counts into them.
233106d4ba38SDimitry Andric   }
23327fa27ce4SDimitry Andric 
VisitArrayInitLoopExpr__anon015dba650211::CounterCoverageMappingBuilder2333ac9a064cSDimitry Andric   void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *AILE) {
2334ac9a064cSDimitry Andric     Visit(AILE->getCommonExpr()->getSourceExpr());
2335ac9a064cSDimitry Andric   }
2336ac9a064cSDimitry Andric 
VisitPseudoObjectExpr__anon015dba650211::CounterCoverageMappingBuilder23377fa27ce4SDimitry Andric   void VisitPseudoObjectExpr(const PseudoObjectExpr *POE) {
23387fa27ce4SDimitry Andric     // Just visit syntatic expression as this is what users actually write.
23397fa27ce4SDimitry Andric     VisitStmt(POE->getSyntacticForm());
23407fa27ce4SDimitry Andric   }
23417fa27ce4SDimitry Andric 
VisitOpaqueValueExpr__anon015dba650211::CounterCoverageMappingBuilder23427fa27ce4SDimitry Andric   void VisitOpaqueValueExpr(const OpaqueValueExpr* OVE) {
2343ac9a064cSDimitry Andric     if (OVE->isUnique())
23447fa27ce4SDimitry Andric       Visit(OVE->getSourceExpr());
23457fa27ce4SDimitry Andric   }
234606d4ba38SDimitry Andric };
234706d4ba38SDimitry Andric 
2348bab175ecSDimitry Andric } // end anonymous namespace
2349bab175ecSDimitry Andric 
dump(llvm::raw_ostream & OS,StringRef FunctionName,ArrayRef<CounterExpression> Expressions,ArrayRef<CounterMappingRegion> Regions)23505e20cdd8SDimitry Andric static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
23515e20cdd8SDimitry Andric                  ArrayRef<CounterExpression> Expressions,
23525e20cdd8SDimitry Andric                  ArrayRef<CounterMappingRegion> Regions) {
23535e20cdd8SDimitry Andric   OS << FunctionName << ":\n";
23545e20cdd8SDimitry Andric   CounterMappingContext Ctx(Expressions);
23555e20cdd8SDimitry Andric   for (const auto &R : Regions) {
235606d4ba38SDimitry Andric     OS.indent(2);
235706d4ba38SDimitry Andric     switch (R.Kind) {
235806d4ba38SDimitry Andric     case CounterMappingRegion::CodeRegion:
235906d4ba38SDimitry Andric       break;
236006d4ba38SDimitry Andric     case CounterMappingRegion::ExpansionRegion:
236106d4ba38SDimitry Andric       OS << "Expansion,";
236206d4ba38SDimitry Andric       break;
236306d4ba38SDimitry Andric     case CounterMappingRegion::SkippedRegion:
236406d4ba38SDimitry Andric       OS << "Skipped,";
236506d4ba38SDimitry Andric       break;
2366461a67faSDimitry Andric     case CounterMappingRegion::GapRegion:
2367461a67faSDimitry Andric       OS << "Gap,";
2368461a67faSDimitry Andric       break;
2369b60736ecSDimitry Andric     case CounterMappingRegion::BranchRegion:
2370312c0ed1SDimitry Andric     case CounterMappingRegion::MCDCBranchRegion:
2371b60736ecSDimitry Andric       OS << "Branch,";
2372b60736ecSDimitry Andric       break;
2373312c0ed1SDimitry Andric     case CounterMappingRegion::MCDCDecisionRegion:
2374312c0ed1SDimitry Andric       OS << "Decision,";
2375312c0ed1SDimitry Andric       break;
237606d4ba38SDimitry Andric     }
237706d4ba38SDimitry Andric 
23785e20cdd8SDimitry Andric     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
23795e20cdd8SDimitry Andric        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
2380aca2e42cSDimitry Andric 
2381ac9a064cSDimitry Andric     if (const auto *DecisionParams =
2382ac9a064cSDimitry Andric             std::get_if<mcdc::DecisionParameters>(&R.MCDCParams)) {
2383ac9a064cSDimitry Andric       OS << "M:" << DecisionParams->BitmapIdx;
2384ac9a064cSDimitry Andric       OS << ", C:" << DecisionParams->NumConditions;
2385aca2e42cSDimitry Andric     } else {
23865e20cdd8SDimitry Andric       Ctx.dump(R.Count, OS);
2387b60736ecSDimitry Andric 
2388aca2e42cSDimitry Andric       if (R.Kind == CounterMappingRegion::BranchRegion ||
2389aca2e42cSDimitry Andric           R.Kind == CounterMappingRegion::MCDCBranchRegion) {
2390b60736ecSDimitry Andric         OS << ", ";
2391b60736ecSDimitry Andric         Ctx.dump(R.FalseCount, OS);
2392b60736ecSDimitry Andric       }
2393aca2e42cSDimitry Andric     }
2394aca2e42cSDimitry Andric 
2395ac9a064cSDimitry Andric     if (const auto *BranchParams =
2396ac9a064cSDimitry Andric             std::get_if<mcdc::BranchParameters>(&R.MCDCParams)) {
2397ac9a064cSDimitry Andric       OS << " [" << BranchParams->ID + 1 << ","
2398ac9a064cSDimitry Andric          << BranchParams->Conds[true] + 1;
2399ac9a064cSDimitry Andric       OS << "," << BranchParams->Conds[false] + 1 << "] ";
2400aca2e42cSDimitry Andric     }
2401b60736ecSDimitry Andric 
240206d4ba38SDimitry Andric     if (R.Kind == CounterMappingRegion::ExpansionRegion)
24035e20cdd8SDimitry Andric       OS << " (Expanded file = " << R.ExpandedFileID << ")";
24045e20cdd8SDimitry Andric     OS << "\n";
240506d4ba38SDimitry Andric   }
240606d4ba38SDimitry Andric }
240706d4ba38SDimitry Andric 
CoverageMappingModuleGen(CodeGenModule & CGM,CoverageSourceInfo & SourceInfo)2408b60736ecSDimitry Andric CoverageMappingModuleGen::CoverageMappingModuleGen(
2409b60736ecSDimitry Andric     CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
24107fa27ce4SDimitry Andric     : CGM(CGM), SourceInfo(SourceInfo) {}
2411344a3780SDimitry Andric 
getCurrentDirname()2412344a3780SDimitry Andric std::string CoverageMappingModuleGen::getCurrentDirname() {
2413344a3780SDimitry Andric   if (!CGM.getCodeGenOpts().CoverageCompilationDir.empty())
2414344a3780SDimitry Andric     return CGM.getCodeGenOpts().CoverageCompilationDir;
2415344a3780SDimitry Andric 
2416344a3780SDimitry Andric   SmallString<256> CWD;
2417344a3780SDimitry Andric   llvm::sys::fs::current_path(CWD);
2418344a3780SDimitry Andric   return CWD.str().str();
2419b60736ecSDimitry Andric }
2420b60736ecSDimitry Andric 
normalizeFilename(StringRef Filename)2421b60736ecSDimitry Andric std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
2422b60736ecSDimitry Andric   llvm::SmallString<256> Path(Filename);
2423b60736ecSDimitry Andric   llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
24247fa27ce4SDimitry Andric 
24257fa27ce4SDimitry Andric   /// Traverse coverage prefix map in reverse order because prefix replacements
24267fa27ce4SDimitry Andric   /// are applied in reverse order starting from the last one when multiple
24277fa27ce4SDimitry Andric   /// prefix replacement options are provided.
24287fa27ce4SDimitry Andric   for (const auto &[From, To] :
24297fa27ce4SDimitry Andric        llvm::reverse(CGM.getCodeGenOpts().CoveragePrefixMap)) {
24307fa27ce4SDimitry Andric     if (llvm::sys::path::replace_path_prefix(Path, From, To))
2431b60736ecSDimitry Andric       break;
2432b60736ecSDimitry Andric   }
2433b60736ecSDimitry Andric   return Path.str().str();
2434b60736ecSDimitry Andric }
2435b60736ecSDimitry Andric 
getInstrProfSection(const CodeGenModule & CGM,llvm::InstrProfSectKind SK)2436cfca06d7SDimitry Andric static std::string getInstrProfSection(const CodeGenModule &CGM,
2437cfca06d7SDimitry Andric                                        llvm::InstrProfSectKind SK) {
2438cfca06d7SDimitry Andric   return llvm::getInstrProfSectionName(
2439cfca06d7SDimitry Andric       SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
2440cfca06d7SDimitry Andric }
2441cfca06d7SDimitry Andric 
emitFunctionMappingRecord(const FunctionInfo & Info,uint64_t FilenamesRef)2442cfca06d7SDimitry Andric void CoverageMappingModuleGen::emitFunctionMappingRecord(
2443cfca06d7SDimitry Andric     const FunctionInfo &Info, uint64_t FilenamesRef) {
244406d4ba38SDimitry Andric   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
2445cfca06d7SDimitry Andric 
2446cfca06d7SDimitry Andric   // Assign a name to the function record. This is used to merge duplicates.
2447cfca06d7SDimitry Andric   std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
2448cfca06d7SDimitry Andric 
2449cfca06d7SDimitry Andric   // A dummy description for a function included-but-not-used in a TU can be
2450cfca06d7SDimitry Andric   // replaced by full description provided by a different TU. The two kinds of
2451cfca06d7SDimitry Andric   // descriptions play distinct roles: therefore, assign them different names
2452cfca06d7SDimitry Andric   // to prevent `linkonce_odr` merging.
2453cfca06d7SDimitry Andric   if (Info.IsUsed)
2454cfca06d7SDimitry Andric     FuncRecordName += "u";
2455cfca06d7SDimitry Andric 
2456cfca06d7SDimitry Andric   // Create the function record type.
2457cfca06d7SDimitry Andric   const uint64_t NameHash = Info.NameHash;
2458cfca06d7SDimitry Andric   const uint64_t FuncHash = Info.FuncHash;
2459cfca06d7SDimitry Andric   const std::string &CoverageMapping = Info.CoverageMapping;
246045b53394SDimitry Andric #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
246145b53394SDimitry Andric   llvm::Type *FunctionRecordTypes[] = {
246245b53394SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
246345b53394SDimitry Andric   };
2464cfca06d7SDimitry Andric   auto *FunctionRecordTy =
2465e3b55780SDimitry Andric       llvm::StructType::get(Ctx, ArrayRef(FunctionRecordTypes),
2466c192b3dcSDimitry Andric                             /*isPacked=*/true);
246706d4ba38SDimitry Andric 
2468cfca06d7SDimitry Andric   // Create the function record constant.
246945b53394SDimitry Andric #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
247006d4ba38SDimitry Andric   llvm::Constant *FunctionRecordVals[] = {
247145b53394SDimitry Andric       #include "llvm/ProfileData/InstrProfData.inc"
247245b53394SDimitry Andric   };
2473e3b55780SDimitry Andric   auto *FuncRecordConstant =
2474e3b55780SDimitry Andric       llvm::ConstantStruct::get(FunctionRecordTy, ArrayRef(FunctionRecordVals));
2475cfca06d7SDimitry Andric 
2476cfca06d7SDimitry Andric   // Create the function record global.
2477cfca06d7SDimitry Andric   auto *FuncRecord = new llvm::GlobalVariable(
2478cfca06d7SDimitry Andric       CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
2479cfca06d7SDimitry Andric       llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
2480cfca06d7SDimitry Andric       FuncRecordName);
2481cfca06d7SDimitry Andric   FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
2482cfca06d7SDimitry Andric   FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
2483cfca06d7SDimitry Andric   FuncRecord->setAlignment(llvm::Align(8));
2484cfca06d7SDimitry Andric   if (CGM.supportsCOMDAT())
2485cfca06d7SDimitry Andric     FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
2486cfca06d7SDimitry Andric 
2487cfca06d7SDimitry Andric   // Make sure the data doesn't get deleted.
2488cfca06d7SDimitry Andric   CGM.addUsedGlobal(FuncRecord);
2489cfca06d7SDimitry Andric }
2490cfca06d7SDimitry Andric 
addFunctionMappingRecord(llvm::GlobalVariable * NamePtr,StringRef NameValue,uint64_t FuncHash,const std::string & CoverageMapping,bool IsUsed)2491cfca06d7SDimitry Andric void CoverageMappingModuleGen::addFunctionMappingRecord(
2492cfca06d7SDimitry Andric     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
2493cfca06d7SDimitry Andric     const std::string &CoverageMapping, bool IsUsed) {
2494cfca06d7SDimitry Andric   const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
2495cfca06d7SDimitry Andric   FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
2496cfca06d7SDimitry Andric 
24972b6b257fSDimitry Andric   if (!IsUsed)
2498b1c73532SDimitry Andric     FunctionNames.push_back(NamePtr);
249906d4ba38SDimitry Andric 
250006d4ba38SDimitry Andric   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
250106d4ba38SDimitry Andric     // Dump the coverage mapping data for this function by decoding the
250206d4ba38SDimitry Andric     // encoded data. This allows us to dump the mapping regions which were
250306d4ba38SDimitry Andric     // also processed by the CoverageMappingWriter which performs
250406d4ba38SDimitry Andric     // additional minimization operations such as reducing the number of
250506d4ba38SDimitry Andric     // expressions.
2506344a3780SDimitry Andric     llvm::SmallVector<std::string, 16> FilenameStrs;
250706d4ba38SDimitry Andric     std::vector<StringRef> Filenames;
250806d4ba38SDimitry Andric     std::vector<CounterExpression> Expressions;
250906d4ba38SDimitry Andric     std::vector<CounterMappingRegion> Regions;
2510344a3780SDimitry Andric     FilenameStrs.resize(FileEntries.size() + 1);
2511344a3780SDimitry Andric     FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2512bab175ecSDimitry Andric     for (const auto &Entry : FileEntries) {
2513bab175ecSDimitry Andric       auto I = Entry.second;
2514b1c73532SDimitry Andric       FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2515bab175ecSDimitry Andric     }
2516e3b55780SDimitry Andric     ArrayRef<std::string> FilenameRefs = llvm::ArrayRef(FilenameStrs);
25175e20cdd8SDimitry Andric     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
25185e20cdd8SDimitry Andric                                     Expressions, Regions);
25195e20cdd8SDimitry Andric     if (Reader.read())
252006d4ba38SDimitry Andric       return;
252145b53394SDimitry Andric     dump(llvm::outs(), NameValue, Expressions, Regions);
252206d4ba38SDimitry Andric   }
252306d4ba38SDimitry Andric }
252406d4ba38SDimitry Andric 
emit()252506d4ba38SDimitry Andric void CoverageMappingModuleGen::emit() {
252606d4ba38SDimitry Andric   if (FunctionRecords.empty())
252706d4ba38SDimitry Andric     return;
252806d4ba38SDimitry Andric   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
252906d4ba38SDimitry Andric   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
253006d4ba38SDimitry Andric 
253106d4ba38SDimitry Andric   // Create the filenames and merge them with coverage mappings
253206d4ba38SDimitry Andric   llvm::SmallVector<std::string, 16> FilenameStrs;
2533344a3780SDimitry Andric   FilenameStrs.resize(FileEntries.size() + 1);
2534344a3780SDimitry Andric   // The first filename is the current working directory.
2535344a3780SDimitry Andric   FilenameStrs[0] = normalizeFilename(getCurrentDirname());
253606d4ba38SDimitry Andric   for (const auto &Entry : FileEntries) {
253706d4ba38SDimitry Andric     auto I = Entry.second;
2538b1c73532SDimitry Andric     FilenameStrs[I] = normalizeFilename(Entry.first.getName());
253906d4ba38SDimitry Andric   }
254006d4ba38SDimitry Andric 
2541cfca06d7SDimitry Andric   std::string Filenames;
2542cfca06d7SDimitry Andric   {
2543cfca06d7SDimitry Andric     llvm::raw_string_ostream OS(Filenames);
2544344a3780SDimitry Andric     CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
254522989816SDimitry Andric   }
2546cfca06d7SDimitry Andric   auto *FilenamesVal =
2547cfca06d7SDimitry Andric       llvm::ConstantDataArray::getString(Ctx, Filenames, false);
2548cfca06d7SDimitry Andric   const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
254922989816SDimitry Andric 
2550cfca06d7SDimitry Andric   // Emit the function records.
2551cfca06d7SDimitry Andric   for (const FunctionInfo &Info : FunctionRecords)
2552cfca06d7SDimitry Andric     emitFunctionMappingRecord(Info, FilenamesRef);
255306d4ba38SDimitry Andric 
2554cfca06d7SDimitry Andric   const unsigned NRecords = 0;
2555cfca06d7SDimitry Andric   const size_t FilenamesSize = Filenames.size();
2556cfca06d7SDimitry Andric   const unsigned CoverageMappingSize = 0;
255797b17066SDimitry Andric   llvm::Type *CovDataHeaderTypes[] = {
255897b17066SDimitry Andric #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
255997b17066SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
256097b17066SDimitry Andric   };
256197b17066SDimitry Andric   auto CovDataHeaderTy =
2562e3b55780SDimitry Andric       llvm::StructType::get(Ctx, ArrayRef(CovDataHeaderTypes));
256397b17066SDimitry Andric   llvm::Constant *CovDataHeaderVals[] = {
256497b17066SDimitry Andric #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
256597b17066SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
256697b17066SDimitry Andric   };
2567e3b55780SDimitry Andric   auto CovDataHeaderVal =
2568e3b55780SDimitry Andric       llvm::ConstantStruct::get(CovDataHeaderTy, ArrayRef(CovDataHeaderVals));
256997b17066SDimitry Andric 
257006d4ba38SDimitry Andric   // Create the coverage data record
2571cfca06d7SDimitry Andric   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
2572e3b55780SDimitry Andric   auto CovDataTy = llvm::StructType::get(Ctx, ArrayRef(CovDataTypes));
2573cfca06d7SDimitry Andric   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
2574e3b55780SDimitry Andric   auto CovDataVal = llvm::ConstantStruct::get(CovDataTy, ArrayRef(TUDataVals));
257597b17066SDimitry Andric   auto CovData = new llvm::GlobalVariable(
2576cfca06d7SDimitry Andric       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
257797b17066SDimitry Andric       CovDataVal, llvm::getCoverageMappingVarName());
257806d4ba38SDimitry Andric 
2579cfca06d7SDimitry Andric   CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
2580519fc96cSDimitry Andric   CovData->setAlignment(llvm::Align(8));
258106d4ba38SDimitry Andric 
258206d4ba38SDimitry Andric   // Make sure the data doesn't get deleted.
258306d4ba38SDimitry Andric   CGM.addUsedGlobal(CovData);
25840414e226SDimitry Andric   // Create the deferred function records array
25850414e226SDimitry Andric   if (!FunctionNames.empty()) {
2586b1c73532SDimitry Andric     auto NamesArrTy = llvm::ArrayType::get(llvm::PointerType::getUnqual(Ctx),
25870414e226SDimitry Andric                                            FunctionNames.size());
25880414e226SDimitry Andric     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
25890414e226SDimitry Andric     // This variable will *NOT* be emitted to the object file. It is used
25900414e226SDimitry Andric     // to pass the list of names referenced to codegen.
25910414e226SDimitry Andric     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
25920414e226SDimitry Andric                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
25932b6b257fSDimitry Andric                              llvm::getCoverageUnusedNamesVarName());
25940414e226SDimitry Andric   }
259506d4ba38SDimitry Andric }
259606d4ba38SDimitry Andric 
getFileID(FileEntryRef File)2597b1c73532SDimitry Andric unsigned CoverageMappingModuleGen::getFileID(FileEntryRef File) {
259806d4ba38SDimitry Andric   auto It = FileEntries.find(File);
259906d4ba38SDimitry Andric   if (It != FileEntries.end())
260006d4ba38SDimitry Andric     return It->second;
2601344a3780SDimitry Andric   unsigned FileID = FileEntries.size() + 1;
260206d4ba38SDimitry Andric   FileEntries.insert(std::make_pair(File, FileID));
260306d4ba38SDimitry Andric   return FileID;
260406d4ba38SDimitry Andric }
260506d4ba38SDimitry Andric 
emitCounterMapping(const Decl * D,llvm::raw_ostream & OS)260606d4ba38SDimitry Andric void CoverageMappingGen::emitCounterMapping(const Decl *D,
260706d4ba38SDimitry Andric                                             llvm::raw_ostream &OS) {
2608ac9a064cSDimitry Andric   assert(CounterMap && MCDCState);
2609ac9a064cSDimitry Andric   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, *MCDCState, SM,
2610ac9a064cSDimitry Andric                                        LangOpts);
261106d4ba38SDimitry Andric   Walker.VisitDecl(D);
261206d4ba38SDimitry Andric   Walker.write(OS);
261306d4ba38SDimitry Andric }
261406d4ba38SDimitry Andric 
emitEmptyMapping(const Decl * D,llvm::raw_ostream & OS)261506d4ba38SDimitry Andric void CoverageMappingGen::emitEmptyMapping(const Decl *D,
261606d4ba38SDimitry Andric                                           llvm::raw_ostream &OS) {
261706d4ba38SDimitry Andric   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
261806d4ba38SDimitry Andric   Walker.VisitDecl(D);
261906d4ba38SDimitry Andric   Walker.write(OS);
262006d4ba38SDimitry Andric }
2621