xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Instrumentation-based code coverage mapping generator
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CoverageMappingGen.h"
14 #include "CodeGenFunction.h"
15 #include "clang/AST/StmtVisitor.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Frontend/FrontendDiagnostic.h"
19 #include "clang/Lex/Lexer.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
23 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
24 #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
25 #include "llvm/ProfileData/InstrProfReader.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Path.h"
28 #include <optional>
29 
30 // This selects the coverage mapping format defined when `InstrProfData.inc`
31 // is textually included.
32 #define COVMAP_V3
33 
34 static llvm::cl::opt<bool> EmptyLineCommentCoverage(
35     "emptyline-comment-coverage",
36     llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
37                    "disable it on test)"),
38     llvm::cl::init(true), llvm::cl::Hidden);
39 
40 static llvm::cl::opt<bool> SystemHeadersCoverage(
41     "system-headers-coverage",
42     llvm::cl::desc("Enable collecting coverage from system headers"),
43     llvm::cl::init(false), llvm::cl::Hidden);
44 
45 using namespace clang;
46 using namespace CodeGen;
47 using namespace llvm::coverage;
48 
49 CoverageSourceInfo *
50 CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
51   CoverageSourceInfo *CoverageInfo =
52       new CoverageSourceInfo(PP.getSourceManager());
53   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
54   if (EmptyLineCommentCoverage) {
55     PP.addCommentHandler(CoverageInfo);
56     PP.setEmptylineHandler(CoverageInfo);
57     PP.setPreprocessToken(true);
58     PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
59       // Update previous token location.
60       CoverageInfo->PrevTokLoc = Tok.getLocation();
61       if (Tok.getKind() != clang::tok::eod)
62         CoverageInfo->updateNextTokLoc(Tok.getLocation());
63     });
64   }
65   return CoverageInfo;
66 }
67 
68 void CoverageSourceInfo::AddSkippedRange(SourceRange Range,
69                                          SkippedRange::Kind RangeKind) {
70   if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
71       PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
72       SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
73                                     Range.getBegin()))
74     SkippedRanges.back().Range.setEnd(Range.getEnd());
75   else
76     SkippedRanges.push_back({Range, RangeKind, PrevTokLoc});
77 }
78 
79 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
80   AddSkippedRange(Range, SkippedRange::PPIfElse);
81 }
82 
83 void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
84   AddSkippedRange(Range, SkippedRange::EmptyLine);
85 }
86 
87 bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
88   AddSkippedRange(Range, SkippedRange::Comment);
89   return false;
90 }
91 
92 void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
93   if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
94     SkippedRanges.back().NextTokLoc = Loc;
95 }
96 
97 namespace {
98 using MCDCConditionID = CounterMappingRegion::MCDCConditionID;
99 using MCDCParameters = CounterMappingRegion::MCDCParameters;
100 
101 /// A region of source code that can be mapped to a counter.
102 class SourceMappingRegion {
103   /// Primary Counter that is also used for Branch Regions for "True" branches.
104   Counter Count;
105 
106   /// Secondary Counter used for Branch Regions for "False" branches.
107   std::optional<Counter> FalseCount;
108 
109   /// Parameters used for Modified Condition/Decision Coverage
110   MCDCParameters MCDCParams;
111 
112   /// The region's starting location.
113   std::optional<SourceLocation> LocStart;
114 
115   /// The region's ending location.
116   std::optional<SourceLocation> LocEnd;
117 
118   /// Whether this region is a gap region. The count from a gap region is set
119   /// as the line execution count if there are no other regions on the line.
120   bool GapRegion;
121 
122 public:
123   SourceMappingRegion(Counter Count, std::optional<SourceLocation> LocStart,
124                       std::optional<SourceLocation> LocEnd,
125                       bool GapRegion = false)
126       : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) {
127   }
128 
129   SourceMappingRegion(Counter Count, std::optional<Counter> FalseCount,
130                       MCDCParameters MCDCParams,
131                       std::optional<SourceLocation> LocStart,
132                       std::optional<SourceLocation> LocEnd,
133                       bool GapRegion = false)
134       : Count(Count), FalseCount(FalseCount), MCDCParams(MCDCParams),
135         LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) {}
136 
137   SourceMappingRegion(MCDCParameters MCDCParams,
138                       std::optional<SourceLocation> LocStart,
139                       std::optional<SourceLocation> LocEnd)
140       : MCDCParams(MCDCParams), LocStart(LocStart), LocEnd(LocEnd),
141         GapRegion(false) {}
142 
143   const Counter &getCounter() const { return Count; }
144 
145   const Counter &getFalseCounter() const {
146     assert(FalseCount && "Region has no alternate counter");
147     return *FalseCount;
148   }
149 
150   void setCounter(Counter C) { Count = C; }
151 
152   bool hasStartLoc() const { return LocStart.has_value(); }
153 
154   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
155 
156   SourceLocation getBeginLoc() const {
157     assert(LocStart && "Region has no start location");
158     return *LocStart;
159   }
160 
161   bool hasEndLoc() const { return LocEnd.has_value(); }
162 
163   void setEndLoc(SourceLocation Loc) {
164     assert(Loc.isValid() && "Setting an invalid end location");
165     LocEnd = Loc;
166   }
167 
168   SourceLocation getEndLoc() const {
169     assert(LocEnd && "Region has no end location");
170     return *LocEnd;
171   }
172 
173   bool isGap() const { return GapRegion; }
174 
175   void setGap(bool Gap) { GapRegion = Gap; }
176 
177   bool isBranch() const { return FalseCount.has_value(); }
178 
179   bool isMCDCDecision() const { return MCDCParams.NumConditions != 0; }
180 
181   const MCDCParameters &getMCDCParams() const { return MCDCParams; }
182 };
183 
184 /// Spelling locations for the start and end of a source region.
185 struct SpellingRegion {
186   /// The line where the region starts.
187   unsigned LineStart;
188 
189   /// The column where the region starts.
190   unsigned ColumnStart;
191 
192   /// The line where the region ends.
193   unsigned LineEnd;
194 
195   /// The column where the region ends.
196   unsigned ColumnEnd;
197 
198   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
199                  SourceLocation LocEnd) {
200     LineStart = SM.getSpellingLineNumber(LocStart);
201     ColumnStart = SM.getSpellingColumnNumber(LocStart);
202     LineEnd = SM.getSpellingLineNumber(LocEnd);
203     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
204   }
205 
206   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
207       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
208 
209   /// Check if the start and end locations appear in source order, i.e
210   /// top->bottom, left->right.
211   bool isInSourceOrder() const {
212     return (LineStart < LineEnd) ||
213            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
214   }
215 };
216 
217 /// Provides the common functionality for the different
218 /// coverage mapping region builders.
219 class CoverageMappingBuilder {
220 public:
221   CoverageMappingModuleGen &CVM;
222   SourceManager &SM;
223   const LangOptions &LangOpts;
224 
225 private:
226   /// Map of clang's FileIDs to IDs used for coverage mapping.
227   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
228       FileIDMapping;
229 
230 public:
231   /// The coverage mapping regions for this function
232   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
233   /// The source mapping regions for this function.
234   std::vector<SourceMappingRegion> SourceRegions;
235 
236   /// A set of regions which can be used as a filter.
237   ///
238   /// It is produced by emitExpansionRegions() and is used in
239   /// emitSourceRegions() to suppress producing code regions if
240   /// the same area is covered by expansion regions.
241   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
242       SourceRegionFilter;
243 
244   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
245                          const LangOptions &LangOpts)
246       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
247 
248   /// Return the precise end location for the given token.
249   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
250     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
251     // macro locations, which we just treat as expanded files.
252     unsigned TokLen =
253         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
254     return Loc.getLocWithOffset(TokLen);
255   }
256 
257   /// Return the start location of an included file or expanded macro.
258   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
259     if (Loc.isMacroID())
260       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
261     return SM.getLocForStartOfFile(SM.getFileID(Loc));
262   }
263 
264   /// Return the end location of an included file or expanded macro.
265   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
266     if (Loc.isMacroID())
267       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
268                                   SM.getFileOffset(Loc));
269     return SM.getLocForEndOfFile(SM.getFileID(Loc));
270   }
271 
272   /// Find out where the current file is included or macro is expanded.
273   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
274     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
275                            : SM.getIncludeLoc(SM.getFileID(Loc));
276   }
277 
278   /// Return true if \c Loc is a location in a built-in macro.
279   bool isInBuiltin(SourceLocation Loc) {
280     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
281   }
282 
283   /// Check whether \c Loc is included or expanded from \c Parent.
284   bool isNestedIn(SourceLocation Loc, FileID Parent) {
285     do {
286       Loc = getIncludeOrExpansionLoc(Loc);
287       if (Loc.isInvalid())
288         return false;
289     } while (!SM.isInFileID(Loc, Parent));
290     return true;
291   }
292 
293   /// Get the start of \c S ignoring macro arguments and builtin macros.
294   SourceLocation getStart(const Stmt *S) {
295     SourceLocation Loc = S->getBeginLoc();
296     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
297       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
298     return Loc;
299   }
300 
301   /// Get the end of \c S ignoring macro arguments and builtin macros.
302   SourceLocation getEnd(const Stmt *S) {
303     SourceLocation Loc = S->getEndLoc();
304     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
305       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
306     return getPreciseTokenLocEnd(Loc);
307   }
308 
309   /// Find the set of files we have regions for and assign IDs
310   ///
311   /// Fills \c Mapping with the virtual file mapping needed to write out
312   /// coverage and collects the necessary file information to emit source and
313   /// expansion regions.
314   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
315     FileIDMapping.clear();
316 
317     llvm::SmallSet<FileID, 8> Visited;
318     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
319     for (const auto &Region : SourceRegions) {
320       SourceLocation Loc = Region.getBeginLoc();
321       FileID File = SM.getFileID(Loc);
322       if (!Visited.insert(File).second)
323         continue;
324 
325       // Do not map FileID's associated with system headers unless collecting
326       // coverage from system headers is explicitly enabled.
327       if (!SystemHeadersCoverage && SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
328         continue;
329 
330       unsigned Depth = 0;
331       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
332            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
333         ++Depth;
334       FileLocs.push_back(std::make_pair(Loc, Depth));
335     }
336     llvm::stable_sort(FileLocs, llvm::less_second());
337 
338     for (const auto &FL : FileLocs) {
339       SourceLocation Loc = FL.first;
340       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
341       auto Entry = SM.getFileEntryRefForID(SpellingFile);
342       if (!Entry)
343         continue;
344 
345       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
346       Mapping.push_back(CVM.getFileID(*Entry));
347     }
348   }
349 
350   /// Get the coverage mapping file ID for \c Loc.
351   ///
352   /// If such file id doesn't exist, return std::nullopt.
353   std::optional<unsigned> getCoverageFileID(SourceLocation Loc) {
354     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
355     if (Mapping != FileIDMapping.end())
356       return Mapping->second.first;
357     return std::nullopt;
358   }
359 
360   /// This shrinks the skipped range if it spans a line that contains a
361   /// non-comment token. If shrinking the skipped range would make it empty,
362   /// this returns std::nullopt.
363   /// Note this function can potentially be expensive because
364   /// getSpellingLineNumber uses getLineNumber, which is expensive.
365   std::optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
366                                                    SourceLocation LocStart,
367                                                    SourceLocation LocEnd,
368                                                    SourceLocation PrevTokLoc,
369                                                    SourceLocation NextTokLoc) {
370     SpellingRegion SR{SM, LocStart, LocEnd};
371     SR.ColumnStart = 1;
372     if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
373         SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
374       SR.LineStart++;
375     if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
376         SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
377       SR.LineEnd--;
378       SR.ColumnEnd++;
379     }
380     if (SR.isInSourceOrder())
381       return SR;
382     return std::nullopt;
383   }
384 
385   /// Gather all the regions that were skipped by the preprocessor
386   /// using the constructs like #if or comments.
387   void gatherSkippedRegions() {
388     /// An array of the minimum lineStarts and the maximum lineEnds
389     /// for mapping regions from the appropriate source files.
390     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
391     FileLineRanges.resize(
392         FileIDMapping.size(),
393         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
394     for (const auto &R : MappingRegions) {
395       FileLineRanges[R.FileID].first =
396           std::min(FileLineRanges[R.FileID].first, R.LineStart);
397       FileLineRanges[R.FileID].second =
398           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
399     }
400 
401     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
402     for (auto &I : SkippedRanges) {
403       SourceRange Range = I.Range;
404       auto LocStart = Range.getBegin();
405       auto LocEnd = Range.getEnd();
406       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
407              "region spans multiple files");
408 
409       auto CovFileID = getCoverageFileID(LocStart);
410       if (!CovFileID)
411         continue;
412       std::optional<SpellingRegion> SR;
413       if (I.isComment())
414         SR = adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc,
415                                 I.NextTokLoc);
416       else if (I.isPPIfElse() || I.isEmptyLine())
417         SR = {SM, LocStart, LocEnd};
418 
419       if (!SR)
420         continue;
421       auto Region = CounterMappingRegion::makeSkipped(
422           *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
423           SR->ColumnEnd);
424       // Make sure that we only collect the regions that are inside
425       // the source code of this function.
426       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
427           Region.LineEnd <= FileLineRanges[*CovFileID].second)
428         MappingRegions.push_back(Region);
429     }
430   }
431 
432   /// Generate the coverage counter mapping regions from collected
433   /// source regions.
434   void emitSourceRegions(const SourceRegionFilter &Filter) {
435     for (const auto &Region : SourceRegions) {
436       assert(Region.hasEndLoc() && "incomplete region");
437 
438       SourceLocation LocStart = Region.getBeginLoc();
439       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
440 
441       // Ignore regions from system headers unless collecting coverage from
442       // system headers is explicitly enabled.
443       if (!SystemHeadersCoverage &&
444           SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
445         continue;
446 
447       auto CovFileID = getCoverageFileID(LocStart);
448       // Ignore regions that don't have a file, such as builtin macros.
449       if (!CovFileID)
450         continue;
451 
452       SourceLocation LocEnd = Region.getEndLoc();
453       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
454              "region spans multiple files");
455 
456       // Don't add code regions for the area covered by expansion regions.
457       // This not only suppresses redundant regions, but sometimes prevents
458       // creating regions with wrong counters if, for example, a statement's
459       // body ends at the end of a nested macro.
460       if (Filter.count(std::make_pair(LocStart, LocEnd)))
461         continue;
462 
463       // Find the spelling locations for the mapping region.
464       SpellingRegion SR{SM, LocStart, LocEnd};
465       assert(SR.isInSourceOrder() && "region start and end out of order");
466 
467       if (Region.isGap()) {
468         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
469             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
470             SR.LineEnd, SR.ColumnEnd));
471       } else if (Region.isBranch()) {
472         MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
473             Region.getCounter(), Region.getFalseCounter(),
474             Region.getMCDCParams(), *CovFileID, SR.LineStart, SR.ColumnStart,
475             SR.LineEnd, SR.ColumnEnd));
476       } else if (Region.isMCDCDecision()) {
477         MappingRegions.push_back(CounterMappingRegion::makeDecisionRegion(
478             Region.getMCDCParams(), *CovFileID, SR.LineStart, SR.ColumnStart,
479             SR.LineEnd, SR.ColumnEnd));
480       } else {
481         MappingRegions.push_back(CounterMappingRegion::makeRegion(
482             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
483             SR.LineEnd, SR.ColumnEnd));
484       }
485     }
486   }
487 
488   /// Generate expansion regions for each virtual file we've seen.
489   SourceRegionFilter emitExpansionRegions() {
490     SourceRegionFilter Filter;
491     for (const auto &FM : FileIDMapping) {
492       SourceLocation ExpandedLoc = FM.second.second;
493       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
494       if (ParentLoc.isInvalid())
495         continue;
496 
497       auto ParentFileID = getCoverageFileID(ParentLoc);
498       if (!ParentFileID)
499         continue;
500       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
501       assert(ExpandedFileID && "expansion in uncovered file");
502 
503       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
504       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
505              "region spans multiple files");
506       Filter.insert(std::make_pair(ParentLoc, LocEnd));
507 
508       SpellingRegion SR{SM, ParentLoc, LocEnd};
509       assert(SR.isInSourceOrder() && "region start and end out of order");
510       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
511           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
512           SR.LineEnd, SR.ColumnEnd));
513     }
514     return Filter;
515   }
516 };
517 
518 /// Creates unreachable coverage regions for the functions that
519 /// are not emitted.
520 struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
521   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
522                               const LangOptions &LangOpts)
523       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
524 
525   void VisitDecl(const Decl *D) {
526     if (!D->hasBody())
527       return;
528     auto Body = D->getBody();
529     SourceLocation Start = getStart(Body);
530     SourceLocation End = getEnd(Body);
531     if (!SM.isWrittenInSameFile(Start, End)) {
532       // Walk up to find the common ancestor.
533       // Correct the locations accordingly.
534       FileID StartFileID = SM.getFileID(Start);
535       FileID EndFileID = SM.getFileID(End);
536       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
537         Start = getIncludeOrExpansionLoc(Start);
538         assert(Start.isValid() &&
539                "Declaration start location not nested within a known region");
540         StartFileID = SM.getFileID(Start);
541       }
542       while (StartFileID != EndFileID) {
543         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
544         assert(End.isValid() &&
545                "Declaration end location not nested within a known region");
546         EndFileID = SM.getFileID(End);
547       }
548     }
549     SourceRegions.emplace_back(Counter(), Start, End);
550   }
551 
552   /// Write the mapping data to the output stream
553   void write(llvm::raw_ostream &OS) {
554     SmallVector<unsigned, 16> FileIDMapping;
555     gatherFileIDs(FileIDMapping);
556     emitSourceRegions(SourceRegionFilter());
557 
558     if (MappingRegions.empty())
559       return;
560 
561     CoverageMappingWriter Writer(FileIDMapping, std::nullopt, MappingRegions);
562     Writer.write(OS);
563   }
564 };
565 
566 /// A wrapper object for maintaining stacks to track the resursive AST visitor
567 /// walks for the purpose of assigning IDs to leaf-level conditions measured by
568 /// MC/DC. The object is created with a reference to the MCDCBitmapMap that was
569 /// created during the initial AST walk. The presence of a bitmap associated
570 /// with a boolean expression (top-level logical operator nest) indicates that
571 /// the boolean expression qualified for MC/DC.  The resulting condition IDs
572 /// are preserved in a map reference that is also provided during object
573 /// creation.
574 struct MCDCCoverageBuilder {
575 
576   /// The AST walk recursively visits nested logical-AND or logical-OR binary
577   /// operator nodes and then visits their LHS and RHS children nodes.  As this
578   /// happens, the algorithm will assign IDs to each operator's LHS and RHS side
579   /// as the walk moves deeper into the nest.  At each level of the recursive
580   /// nest, the LHS and RHS may actually correspond to larger subtrees (not
581   /// leaf-conditions). If this is the case, when that node is visited, the ID
582   /// assigned to the subtree is re-assigned to its LHS, and a new ID is given
583   /// to its RHS. At the end of the walk, all leaf-level conditions will have a
584   /// unique ID -- keep in mind that the final set of IDs may not be in
585   /// numerical order from left to right.
586   ///
587   /// Example: "x = (A && B) || (C && D) || (D && F)"
588   ///
589   ///      Visit Depth1:
590   ///              (A && B) || (C && D) || (D && F)
591   ///              ^-------LHS--------^    ^-RHS--^
592   ///                      ID=1              ID=2
593   ///
594   ///      Visit LHS-Depth2:
595   ///              (A && B) || (C && D)
596   ///              ^-LHS--^    ^-RHS--^
597   ///                ID=1        ID=3
598   ///
599   ///      Visit LHS-Depth3:
600   ///               (A && B)
601   ///               LHS   RHS
602   ///               ID=1  ID=4
603   ///
604   ///      Visit RHS-Depth3:
605   ///                         (C && D)
606   ///                         LHS   RHS
607   ///                         ID=3  ID=5
608   ///
609   ///      Visit RHS-Depth2:              (D && F)
610   ///                                     LHS   RHS
611   ///                                     ID=2  ID=6
612   ///
613   ///      Visit Depth1:
614   ///              (A && B)  || (C && D)  || (D && F)
615   ///              ID=1  ID=4   ID=3  ID=5   ID=2  ID=6
616   ///
617   /// A node ID of '0' always means MC/DC isn't being tracked.
618   ///
619   /// As the AST walk proceeds recursively, the algorithm will also use stacks
620   /// to track the IDs of logical-AND and logical-OR operations on the RHS so
621   /// that it can be determined which nodes are executed next, depending on how
622   /// a LHS or RHS of a logical-AND or logical-OR is evaluated.  This
623   /// information relies on the assigned IDs and are embedded within the
624   /// coverage region IDs of each branch region associated with a leaf-level
625   /// condition. This information helps the visualization tool reconstruct all
626   /// possible test vectors for the purposes of MC/DC analysis. if a "next" node
627   /// ID is '0', it means it's the end of the test vector. The following rules
628   /// are used:
629   ///
630   /// For logical-AND ("LHS && RHS"):
631   /// - If LHS is TRUE, execution goes to the RHS node.
632   /// - If LHS is FALSE, execution goes to the LHS node of the next logical-OR.
633   ///   If that does not exist, execution exits (ID == 0).
634   ///
635   /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND.
636   ///   If that does not exist, execution exits (ID == 0).
637   /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR.
638   ///   If that does not exist, execution exits (ID == 0).
639   ///
640   /// For logical-OR ("LHS || RHS"):
641   /// - If LHS is TRUE, execution goes to the LHS node of the next logical-AND.
642   ///   If that does not exist, execution exits (ID == 0).
643   /// - If LHS is FALSE, execution goes to the RHS node.
644   ///
645   /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND.
646   ///   If that does not exist, execution exits (ID == 0).
647   /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR.
648   ///   If that does not exist, execution exits (ID == 0).
649   ///
650   /// Finally, the condition IDs are also used when instrumenting the code to
651   /// indicate a unique offset into a temporary bitmap that represents the true
652   /// or false evaluation of that particular condition.
653   ///
654   /// NOTE regarding the use of CodeGenFunction::stripCond(). Even though, for
655   /// simplicity, parentheses and unary logical-NOT operators are considered
656   /// part of their underlying condition for both MC/DC and branch coverage, the
657   /// condition IDs themselves are assigned and tracked using the underlying
658   /// condition itself.  This is done solely for consistency since parentheses
659   /// and logical-NOTs are ignored when checking whether the condition is
660   /// actually an instrumentable condition. This can also make debugging a bit
661   /// easier.
662 
663 private:
664   CodeGenModule &CGM;
665 
666   llvm::SmallVector<MCDCConditionID> AndRHS;
667   llvm::SmallVector<MCDCConditionID> OrRHS;
668   llvm::SmallVector<const BinaryOperator *> NestLevel;
669   llvm::DenseMap<const Stmt *, MCDCConditionID> &CondIDs;
670   llvm::DenseMap<const Stmt *, unsigned> &MCDCBitmapMap;
671   MCDCConditionID NextID = 1;
672   bool NotMapped = false;
673 
674   /// Is this a logical-AND operation?
675   bool isLAnd(const BinaryOperator *E) const {
676     return E->getOpcode() == BO_LAnd;
677   }
678 
679   /// Push an ID onto the corresponding RHS stack.
680   void pushRHS(const BinaryOperator *E) {
681     llvm::SmallVector<MCDCConditionID> &rhs = isLAnd(E) ? AndRHS : OrRHS;
682     rhs.push_back(CondIDs[CodeGenFunction::stripCond(E->getRHS())]);
683   }
684 
685   /// Pop an ID from the corresponding RHS stack.
686   void popRHS(const BinaryOperator *E) {
687     llvm::SmallVector<MCDCConditionID> &rhs = isLAnd(E) ? AndRHS : OrRHS;
688     if (!rhs.empty())
689       rhs.pop_back();
690   }
691 
692   /// If the expected ID is on top, pop it off the corresponding RHS stack.
693   void popRHSifTop(const BinaryOperator *E) {
694     if (!OrRHS.empty() && CondIDs[E] == OrRHS.back())
695       OrRHS.pop_back();
696     else if (!AndRHS.empty() && CondIDs[E] == AndRHS.back())
697       AndRHS.pop_back();
698   }
699 
700 public:
701   MCDCCoverageBuilder(CodeGenModule &CGM,
702                       llvm::DenseMap<const Stmt *, MCDCConditionID> &CondIDMap,
703                       llvm::DenseMap<const Stmt *, unsigned> &MCDCBitmapMap)
704       : CGM(CGM), CondIDs(CondIDMap), MCDCBitmapMap(MCDCBitmapMap) {}
705 
706   /// Return the ID of the RHS of the next, upper nest-level logical-OR.
707   MCDCConditionID getNextLOrCondID() const {
708     return OrRHS.empty() ? 0 : OrRHS.back();
709   }
710 
711   /// Return the ID of the RHS of the next, upper nest-level logical-AND.
712   MCDCConditionID getNextLAndCondID() const {
713     return AndRHS.empty() ? 0 : AndRHS.back();
714   }
715 
716   /// Return the ID of a given condition.
717   MCDCConditionID getCondID(const Expr *Cond) const {
718     auto I = CondIDs.find(CodeGenFunction::stripCond(Cond));
719     if (I == CondIDs.end())
720       return 0;
721     else
722       return I->second;
723   }
724 
725   /// Push the binary operator statement to track the nest level and assign IDs
726   /// to the operator's LHS and RHS.  The RHS may be a larger subtree that is
727   /// broken up on successive levels.
728   void pushAndAssignIDs(const BinaryOperator *E) {
729     if (!CGM.getCodeGenOpts().MCDCCoverage)
730       return;
731 
732     // If binary expression is disqualified, don't do mapping.
733     if (NestLevel.empty() && MCDCBitmapMap.find(CodeGenFunction::stripCond(
734                                  E)) == MCDCBitmapMap.end())
735       NotMapped = true;
736 
737     // Push Stmt on 'NestLevel' stack to keep track of nest location.
738     NestLevel.push_back(E);
739 
740     // Don't go any further if we don't need to map condition IDs.
741     if (NotMapped)
742       return;
743 
744     // If the operator itself has an assigned ID, this means it represents a
745     // larger subtree.  In this case, pop its ID out of the RHS stack and
746     // assign that ID to its LHS node.  Its RHS will receive a new ID.
747     if (CondIDs.find(CodeGenFunction::stripCond(E)) != CondIDs.end()) {
748       // If Stmt has an ID, assign its ID to LHS
749       CondIDs[CodeGenFunction::stripCond(E->getLHS())] = CondIDs[E];
750 
751       // Since the operator's LHS assumes the operator's same ID, pop the
752       // operator from the RHS stack so that if LHS short-circuits, it won't be
753       // incorrectly re-used as the node executed next.
754       popRHSifTop(E);
755     } else {
756       // Otherwise, assign ID+1 to LHS.
757       CondIDs[CodeGenFunction::stripCond(E->getLHS())] = NextID++;
758     }
759 
760     // Assign ID+1 to RHS.
761     CondIDs[CodeGenFunction::stripCond(E->getRHS())] = NextID++;
762 
763     // Push ID of Stmt's RHS so that LHS nodes know about it
764     pushRHS(E);
765   }
766 
767   /// Pop the binary operator from the next level. If the walk is at the top of
768   /// the next, assign the total number of conditions.
769   unsigned popAndReturnCondCount(const BinaryOperator *E) {
770     if (!CGM.getCodeGenOpts().MCDCCoverage)
771       return 0;
772 
773     unsigned TotalConds = 0;
774 
775     // Pop Stmt from 'NestLevel' stack.
776     assert(NestLevel.back() == E);
777     NestLevel.pop_back();
778 
779     // Reset state if not doing mapping.
780     if (NestLevel.empty() && NotMapped) {
781       NotMapped = false;
782       return 0;
783     }
784 
785     // Pop RHS ID.
786     popRHS(E);
787 
788     // If at the parent (NestLevel=0), set conds and reset.
789     if (NestLevel.empty()) {
790       TotalConds = NextID - 1;
791 
792       // Reset ID back to beginning.
793       NextID = 1;
794     }
795     return TotalConds;
796   }
797 };
798 
799 /// A StmtVisitor that creates coverage mapping regions which map
800 /// from the source code locations to the PGO counters.
801 struct CounterCoverageMappingBuilder
802     : public CoverageMappingBuilder,
803       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
804   /// The map of statements to count values.
805   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
806 
807   /// The map of statements to bitmap coverage object values.
808   llvm::DenseMap<const Stmt *, unsigned> &MCDCBitmapMap;
809 
810   /// A stack of currently live regions.
811   llvm::SmallVector<SourceMappingRegion> RegionStack;
812 
813   /// An object to manage MCDC regions.
814   MCDCCoverageBuilder MCDCBuilder;
815 
816   CounterExpressionBuilder Builder;
817 
818   /// A location in the most recently visited file or macro.
819   ///
820   /// This is used to adjust the active source regions appropriately when
821   /// expressions cross file or macro boundaries.
822   SourceLocation MostRecentLocation;
823 
824   /// Whether the visitor at a terminate statement.
825   bool HasTerminateStmt = false;
826 
827   /// Gap region counter after terminate statement.
828   Counter GapRegionCounter;
829 
830   /// Return a counter for the subtraction of \c RHS from \c LHS
831   Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
832     return Builder.subtract(LHS, RHS, Simplify);
833   }
834 
835   /// Return a counter for the sum of \c LHS and \c RHS.
836   Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) {
837     return Builder.add(LHS, RHS, Simplify);
838   }
839 
840   Counter addCounters(Counter C1, Counter C2, Counter C3,
841                       bool Simplify = true) {
842     return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
843   }
844 
845   /// Return the region counter for the given statement.
846   ///
847   /// This should only be called on statements that have a dedicated counter.
848   Counter getRegionCounter(const Stmt *S) {
849     return Counter::getCounter(CounterMap[S]);
850   }
851 
852   unsigned getRegionBitmap(const Stmt *S) { return MCDCBitmapMap[S]; }
853 
854   /// Push a region onto the stack.
855   ///
856   /// Returns the index on the stack where the region was pushed. This can be
857   /// used with popRegions to exit a "scope", ending the region that was pushed.
858   size_t pushRegion(Counter Count,
859                     std::optional<SourceLocation> StartLoc = std::nullopt,
860                     std::optional<SourceLocation> EndLoc = std::nullopt,
861                     std::optional<Counter> FalseCount = std::nullopt,
862                     MCDCConditionID ID = 0, MCDCConditionID TrueID = 0,
863                     MCDCConditionID FalseID = 0) {
864 
865     if (StartLoc && !FalseCount) {
866       MostRecentLocation = *StartLoc;
867     }
868 
869     // If either of these locations is invalid, something elsewhere in the
870     // compiler has broken.
871     assert((!StartLoc || StartLoc->isValid()) && "Start location is not valid");
872     assert((!EndLoc || EndLoc->isValid()) && "End location is not valid");
873 
874     // However, we can still recover without crashing.
875     // If either location is invalid, set it to std::nullopt to avoid
876     // letting users of RegionStack think that region has a valid start/end
877     // location.
878     if (StartLoc && StartLoc->isInvalid())
879       StartLoc = std::nullopt;
880     if (EndLoc && EndLoc->isInvalid())
881       EndLoc = std::nullopt;
882     RegionStack.emplace_back(Count, FalseCount,
883                              MCDCParameters{0, 0, ID, TrueID, FalseID},
884                              StartLoc, EndLoc);
885 
886     return RegionStack.size() - 1;
887   }
888 
889   size_t pushRegion(unsigned BitmapIdx, unsigned Conditions,
890                     std::optional<SourceLocation> StartLoc = std::nullopt,
891                     std::optional<SourceLocation> EndLoc = std::nullopt) {
892 
893     RegionStack.emplace_back(MCDCParameters{BitmapIdx, Conditions}, StartLoc,
894                              EndLoc);
895 
896     return RegionStack.size() - 1;
897   }
898 
899   size_t locationDepth(SourceLocation Loc) {
900     size_t Depth = 0;
901     while (Loc.isValid()) {
902       Loc = getIncludeOrExpansionLoc(Loc);
903       Depth++;
904     }
905     return Depth;
906   }
907 
908   /// Pop regions from the stack into the function's list of regions.
909   ///
910   /// Adds all regions from \c ParentIndex to the top of the stack to the
911   /// function's \c SourceRegions.
912   void popRegions(size_t ParentIndex) {
913     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
914     while (RegionStack.size() > ParentIndex) {
915       SourceMappingRegion &Region = RegionStack.back();
916       if (Region.hasStartLoc() &&
917           (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
918         SourceLocation StartLoc = Region.getBeginLoc();
919         SourceLocation EndLoc = Region.hasEndLoc()
920                                     ? Region.getEndLoc()
921                                     : RegionStack[ParentIndex].getEndLoc();
922         bool isBranch = Region.isBranch();
923         size_t StartDepth = locationDepth(StartLoc);
924         size_t EndDepth = locationDepth(EndLoc);
925         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
926           bool UnnestStart = StartDepth >= EndDepth;
927           bool UnnestEnd = EndDepth >= StartDepth;
928           if (UnnestEnd) {
929             // The region ends in a nested file or macro expansion. If the
930             // region is not a branch region, create a separate region for each
931             // expansion, and for all regions, update the EndLoc. Branch
932             // regions should not be split in order to keep a straightforward
933             // correspondance between the region and its associated branch
934             // condition, even if the condition spans multiple depths.
935             SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
936             assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
937 
938             if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
939               SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
940                                          EndLoc);
941 
942             EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
943             if (EndLoc.isInvalid())
944               llvm::report_fatal_error(
945                   "File exit not handled before popRegions");
946             EndDepth--;
947           }
948           if (UnnestStart) {
949             // The region ends in a nested file or macro expansion. If the
950             // region is not a branch region, create a separate region for each
951             // expansion, and for all regions, update the StartLoc. Branch
952             // regions should not be split in order to keep a straightforward
953             // correspondance between the region and its associated branch
954             // condition, even if the condition spans multiple depths.
955             SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
956             assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
957 
958             if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
959               SourceRegions.emplace_back(Region.getCounter(), StartLoc,
960                                          NestedLoc);
961 
962             StartLoc = getIncludeOrExpansionLoc(StartLoc);
963             if (StartLoc.isInvalid())
964               llvm::report_fatal_error(
965                   "File exit not handled before popRegions");
966             StartDepth--;
967           }
968         }
969         Region.setStartLoc(StartLoc);
970         Region.setEndLoc(EndLoc);
971 
972         if (!isBranch) {
973           MostRecentLocation = EndLoc;
974           // If this region happens to span an entire expansion, we need to
975           // make sure we don't overlap the parent region with it.
976           if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
977               EndLoc == getEndOfFileOrMacro(EndLoc))
978             MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
979         }
980 
981         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
982         assert(SpellingRegion(SM, Region).isInSourceOrder());
983         SourceRegions.push_back(Region);
984       }
985       RegionStack.pop_back();
986     }
987   }
988 
989   /// Return the currently active region.
990   SourceMappingRegion &getRegion() {
991     assert(!RegionStack.empty() && "statement has no region");
992     return RegionStack.back();
993   }
994 
995   /// Propagate counts through the children of \p S if \p VisitChildren is true.
996   /// Otherwise, only emit a count for \p S itself.
997   Counter propagateCounts(Counter TopCount, const Stmt *S,
998                           bool VisitChildren = true) {
999     SourceLocation StartLoc = getStart(S);
1000     SourceLocation EndLoc = getEnd(S);
1001     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
1002     if (VisitChildren)
1003       Visit(S);
1004     Counter ExitCount = getRegion().getCounter();
1005     popRegions(Index);
1006 
1007     // The statement may be spanned by an expansion. Make sure we handle a file
1008     // exit out of this expansion before moving to the next statement.
1009     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
1010       MostRecentLocation = EndLoc;
1011 
1012     return ExitCount;
1013   }
1014 
1015   /// Determine whether the given condition can be constant folded.
1016   bool ConditionFoldsToBool(const Expr *Cond) {
1017     Expr::EvalResult Result;
1018     return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
1019   }
1020 
1021   /// Create a Branch Region around an instrumentable condition for coverage
1022   /// and add it to the function's SourceRegions.  A branch region tracks a
1023   /// "True" counter and a "False" counter for boolean expressions that
1024   /// result in the generation of a branch.
1025   void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt,
1026                           MCDCConditionID ID = 0, MCDCConditionID TrueID = 0,
1027                           MCDCConditionID FalseID = 0) {
1028     // Check for NULL conditions.
1029     if (!C)
1030       return;
1031 
1032     // Ensure we are an instrumentable condition (i.e. no "&&" or "||").  Push
1033     // region onto RegionStack but immediately pop it (which adds it to the
1034     // function's SourceRegions) because it doesn't apply to any other source
1035     // code other than the Condition.
1036     if (CodeGenFunction::isInstrumentedCondition(C)) {
1037       // If a condition can fold to true or false, the corresponding branch
1038       // will be removed.  Create a region with both counters hard-coded to
1039       // zero. This allows us to visualize them in a special way.
1040       // Alternatively, we can prevent any optimization done via
1041       // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
1042       // CodeGenFunction.c always returns false, but that is very heavy-handed.
1043       if (ConditionFoldsToBool(C))
1044         popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
1045                               Counter::getZero(), ID, TrueID, FalseID));
1046       else
1047         // Otherwise, create a region with the True counter and False counter.
1048         popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt, ID,
1049                               TrueID, FalseID));
1050     }
1051   }
1052 
1053   /// Create a Decision Region with a BitmapIdx and number of Conditions. This
1054   /// type of region "contains" branch regions, one for each of the conditions.
1055   /// The visualization tool will group everything together.
1056   void createDecisionRegion(const Expr *C, unsigned BitmapIdx, unsigned Conds) {
1057     popRegions(pushRegion(BitmapIdx, Conds, getStart(C), getEnd(C)));
1058   }
1059 
1060   /// Create a Branch Region around a SwitchCase for code coverage
1061   /// and add it to the function's SourceRegions.
1062   void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt,
1063                               Counter FalseCnt) {
1064     // Push region onto RegionStack but immediately pop it (which adds it to
1065     // the function's SourceRegions) because it doesn't apply to any other
1066     // source other than the SwitchCase.
1067     popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
1068   }
1069 
1070   /// Check whether a region with bounds \c StartLoc and \c EndLoc
1071   /// is already added to \c SourceRegions.
1072   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
1073                             bool isBranch = false) {
1074     return llvm::any_of(
1075         llvm::reverse(SourceRegions), [&](const SourceMappingRegion &Region) {
1076           return Region.getBeginLoc() == StartLoc &&
1077                  Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
1078         });
1079   }
1080 
1081   /// Adjust the most recently visited location to \c EndLoc.
1082   ///
1083   /// This should be used after visiting any statements in non-source order.
1084   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
1085     MostRecentLocation = EndLoc;
1086     // The code region for a whole macro is created in handleFileExit() when
1087     // it detects exiting of the virtual file of that macro. If we visited
1088     // statements in non-source order, we might already have such a region
1089     // added, for example, if a body of a loop is divided among multiple
1090     // macros. Avoid adding duplicate regions in such case.
1091     if (getRegion().hasEndLoc() &&
1092         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
1093         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
1094                              MostRecentLocation, getRegion().isBranch()))
1095       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
1096   }
1097 
1098   /// Adjust regions and state when \c NewLoc exits a file.
1099   ///
1100   /// If moving from our most recently tracked location to \c NewLoc exits any
1101   /// files, this adjusts our current region stack and creates the file regions
1102   /// for the exited file.
1103   void handleFileExit(SourceLocation NewLoc) {
1104     if (NewLoc.isInvalid() ||
1105         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
1106       return;
1107 
1108     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
1109     // find the common ancestor.
1110     SourceLocation LCA = NewLoc;
1111     FileID ParentFile = SM.getFileID(LCA);
1112     while (!isNestedIn(MostRecentLocation, ParentFile)) {
1113       LCA = getIncludeOrExpansionLoc(LCA);
1114       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
1115         // Since there isn't a common ancestor, no file was exited. We just need
1116         // to adjust our location to the new file.
1117         MostRecentLocation = NewLoc;
1118         return;
1119       }
1120       ParentFile = SM.getFileID(LCA);
1121     }
1122 
1123     llvm::SmallSet<SourceLocation, 8> StartLocs;
1124     std::optional<Counter> ParentCounter;
1125     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
1126       if (!I.hasStartLoc())
1127         continue;
1128       SourceLocation Loc = I.getBeginLoc();
1129       if (!isNestedIn(Loc, ParentFile)) {
1130         ParentCounter = I.getCounter();
1131         break;
1132       }
1133 
1134       while (!SM.isInFileID(Loc, ParentFile)) {
1135         // The most nested region for each start location is the one with the
1136         // correct count. We avoid creating redundant regions by stopping once
1137         // we've seen this region.
1138         if (StartLocs.insert(Loc).second) {
1139           if (I.isBranch())
1140             SourceRegions.emplace_back(
1141                 I.getCounter(), I.getFalseCounter(),
1142                 MCDCParameters{0, 0, I.getMCDCParams().ID,
1143                                I.getMCDCParams().TrueID,
1144                                I.getMCDCParams().FalseID},
1145                 Loc, getEndOfFileOrMacro(Loc), I.isBranch());
1146           else
1147             SourceRegions.emplace_back(I.getCounter(), Loc,
1148                                        getEndOfFileOrMacro(Loc));
1149         }
1150         Loc = getIncludeOrExpansionLoc(Loc);
1151       }
1152       I.setStartLoc(getPreciseTokenLocEnd(Loc));
1153     }
1154 
1155     if (ParentCounter) {
1156       // If the file is contained completely by another region and doesn't
1157       // immediately start its own region, the whole file gets a region
1158       // corresponding to the parent.
1159       SourceLocation Loc = MostRecentLocation;
1160       while (isNestedIn(Loc, ParentFile)) {
1161         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
1162         if (StartLocs.insert(FileStart).second) {
1163           SourceRegions.emplace_back(*ParentCounter, FileStart,
1164                                      getEndOfFileOrMacro(Loc));
1165           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
1166         }
1167         Loc = getIncludeOrExpansionLoc(Loc);
1168       }
1169     }
1170 
1171     MostRecentLocation = NewLoc;
1172   }
1173 
1174   /// Ensure that \c S is included in the current region.
1175   void extendRegion(const Stmt *S) {
1176     SourceMappingRegion &Region = getRegion();
1177     SourceLocation StartLoc = getStart(S);
1178 
1179     handleFileExit(StartLoc);
1180     if (!Region.hasStartLoc())
1181       Region.setStartLoc(StartLoc);
1182   }
1183 
1184   /// Mark \c S as a terminator, starting a zero region.
1185   void terminateRegion(const Stmt *S) {
1186     extendRegion(S);
1187     SourceMappingRegion &Region = getRegion();
1188     SourceLocation EndLoc = getEnd(S);
1189     if (!Region.hasEndLoc())
1190       Region.setEndLoc(EndLoc);
1191     pushRegion(Counter::getZero());
1192     HasTerminateStmt = true;
1193   }
1194 
1195   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
1196   std::optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
1197                                                 SourceLocation BeforeLoc) {
1198     // If AfterLoc is in function-like macro, use the right parenthesis
1199     // location.
1200     if (AfterLoc.isMacroID()) {
1201       FileID FID = SM.getFileID(AfterLoc);
1202       const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
1203       if (EI->isFunctionMacroExpansion())
1204         AfterLoc = EI->getExpansionLocEnd();
1205     }
1206 
1207     size_t StartDepth = locationDepth(AfterLoc);
1208     size_t EndDepth = locationDepth(BeforeLoc);
1209     while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
1210       bool UnnestStart = StartDepth >= EndDepth;
1211       bool UnnestEnd = EndDepth >= StartDepth;
1212       if (UnnestEnd) {
1213         assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1214                                       BeforeLoc));
1215 
1216         BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1217         assert(BeforeLoc.isValid());
1218         EndDepth--;
1219       }
1220       if (UnnestStart) {
1221         assert(SM.isWrittenInSameFile(AfterLoc,
1222                                       getEndOfFileOrMacro(AfterLoc)));
1223 
1224         AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
1225         assert(AfterLoc.isValid());
1226         AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1227         assert(AfterLoc.isValid());
1228         StartDepth--;
1229       }
1230     }
1231     AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1232     // If the start and end locations of the gap are both within the same macro
1233     // file, the range may not be in source order.
1234     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
1235       return std::nullopt;
1236     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
1237         !SpellingRegion(SM, AfterLoc, BeforeLoc).isInSourceOrder())
1238       return std::nullopt;
1239     return {{AfterLoc, BeforeLoc}};
1240   }
1241 
1242   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
1243   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
1244                             Counter Count) {
1245     if (StartLoc == EndLoc)
1246       return;
1247     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
1248     handleFileExit(StartLoc);
1249     size_t Index = pushRegion(Count, StartLoc, EndLoc);
1250     getRegion().setGap(true);
1251     handleFileExit(EndLoc);
1252     popRegions(Index);
1253   }
1254 
1255   /// Keep counts of breaks and continues inside loops.
1256   struct BreakContinue {
1257     Counter BreakCount;
1258     Counter ContinueCount;
1259   };
1260   SmallVector<BreakContinue, 8> BreakContinueStack;
1261 
1262   CounterCoverageMappingBuilder(
1263       CoverageMappingModuleGen &CVM,
1264       llvm::DenseMap<const Stmt *, unsigned> &CounterMap,
1265       llvm::DenseMap<const Stmt *, unsigned> &MCDCBitmapMap,
1266       llvm::DenseMap<const Stmt *, MCDCConditionID> &CondIDMap,
1267       SourceManager &SM, const LangOptions &LangOpts)
1268       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
1269         MCDCBitmapMap(MCDCBitmapMap),
1270         MCDCBuilder(CVM.getCodeGenModule(), CondIDMap, MCDCBitmapMap) {}
1271 
1272   /// Write the mapping data to the output stream
1273   void write(llvm::raw_ostream &OS) {
1274     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
1275     gatherFileIDs(VirtualFileMapping);
1276     SourceRegionFilter Filter = emitExpansionRegions();
1277     emitSourceRegions(Filter);
1278     gatherSkippedRegions();
1279 
1280     if (MappingRegions.empty())
1281       return;
1282 
1283     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
1284                                  MappingRegions);
1285     Writer.write(OS);
1286   }
1287 
1288   void VisitStmt(const Stmt *S) {
1289     if (S->getBeginLoc().isValid())
1290       extendRegion(S);
1291     const Stmt *LastStmt = nullptr;
1292     bool SaveTerminateStmt = HasTerminateStmt;
1293     HasTerminateStmt = false;
1294     GapRegionCounter = Counter::getZero();
1295     for (const Stmt *Child : S->children())
1296       if (Child) {
1297         // If last statement contains terminate statements, add a gap area
1298         // between the two statements. Skipping attributed statements, because
1299         // they don't have valid start location.
1300         if (LastStmt && HasTerminateStmt && !isa<AttributedStmt>(Child)) {
1301           auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
1302           if (Gap)
1303             fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
1304                                  GapRegionCounter);
1305           SaveTerminateStmt = true;
1306           HasTerminateStmt = false;
1307         }
1308         this->Visit(Child);
1309         LastStmt = Child;
1310       }
1311     if (SaveTerminateStmt)
1312       HasTerminateStmt = true;
1313     handleFileExit(getEnd(S));
1314   }
1315 
1316   void VisitDecl(const Decl *D) {
1317     Stmt *Body = D->getBody();
1318 
1319     // Do not propagate region counts into system headers unless collecting
1320     // coverage from system headers is explicitly enabled.
1321     if (!SystemHeadersCoverage && Body &&
1322         SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
1323       return;
1324 
1325     // Do not visit the artificial children nodes of defaulted methods. The
1326     // lexer may not be able to report back precise token end locations for
1327     // these children nodes (llvm.org/PR39822), and moreover users will not be
1328     // able to see coverage for them.
1329     Counter BodyCounter = getRegionCounter(Body);
1330     bool Defaulted = false;
1331     if (auto *Method = dyn_cast<CXXMethodDecl>(D))
1332       Defaulted = Method->isDefaulted();
1333     if (auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1334       for (auto *Initializer : Ctor->inits()) {
1335         if (Initializer->isWritten()) {
1336           auto *Init = Initializer->getInit();
1337           if (getStart(Init).isValid() && getEnd(Init).isValid())
1338             propagateCounts(BodyCounter, Init);
1339         }
1340       }
1341     }
1342 
1343     propagateCounts(BodyCounter, Body,
1344                     /*VisitChildren=*/!Defaulted);
1345     assert(RegionStack.empty() && "Regions entered but never exited");
1346   }
1347 
1348   void VisitReturnStmt(const ReturnStmt *S) {
1349     extendRegion(S);
1350     if (S->getRetValue())
1351       Visit(S->getRetValue());
1352     terminateRegion(S);
1353   }
1354 
1355   void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
1356     extendRegion(S);
1357     Visit(S->getBody());
1358   }
1359 
1360   void VisitCoreturnStmt(const CoreturnStmt *S) {
1361     extendRegion(S);
1362     if (S->getOperand())
1363       Visit(S->getOperand());
1364     terminateRegion(S);
1365   }
1366 
1367   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
1368     extendRegion(E);
1369     if (E->getSubExpr())
1370       Visit(E->getSubExpr());
1371     terminateRegion(E);
1372   }
1373 
1374   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
1375 
1376   void VisitLabelStmt(const LabelStmt *S) {
1377     Counter LabelCount = getRegionCounter(S);
1378     SourceLocation Start = getStart(S);
1379     // We can't extendRegion here or we risk overlapping with our new region.
1380     handleFileExit(Start);
1381     pushRegion(LabelCount, Start);
1382     Visit(S->getSubStmt());
1383   }
1384 
1385   void VisitBreakStmt(const BreakStmt *S) {
1386     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1387     BreakContinueStack.back().BreakCount = addCounters(
1388         BreakContinueStack.back().BreakCount, getRegion().getCounter());
1389     // FIXME: a break in a switch should terminate regions for all preceding
1390     // case statements, not just the most recent one.
1391     terminateRegion(S);
1392   }
1393 
1394   void VisitContinueStmt(const ContinueStmt *S) {
1395     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1396     BreakContinueStack.back().ContinueCount = addCounters(
1397         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1398     terminateRegion(S);
1399   }
1400 
1401   void VisitCallExpr(const CallExpr *E) {
1402     VisitStmt(E);
1403 
1404     // Terminate the region when we hit a noreturn function.
1405     // (This is helpful dealing with switch statements.)
1406     QualType CalleeType = E->getCallee()->getType();
1407     if (getFunctionExtInfo(*CalleeType).getNoReturn())
1408       terminateRegion(E);
1409   }
1410 
1411   void VisitWhileStmt(const WhileStmt *S) {
1412     extendRegion(S);
1413 
1414     Counter ParentCount = getRegion().getCounter();
1415     Counter BodyCount = getRegionCounter(S);
1416 
1417     // Handle the body first so that we can get the backedge count.
1418     BreakContinueStack.push_back(BreakContinue());
1419     extendRegion(S->getBody());
1420     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1421     BreakContinue BC = BreakContinueStack.pop_back_val();
1422 
1423     bool BodyHasTerminateStmt = HasTerminateStmt;
1424     HasTerminateStmt = false;
1425 
1426     // Go back to handle the condition.
1427     Counter CondCount =
1428         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1429     propagateCounts(CondCount, S->getCond());
1430     adjustForOutOfOrderTraversal(getEnd(S));
1431 
1432     // The body count applies to the area immediately after the increment.
1433     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1434     if (Gap)
1435       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1436 
1437     Counter OutCount =
1438         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1439     if (OutCount != ParentCount) {
1440       pushRegion(OutCount);
1441       GapRegionCounter = OutCount;
1442       if (BodyHasTerminateStmt)
1443         HasTerminateStmt = true;
1444     }
1445 
1446     // Create Branch Region around condition.
1447     createBranchRegion(S->getCond(), BodyCount,
1448                        subtractCounters(CondCount, BodyCount));
1449   }
1450 
1451   void VisitDoStmt(const DoStmt *S) {
1452     extendRegion(S);
1453 
1454     Counter ParentCount = getRegion().getCounter();
1455     Counter BodyCount = getRegionCounter(S);
1456 
1457     BreakContinueStack.push_back(BreakContinue());
1458     extendRegion(S->getBody());
1459     Counter BackedgeCount =
1460         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1461     BreakContinue BC = BreakContinueStack.pop_back_val();
1462 
1463     bool BodyHasTerminateStmt = HasTerminateStmt;
1464     HasTerminateStmt = false;
1465 
1466     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1467     propagateCounts(CondCount, S->getCond());
1468 
1469     Counter OutCount =
1470         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1471     if (OutCount != ParentCount) {
1472       pushRegion(OutCount);
1473       GapRegionCounter = OutCount;
1474     }
1475 
1476     // Create Branch Region around condition.
1477     createBranchRegion(S->getCond(), BodyCount,
1478                        subtractCounters(CondCount, BodyCount));
1479 
1480     if (BodyHasTerminateStmt)
1481       HasTerminateStmt = true;
1482   }
1483 
1484   void VisitForStmt(const ForStmt *S) {
1485     extendRegion(S);
1486     if (S->getInit())
1487       Visit(S->getInit());
1488 
1489     Counter ParentCount = getRegion().getCounter();
1490     Counter BodyCount = getRegionCounter(S);
1491 
1492     // The loop increment may contain a break or continue.
1493     if (S->getInc())
1494       BreakContinueStack.emplace_back();
1495 
1496     // Handle the body first so that we can get the backedge count.
1497     BreakContinueStack.emplace_back();
1498     extendRegion(S->getBody());
1499     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1500     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1501 
1502     bool BodyHasTerminateStmt = HasTerminateStmt;
1503     HasTerminateStmt = false;
1504 
1505     // The increment is essentially part of the body but it needs to include
1506     // the count for all the continue statements.
1507     BreakContinue IncrementBC;
1508     if (const Stmt *Inc = S->getInc()) {
1509       propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1510       IncrementBC = BreakContinueStack.pop_back_val();
1511     }
1512 
1513     // Go back to handle the condition.
1514     Counter CondCount = addCounters(
1515         addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1516         IncrementBC.ContinueCount);
1517     if (const Expr *Cond = S->getCond()) {
1518       propagateCounts(CondCount, Cond);
1519       adjustForOutOfOrderTraversal(getEnd(S));
1520     }
1521 
1522     // The body count applies to the area immediately after the increment.
1523     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1524     if (Gap)
1525       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1526 
1527     Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1528                                    subtractCounters(CondCount, BodyCount));
1529     if (OutCount != ParentCount) {
1530       pushRegion(OutCount);
1531       GapRegionCounter = OutCount;
1532       if (BodyHasTerminateStmt)
1533         HasTerminateStmt = true;
1534     }
1535 
1536     // Create Branch Region around condition.
1537     createBranchRegion(S->getCond(), BodyCount,
1538                        subtractCounters(CondCount, BodyCount));
1539   }
1540 
1541   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1542     extendRegion(S);
1543     if (S->getInit())
1544       Visit(S->getInit());
1545     Visit(S->getLoopVarStmt());
1546     Visit(S->getRangeStmt());
1547 
1548     Counter ParentCount = getRegion().getCounter();
1549     Counter BodyCount = getRegionCounter(S);
1550 
1551     BreakContinueStack.push_back(BreakContinue());
1552     extendRegion(S->getBody());
1553     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1554     BreakContinue BC = BreakContinueStack.pop_back_val();
1555 
1556     bool BodyHasTerminateStmt = HasTerminateStmt;
1557     HasTerminateStmt = false;
1558 
1559     // The body count applies to the area immediately after the range.
1560     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1561     if (Gap)
1562       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1563 
1564     Counter LoopCount =
1565         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1566     Counter OutCount =
1567         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1568     if (OutCount != ParentCount) {
1569       pushRegion(OutCount);
1570       GapRegionCounter = OutCount;
1571       if (BodyHasTerminateStmt)
1572         HasTerminateStmt = true;
1573     }
1574 
1575     // Create Branch Region around condition.
1576     createBranchRegion(S->getCond(), BodyCount,
1577                        subtractCounters(LoopCount, BodyCount));
1578   }
1579 
1580   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1581     extendRegion(S);
1582     Visit(S->getElement());
1583 
1584     Counter ParentCount = getRegion().getCounter();
1585     Counter BodyCount = getRegionCounter(S);
1586 
1587     BreakContinueStack.push_back(BreakContinue());
1588     extendRegion(S->getBody());
1589     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1590     BreakContinue BC = BreakContinueStack.pop_back_val();
1591 
1592     // The body count applies to the area immediately after the collection.
1593     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1594     if (Gap)
1595       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1596 
1597     Counter LoopCount =
1598         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1599     Counter OutCount =
1600         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1601     if (OutCount != ParentCount) {
1602       pushRegion(OutCount);
1603       GapRegionCounter = OutCount;
1604     }
1605   }
1606 
1607   void VisitSwitchStmt(const SwitchStmt *S) {
1608     extendRegion(S);
1609     if (S->getInit())
1610       Visit(S->getInit());
1611     Visit(S->getCond());
1612 
1613     BreakContinueStack.push_back(BreakContinue());
1614 
1615     const Stmt *Body = S->getBody();
1616     extendRegion(Body);
1617     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1618       if (!CS->body_empty()) {
1619         // Make a region for the body of the switch.  If the body starts with
1620         // a case, that case will reuse this region; otherwise, this covers
1621         // the unreachable code at the beginning of the switch body.
1622         size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1623         getRegion().setGap(true);
1624         Visit(Body);
1625 
1626         // Set the end for the body of the switch, if it isn't already set.
1627         for (size_t i = RegionStack.size(); i != Index; --i) {
1628           if (!RegionStack[i - 1].hasEndLoc())
1629             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1630         }
1631 
1632         popRegions(Index);
1633       }
1634     } else
1635       propagateCounts(Counter::getZero(), Body);
1636     BreakContinue BC = BreakContinueStack.pop_back_val();
1637 
1638     if (!BreakContinueStack.empty())
1639       BreakContinueStack.back().ContinueCount = addCounters(
1640           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1641 
1642     Counter ParentCount = getRegion().getCounter();
1643     Counter ExitCount = getRegionCounter(S);
1644     SourceLocation ExitLoc = getEnd(S);
1645     pushRegion(ExitCount);
1646     GapRegionCounter = ExitCount;
1647 
1648     // Ensure that handleFileExit recognizes when the end location is located
1649     // in a different file.
1650     MostRecentLocation = getStart(S);
1651     handleFileExit(ExitLoc);
1652 
1653     // Create a Branch Region around each Case. Subtract the case's
1654     // counter from the Parent counter to track the "False" branch count.
1655     Counter CaseCountSum;
1656     bool HasDefaultCase = false;
1657     const SwitchCase *Case = S->getSwitchCaseList();
1658     for (; Case; Case = Case->getNextSwitchCase()) {
1659       HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1660       CaseCountSum =
1661           addCounters(CaseCountSum, getRegionCounter(Case), /*Simplify=*/false);
1662       createSwitchCaseRegion(
1663           Case, getRegionCounter(Case),
1664           subtractCounters(ParentCount, getRegionCounter(Case)));
1665     }
1666     // Simplify is skipped while building the counters above: it can get really
1667     // slow on top of switches with thousands of cases. Instead, trigger
1668     // simplification by adding zero to the last counter.
1669     CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
1670 
1671     // If no explicit default case exists, create a branch region to represent
1672     // the hidden branch, which will be added later by the CodeGen. This region
1673     // will be associated with the switch statement's condition.
1674     if (!HasDefaultCase) {
1675       Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
1676       Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
1677       createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
1678     }
1679   }
1680 
1681   void VisitSwitchCase(const SwitchCase *S) {
1682     extendRegion(S);
1683 
1684     SourceMappingRegion &Parent = getRegion();
1685 
1686     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1687     // Reuse the existing region if it starts at our label. This is typical of
1688     // the first case in a switch.
1689     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1690       Parent.setCounter(Count);
1691     else
1692       pushRegion(Count, getStart(S));
1693 
1694     GapRegionCounter = Count;
1695 
1696     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1697       Visit(CS->getLHS());
1698       if (const Expr *RHS = CS->getRHS())
1699         Visit(RHS);
1700     }
1701     Visit(S->getSubStmt());
1702   }
1703 
1704   void VisitIfStmt(const IfStmt *S) {
1705     extendRegion(S);
1706     if (S->getInit())
1707       Visit(S->getInit());
1708 
1709     // Extend into the condition before we propagate through it below - this is
1710     // needed to handle macros that generate the "if" but not the condition.
1711     if (!S->isConsteval())
1712       extendRegion(S->getCond());
1713 
1714     Counter ParentCount = getRegion().getCounter();
1715     Counter ThenCount = getRegionCounter(S);
1716 
1717     if (!S->isConsteval()) {
1718       // Emitting a counter for the condition makes it easier to interpret the
1719       // counter for the body when looking at the coverage.
1720       propagateCounts(ParentCount, S->getCond());
1721 
1722       // The 'then' count applies to the area immediately after the condition.
1723       std::optional<SourceRange> Gap =
1724           findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
1725       if (Gap)
1726         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
1727     }
1728 
1729     extendRegion(S->getThen());
1730     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1731 
1732     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1733     if (const Stmt *Else = S->getElse()) {
1734       bool ThenHasTerminateStmt = HasTerminateStmt;
1735       HasTerminateStmt = false;
1736       // The 'else' count applies to the area immediately after the 'then'.
1737       std::optional<SourceRange> Gap =
1738           findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
1739       if (Gap)
1740         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
1741       extendRegion(Else);
1742       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1743 
1744       if (ThenHasTerminateStmt)
1745         HasTerminateStmt = true;
1746     } else
1747       OutCount = addCounters(OutCount, ElseCount);
1748 
1749     if (OutCount != ParentCount) {
1750       pushRegion(OutCount);
1751       GapRegionCounter = OutCount;
1752     }
1753 
1754     if (!S->isConsteval()) {
1755       // Create Branch Region around condition.
1756       createBranchRegion(S->getCond(), ThenCount,
1757                          subtractCounters(ParentCount, ThenCount));
1758     }
1759   }
1760 
1761   void VisitCXXTryStmt(const CXXTryStmt *S) {
1762     extendRegion(S);
1763     // Handle macros that generate the "try" but not the rest.
1764     extendRegion(S->getTryBlock());
1765 
1766     Counter ParentCount = getRegion().getCounter();
1767     propagateCounts(ParentCount, S->getTryBlock());
1768 
1769     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1770       Visit(S->getHandler(I));
1771 
1772     Counter ExitCount = getRegionCounter(S);
1773     pushRegion(ExitCount);
1774   }
1775 
1776   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1777     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1778   }
1779 
1780   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1781     extendRegion(E);
1782 
1783     Counter ParentCount = getRegion().getCounter();
1784     Counter TrueCount = getRegionCounter(E);
1785 
1786     propagateCounts(ParentCount, E->getCond());
1787     Counter OutCount;
1788 
1789     if (!isa<BinaryConditionalOperator>(E)) {
1790       // The 'then' count applies to the area immediately after the condition.
1791       auto Gap =
1792           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1793       if (Gap)
1794         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
1795 
1796       extendRegion(E->getTrueExpr());
1797       OutCount = propagateCounts(TrueCount, E->getTrueExpr());
1798     }
1799 
1800     extendRegion(E->getFalseExpr());
1801     OutCount = addCounters(
1802         OutCount, propagateCounts(subtractCounters(ParentCount, TrueCount),
1803                                   E->getFalseExpr()));
1804 
1805     if (OutCount != ParentCount) {
1806       pushRegion(OutCount);
1807       GapRegionCounter = OutCount;
1808     }
1809 
1810     // Create Branch Region around condition.
1811     createBranchRegion(E->getCond(), TrueCount,
1812                        subtractCounters(ParentCount, TrueCount));
1813   }
1814 
1815   void VisitBinLAnd(const BinaryOperator *E) {
1816     // Keep track of Binary Operator and assign MCDC condition IDs
1817     MCDCBuilder.pushAndAssignIDs(E);
1818 
1819     extendRegion(E->getLHS());
1820     propagateCounts(getRegion().getCounter(), E->getLHS());
1821     handleFileExit(getEnd(E->getLHS()));
1822 
1823     // Counter tracks the right hand side of a logical and operator.
1824     extendRegion(E->getRHS());
1825     propagateCounts(getRegionCounter(E), E->getRHS());
1826 
1827     // Process Binary Operator and create MCDC Decision Region if top-level
1828     unsigned NumConds = 0;
1829     if ((NumConds = MCDCBuilder.popAndReturnCondCount(E)))
1830       createDecisionRegion(E, getRegionBitmap(E), NumConds);
1831 
1832     // Extract the RHS's Execution Counter.
1833     Counter RHSExecCnt = getRegionCounter(E);
1834 
1835     // Extract the RHS's "True" Instance Counter.
1836     Counter RHSTrueCnt = getRegionCounter(E->getRHS());
1837 
1838     // Extract the Parent Region Counter.
1839     Counter ParentCnt = getRegion().getCounter();
1840 
1841     // Extract the MCDC condition IDs (returns 0 if not needed).
1842     MCDCConditionID NextOrID = MCDCBuilder.getNextLOrCondID();
1843     MCDCConditionID NextAndID = MCDCBuilder.getNextLAndCondID();
1844     MCDCConditionID LHSid = MCDCBuilder.getCondID(E->getLHS());
1845     MCDCConditionID RHSid = MCDCBuilder.getCondID(E->getRHS());
1846 
1847     // Create Branch Region around LHS condition.
1848     // MC/DC: For "LHS && RHS"
1849     // - If LHS is TRUE, execution goes to the RHS.
1850     // - If LHS is FALSE, execution goes to the LHS of the next logical-OR.
1851     //   If that does not exist, execution exits (ID == 0).
1852     createBranchRegion(E->getLHS(), RHSExecCnt,
1853                        subtractCounters(ParentCnt, RHSExecCnt), LHSid, RHSid,
1854                        NextOrID);
1855 
1856     // Create Branch Region around RHS condition.
1857     // MC/DC: For "LHS && RHS"
1858     // - If RHS is TRUE, execution goes to LHS of the next logical-AND.
1859     //   If that does not exist, execution exits (ID == 0).
1860     // - If RHS is FALSE, execution goes to the LHS of the next logical-OR.
1861     //   If that does not exist, execution exits (ID == 0).
1862     createBranchRegion(E->getRHS(), RHSTrueCnt,
1863                        subtractCounters(RHSExecCnt, RHSTrueCnt), RHSid,
1864                        NextAndID, NextOrID);
1865   }
1866 
1867   // Determine whether the right side of OR operation need to be visited.
1868   bool shouldVisitRHS(const Expr *LHS) {
1869     bool LHSIsTrue = false;
1870     bool LHSIsConst = false;
1871     if (!LHS->isValueDependent())
1872       LHSIsConst = LHS->EvaluateAsBooleanCondition(
1873           LHSIsTrue, CVM.getCodeGenModule().getContext());
1874     return !LHSIsConst || (LHSIsConst && !LHSIsTrue);
1875   }
1876 
1877   void VisitBinLOr(const BinaryOperator *E) {
1878     // Keep track of Binary Operator and assign MCDC condition IDs
1879     MCDCBuilder.pushAndAssignIDs(E);
1880 
1881     extendRegion(E->getLHS());
1882     Counter OutCount = propagateCounts(getRegion().getCounter(), E->getLHS());
1883     handleFileExit(getEnd(E->getLHS()));
1884 
1885     // Counter tracks the right hand side of a logical or operator.
1886     extendRegion(E->getRHS());
1887     propagateCounts(getRegionCounter(E), E->getRHS());
1888 
1889     // Process Binary Operator and create MCDC Decision Region if top-level
1890     unsigned NumConds = 0;
1891     if ((NumConds = MCDCBuilder.popAndReturnCondCount(E)))
1892       createDecisionRegion(E, getRegionBitmap(E), NumConds);
1893 
1894     // Extract the RHS's Execution Counter.
1895     Counter RHSExecCnt = getRegionCounter(E);
1896 
1897     // Extract the RHS's "False" Instance Counter.
1898     Counter RHSFalseCnt = getRegionCounter(E->getRHS());
1899 
1900     if (!shouldVisitRHS(E->getLHS())) {
1901       GapRegionCounter = OutCount;
1902     }
1903 
1904     // Extract the Parent Region Counter.
1905     Counter ParentCnt = getRegion().getCounter();
1906 
1907     // Extract the MCDC condition IDs (returns 0 if not needed).
1908     MCDCConditionID NextOrID = MCDCBuilder.getNextLOrCondID();
1909     MCDCConditionID NextAndID = MCDCBuilder.getNextLAndCondID();
1910     MCDCConditionID LHSid = MCDCBuilder.getCondID(E->getLHS());
1911     MCDCConditionID RHSid = MCDCBuilder.getCondID(E->getRHS());
1912 
1913     // Create Branch Region around LHS condition.
1914     // MC/DC: For "LHS || RHS"
1915     // - If LHS is TRUE, execution goes to the LHS of the next logical-AND.
1916     //   If that does not exist, execution exits (ID == 0).
1917     // - If LHS is FALSE, execution goes to the RHS.
1918     createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
1919                        RHSExecCnt, LHSid, NextAndID, RHSid);
1920 
1921     // Create Branch Region around RHS condition.
1922     // MC/DC: For "LHS || RHS"
1923     // - If RHS is TRUE, execution goes to LHS of the next logical-AND.
1924     //   If that does not exist, execution exits (ID == 0).
1925     // - If RHS is FALSE, execution goes to the LHS of the next logical-OR.
1926     //   If that does not exist, execution exits (ID == 0).
1927     createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
1928                        RHSFalseCnt, RHSid, NextAndID, NextOrID);
1929   }
1930 
1931   void VisitLambdaExpr(const LambdaExpr *LE) {
1932     // Lambdas are treated as their own functions for now, so we shouldn't
1933     // propagate counts into them.
1934   }
1935 
1936   void VisitPseudoObjectExpr(const PseudoObjectExpr *POE) {
1937     // Just visit syntatic expression as this is what users actually write.
1938     VisitStmt(POE->getSyntacticForm());
1939   }
1940 
1941   void VisitOpaqueValueExpr(const OpaqueValueExpr* OVE) {
1942     Visit(OVE->getSourceExpr());
1943   }
1944 };
1945 
1946 } // end anonymous namespace
1947 
1948 static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1949                  ArrayRef<CounterExpression> Expressions,
1950                  ArrayRef<CounterMappingRegion> Regions) {
1951   OS << FunctionName << ":\n";
1952   CounterMappingContext Ctx(Expressions);
1953   for (const auto &R : Regions) {
1954     OS.indent(2);
1955     switch (R.Kind) {
1956     case CounterMappingRegion::CodeRegion:
1957       break;
1958     case CounterMappingRegion::ExpansionRegion:
1959       OS << "Expansion,";
1960       break;
1961     case CounterMappingRegion::SkippedRegion:
1962       OS << "Skipped,";
1963       break;
1964     case CounterMappingRegion::GapRegion:
1965       OS << "Gap,";
1966       break;
1967     case CounterMappingRegion::BranchRegion:
1968     case CounterMappingRegion::MCDCBranchRegion:
1969       OS << "Branch,";
1970       break;
1971     case CounterMappingRegion::MCDCDecisionRegion:
1972       OS << "Decision,";
1973       break;
1974     }
1975 
1976     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1977        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1978 
1979     if (R.Kind == CounterMappingRegion::MCDCDecisionRegion) {
1980       OS << "M:" << R.MCDCParams.BitmapIdx;
1981       OS << ", C:" << R.MCDCParams.NumConditions;
1982     } else {
1983       Ctx.dump(R.Count, OS);
1984 
1985       if (R.Kind == CounterMappingRegion::BranchRegion ||
1986           R.Kind == CounterMappingRegion::MCDCBranchRegion) {
1987         OS << ", ";
1988         Ctx.dump(R.FalseCount, OS);
1989       }
1990     }
1991 
1992     if (R.Kind == CounterMappingRegion::MCDCBranchRegion) {
1993       OS << " [" << R.MCDCParams.ID << "," << R.MCDCParams.TrueID;
1994       OS << "," << R.MCDCParams.FalseID << "] ";
1995     }
1996 
1997     if (R.Kind == CounterMappingRegion::ExpansionRegion)
1998       OS << " (Expanded file = " << R.ExpandedFileID << ")";
1999     OS << "\n";
2000   }
2001 }
2002 
2003 CoverageMappingModuleGen::CoverageMappingModuleGen(
2004     CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
2005     : CGM(CGM), SourceInfo(SourceInfo) {}
2006 
2007 std::string CoverageMappingModuleGen::getCurrentDirname() {
2008   if (!CGM.getCodeGenOpts().CoverageCompilationDir.empty())
2009     return CGM.getCodeGenOpts().CoverageCompilationDir;
2010 
2011   SmallString<256> CWD;
2012   llvm::sys::fs::current_path(CWD);
2013   return CWD.str().str();
2014 }
2015 
2016 std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
2017   llvm::SmallString<256> Path(Filename);
2018   llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
2019 
2020   /// Traverse coverage prefix map in reverse order because prefix replacements
2021   /// are applied in reverse order starting from the last one when multiple
2022   /// prefix replacement options are provided.
2023   for (const auto &[From, To] :
2024        llvm::reverse(CGM.getCodeGenOpts().CoveragePrefixMap)) {
2025     if (llvm::sys::path::replace_path_prefix(Path, From, To))
2026       break;
2027   }
2028   return Path.str().str();
2029 }
2030 
2031 static std::string getInstrProfSection(const CodeGenModule &CGM,
2032                                        llvm::InstrProfSectKind SK) {
2033   return llvm::getInstrProfSectionName(
2034       SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
2035 }
2036 
2037 void CoverageMappingModuleGen::emitFunctionMappingRecord(
2038     const FunctionInfo &Info, uint64_t FilenamesRef) {
2039   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
2040 
2041   // Assign a name to the function record. This is used to merge duplicates.
2042   std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
2043 
2044   // A dummy description for a function included-but-not-used in a TU can be
2045   // replaced by full description provided by a different TU. The two kinds of
2046   // descriptions play distinct roles: therefore, assign them different names
2047   // to prevent `linkonce_odr` merging.
2048   if (Info.IsUsed)
2049     FuncRecordName += "u";
2050 
2051   // Create the function record type.
2052   const uint64_t NameHash = Info.NameHash;
2053   const uint64_t FuncHash = Info.FuncHash;
2054   const std::string &CoverageMapping = Info.CoverageMapping;
2055 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
2056   llvm::Type *FunctionRecordTypes[] = {
2057 #include "llvm/ProfileData/InstrProfData.inc"
2058   };
2059   auto *FunctionRecordTy =
2060       llvm::StructType::get(Ctx, ArrayRef(FunctionRecordTypes),
2061                             /*isPacked=*/true);
2062 
2063   // Create the function record constant.
2064 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
2065   llvm::Constant *FunctionRecordVals[] = {
2066       #include "llvm/ProfileData/InstrProfData.inc"
2067   };
2068   auto *FuncRecordConstant =
2069       llvm::ConstantStruct::get(FunctionRecordTy, ArrayRef(FunctionRecordVals));
2070 
2071   // Create the function record global.
2072   auto *FuncRecord = new llvm::GlobalVariable(
2073       CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
2074       llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
2075       FuncRecordName);
2076   FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
2077   FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
2078   FuncRecord->setAlignment(llvm::Align(8));
2079   if (CGM.supportsCOMDAT())
2080     FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
2081 
2082   // Make sure the data doesn't get deleted.
2083   CGM.addUsedGlobal(FuncRecord);
2084 }
2085 
2086 void CoverageMappingModuleGen::addFunctionMappingRecord(
2087     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
2088     const std::string &CoverageMapping, bool IsUsed) {
2089   const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
2090   FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
2091 
2092   if (!IsUsed)
2093     FunctionNames.push_back(NamePtr);
2094 
2095   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
2096     // Dump the coverage mapping data for this function by decoding the
2097     // encoded data. This allows us to dump the mapping regions which were
2098     // also processed by the CoverageMappingWriter which performs
2099     // additional minimization operations such as reducing the number of
2100     // expressions.
2101     llvm::SmallVector<std::string, 16> FilenameStrs;
2102     std::vector<StringRef> Filenames;
2103     std::vector<CounterExpression> Expressions;
2104     std::vector<CounterMappingRegion> Regions;
2105     FilenameStrs.resize(FileEntries.size() + 1);
2106     FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2107     for (const auto &Entry : FileEntries) {
2108       auto I = Entry.second;
2109       FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2110     }
2111     ArrayRef<std::string> FilenameRefs = llvm::ArrayRef(FilenameStrs);
2112     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
2113                                     Expressions, Regions);
2114     if (Reader.read())
2115       return;
2116     dump(llvm::outs(), NameValue, Expressions, Regions);
2117   }
2118 }
2119 
2120 void CoverageMappingModuleGen::emit() {
2121   if (FunctionRecords.empty())
2122     return;
2123   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
2124   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
2125 
2126   // Create the filenames and merge them with coverage mappings
2127   llvm::SmallVector<std::string, 16> FilenameStrs;
2128   FilenameStrs.resize(FileEntries.size() + 1);
2129   // The first filename is the current working directory.
2130   FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2131   for (const auto &Entry : FileEntries) {
2132     auto I = Entry.second;
2133     FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2134   }
2135 
2136   std::string Filenames;
2137   {
2138     llvm::raw_string_ostream OS(Filenames);
2139     CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
2140   }
2141   auto *FilenamesVal =
2142       llvm::ConstantDataArray::getString(Ctx, Filenames, false);
2143   const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
2144 
2145   // Emit the function records.
2146   for (const FunctionInfo &Info : FunctionRecords)
2147     emitFunctionMappingRecord(Info, FilenamesRef);
2148 
2149   const unsigned NRecords = 0;
2150   const size_t FilenamesSize = Filenames.size();
2151   const unsigned CoverageMappingSize = 0;
2152   llvm::Type *CovDataHeaderTypes[] = {
2153 #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
2154 #include "llvm/ProfileData/InstrProfData.inc"
2155   };
2156   auto CovDataHeaderTy =
2157       llvm::StructType::get(Ctx, ArrayRef(CovDataHeaderTypes));
2158   llvm::Constant *CovDataHeaderVals[] = {
2159 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
2160 #include "llvm/ProfileData/InstrProfData.inc"
2161   };
2162   auto CovDataHeaderVal =
2163       llvm::ConstantStruct::get(CovDataHeaderTy, ArrayRef(CovDataHeaderVals));
2164 
2165   // Create the coverage data record
2166   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
2167   auto CovDataTy = llvm::StructType::get(Ctx, ArrayRef(CovDataTypes));
2168   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
2169   auto CovDataVal = llvm::ConstantStruct::get(CovDataTy, ArrayRef(TUDataVals));
2170   auto CovData = new llvm::GlobalVariable(
2171       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
2172       CovDataVal, llvm::getCoverageMappingVarName());
2173 
2174   CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
2175   CovData->setAlignment(llvm::Align(8));
2176 
2177   // Make sure the data doesn't get deleted.
2178   CGM.addUsedGlobal(CovData);
2179   // Create the deferred function records array
2180   if (!FunctionNames.empty()) {
2181     auto NamesArrTy = llvm::ArrayType::get(llvm::PointerType::getUnqual(Ctx),
2182                                            FunctionNames.size());
2183     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
2184     // This variable will *NOT* be emitted to the object file. It is used
2185     // to pass the list of names referenced to codegen.
2186     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
2187                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
2188                              llvm::getCoverageUnusedNamesVarName());
2189   }
2190 }
2191 
2192 unsigned CoverageMappingModuleGen::getFileID(FileEntryRef File) {
2193   auto It = FileEntries.find(File);
2194   if (It != FileEntries.end())
2195     return It->second;
2196   unsigned FileID = FileEntries.size() + 1;
2197   FileEntries.insert(std::make_pair(File, FileID));
2198   return FileID;
2199 }
2200 
2201 void CoverageMappingGen::emitCounterMapping(const Decl *D,
2202                                             llvm::raw_ostream &OS) {
2203   assert(CounterMap && MCDCBitmapMap);
2204   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, *MCDCBitmapMap,
2205                                        *CondIDMap, SM, LangOpts);
2206   Walker.VisitDecl(D);
2207   Walker.write(OS);
2208 }
2209 
2210 void CoverageMappingGen::emitEmptyMapping(const Decl *D,
2211                                           llvm::raw_ostream &OS) {
2212   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
2213   Walker.VisitDecl(D);
2214   Walker.write(OS);
2215 }
2216