1ee02499aSAlex Lorenz //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2ee02499aSAlex Lorenz //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ee02499aSAlex Lorenz //
7ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
8ee02499aSAlex Lorenz //
9ee02499aSAlex Lorenz // Instrumentation-based code coverage mapping generator
10ee02499aSAlex Lorenz //
11ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
12ee02499aSAlex Lorenz 
13ee02499aSAlex Lorenz #include "CoverageMappingGen.h"
14ee02499aSAlex Lorenz #include "CodeGenFunction.h"
15ee02499aSAlex Lorenz #include "clang/AST/StmtVisitor.h"
16dd1ea9deSVedant Kumar #include "clang/Basic/Diagnostic.h"
17e08464fbSReid Kleckner #include "clang/Basic/FileManager.h"
18dd1ea9deSVedant Kumar #include "clang/Frontend/FrontendDiagnostic.h"
19ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h"
20e08464fbSReid Kleckner #include "llvm/ADT/Optional.h"
21bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h"
22ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h"
23b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h"
24b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
25b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
260d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h"
27ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h"
2814f8fb68SVedant Kumar #include "llvm/Support/Path.h"
29ee02499aSAlex Lorenz 
30dd1ea9deSVedant Kumar // This selects the coverage mapping format defined when `InstrProfData.inc`
31dd1ea9deSVedant Kumar // is textually included.
32dd1ea9deSVedant Kumar #define COVMAP_V3
33dd1ea9deSVedant Kumar 
349caa3fbeSZequan Wu static llvm::cl::opt<bool> EmptyLineCommentCoverage(
359caa3fbeSZequan Wu     "emptyline-comment-coverage",
369caa3fbeSZequan Wu     llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
379caa3fbeSZequan Wu                    "disable it on test)"),
389caa3fbeSZequan Wu     llvm::cl::init(true), llvm::cl::Hidden);
399caa3fbeSZequan Wu 
40ee02499aSAlex Lorenz using namespace clang;
41ee02499aSAlex Lorenz using namespace CodeGen;
42ee02499aSAlex Lorenz using namespace llvm::coverage;
43ee02499aSAlex Lorenz 
44b46176bbSZequan Wu CoverageSourceInfo *
45b46176bbSZequan Wu CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
469caa3fbeSZequan Wu   CoverageSourceInfo *CoverageInfo =
479caa3fbeSZequan Wu       new CoverageSourceInfo(PP.getSourceManager());
48b46176bbSZequan Wu   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
499caa3fbeSZequan Wu   if (EmptyLineCommentCoverage) {
50b46176bbSZequan Wu     PP.addCommentHandler(CoverageInfo);
519caa3fbeSZequan Wu     PP.setEmptylineHandler(CoverageInfo);
52b46176bbSZequan Wu     PP.setPreprocessToken(true);
53b46176bbSZequan Wu     PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
54b46176bbSZequan Wu       // Update previous token location.
55b46176bbSZequan Wu       CoverageInfo->PrevTokLoc = Tok.getLocation();
5684fffa67SZequan Wu       if (Tok.getKind() != clang::tok::eod)
57b46176bbSZequan Wu         CoverageInfo->updateNextTokLoc(Tok.getLocation());
58b46176bbSZequan Wu     });
599caa3fbeSZequan Wu   }
60b46176bbSZequan Wu   return CoverageInfo;
61b46176bbSZequan Wu }
62b46176bbSZequan Wu 
639caa3fbeSZequan Wu void CoverageSourceInfo::AddSkippedRange(SourceRange Range) {
649caa3fbeSZequan Wu   if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
659caa3fbeSZequan Wu       PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
669caa3fbeSZequan Wu       SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
679caa3fbeSZequan Wu                                     Range.getBegin()))
689caa3fbeSZequan Wu     SkippedRanges.back().Range.setEnd(Range.getEnd());
699caa3fbeSZequan Wu   else
709caa3fbeSZequan Wu     SkippedRanges.push_back({Range, PrevTokLoc});
719caa3fbeSZequan Wu }
729caa3fbeSZequan Wu 
733919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
749caa3fbeSZequan Wu   AddSkippedRange(Range);
759caa3fbeSZequan Wu }
769caa3fbeSZequan Wu 
779caa3fbeSZequan Wu void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
789caa3fbeSZequan Wu   AddSkippedRange(Range);
79b46176bbSZequan Wu }
80b46176bbSZequan Wu 
81b46176bbSZequan Wu bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
829caa3fbeSZequan Wu   AddSkippedRange(Range);
83b46176bbSZequan Wu   return false;
84b46176bbSZequan Wu }
85b46176bbSZequan Wu 
86b46176bbSZequan Wu void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
879caa3fbeSZequan Wu   if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
88b46176bbSZequan Wu     SkippedRanges.back().NextTokLoc = Loc;
89ee02499aSAlex Lorenz }
90ee02499aSAlex Lorenz 
91ee02499aSAlex Lorenz namespace {
92ee02499aSAlex Lorenz 
939fc8faf9SAdrian Prantl /// A region of source code that can be mapped to a counter.
9409c7179bSJustin Bogner class SourceMappingRegion {
959f2967bcSAlan Phipps   /// Primary Counter that is also used for Branch Regions for "True" branches.
96ee02499aSAlex Lorenz   Counter Count;
97ee02499aSAlex Lorenz 
989f2967bcSAlan Phipps   /// Secondary Counter used for Branch Regions for "False" branches.
999f2967bcSAlan Phipps   Optional<Counter> FalseCount;
1009f2967bcSAlan Phipps 
1019fc8faf9SAdrian Prantl   /// The region's starting location.
102bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
103ee02499aSAlex Lorenz 
1049fc8faf9SAdrian Prantl   /// The region's ending location.
105bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
106ee02499aSAlex Lorenz 
107a1c4deb7SVedant Kumar   /// Whether this region is a gap region. The count from a gap region is set
108a1c4deb7SVedant Kumar   /// as the line execution count if there are no other regions on the line.
109a1c4deb7SVedant Kumar   bool GapRegion;
110a1c4deb7SVedant Kumar 
11109c7179bSJustin Bogner public:
112bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
113*9783e209SZequan Wu                       Optional<SourceLocation> LocEnd, bool GapRegion = false)
114*9783e209SZequan Wu       : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) {
115*9783e209SZequan Wu   }
116ee02499aSAlex Lorenz 
1179f2967bcSAlan Phipps   SourceMappingRegion(Counter Count, Optional<Counter> FalseCount,
1189f2967bcSAlan Phipps                       Optional<SourceLocation> LocStart,
119*9783e209SZequan Wu                       Optional<SourceLocation> LocEnd, bool GapRegion = false)
1209f2967bcSAlan Phipps       : Count(Count), FalseCount(FalseCount), LocStart(LocStart),
121*9783e209SZequan Wu         LocEnd(LocEnd), GapRegion(GapRegion) {}
1229f2967bcSAlan Phipps 
12309c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
12409c7179bSJustin Bogner 
1259f2967bcSAlan Phipps   const Counter &getFalseCounter() const {
1269f2967bcSAlan Phipps     assert(FalseCount && "Region has no alternate counter");
1279f2967bcSAlan Phipps     return *FalseCount;
1289f2967bcSAlan Phipps   }
1299f2967bcSAlan Phipps 
130bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
13109c7179bSJustin Bogner 
132bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
133bf42cfd7SJustin Bogner 
134bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
135bf42cfd7SJustin Bogner 
1363cffc4c7SStephen Kelly   SourceLocation getBeginLoc() const {
137bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
138bf42cfd7SJustin Bogner     return *LocStart;
13909c7179bSJustin Bogner   }
14009c7179bSJustin Bogner 
141bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
142ee02499aSAlex Lorenz 
143a14a1f92SVedant Kumar   void setEndLoc(SourceLocation Loc) {
144a14a1f92SVedant Kumar     assert(Loc.isValid() && "Setting an invalid end location");
145a14a1f92SVedant Kumar     LocEnd = Loc;
146a14a1f92SVedant Kumar   }
147ee02499aSAlex Lorenz 
148462c77b4SCraig Topper   SourceLocation getEndLoc() const {
149bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
150bf42cfd7SJustin Bogner     return *LocEnd;
151ee02499aSAlex Lorenz   }
152747b0e29SVedant Kumar 
153a1c4deb7SVedant Kumar   bool isGap() const { return GapRegion; }
154a1c4deb7SVedant Kumar 
155a1c4deb7SVedant Kumar   void setGap(bool Gap) { GapRegion = Gap; }
1569f2967bcSAlan Phipps 
1579f2967bcSAlan Phipps   bool isBranch() const { return FalseCount.hasValue(); }
158ee02499aSAlex Lorenz };
159ee02499aSAlex Lorenz 
160d7369648SVedant Kumar /// Spelling locations for the start and end of a source region.
161d7369648SVedant Kumar struct SpellingRegion {
162d7369648SVedant Kumar   /// The line where the region starts.
163d7369648SVedant Kumar   unsigned LineStart;
164d7369648SVedant Kumar 
165d7369648SVedant Kumar   /// The column where the region starts.
166d7369648SVedant Kumar   unsigned ColumnStart;
167d7369648SVedant Kumar 
168d7369648SVedant Kumar   /// The line where the region ends.
169d7369648SVedant Kumar   unsigned LineEnd;
170d7369648SVedant Kumar 
171d7369648SVedant Kumar   /// The column where the region ends.
172d7369648SVedant Kumar   unsigned ColumnEnd;
173d7369648SVedant Kumar 
174d7369648SVedant Kumar   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
175d7369648SVedant Kumar                  SourceLocation LocEnd) {
176d7369648SVedant Kumar     LineStart = SM.getSpellingLineNumber(LocStart);
177d7369648SVedant Kumar     ColumnStart = SM.getSpellingColumnNumber(LocStart);
178d7369648SVedant Kumar     LineEnd = SM.getSpellingLineNumber(LocEnd);
179d7369648SVedant Kumar     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
180d7369648SVedant Kumar   }
181d7369648SVedant Kumar 
182fa8fa044SVedant Kumar   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
183a6e4358fSStephen Kelly       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
184fa8fa044SVedant Kumar 
185d7369648SVedant Kumar   /// Check if the start and end locations appear in source order, i.e
186d7369648SVedant Kumar   /// top->bottom, left->right.
187d7369648SVedant Kumar   bool isInSourceOrder() const {
188d7369648SVedant Kumar     return (LineStart < LineEnd) ||
189d7369648SVedant Kumar            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
190d7369648SVedant Kumar   }
191d7369648SVedant Kumar };
192d7369648SVedant Kumar 
1939fc8faf9SAdrian Prantl /// Provides the common functionality for the different
194ee02499aSAlex Lorenz /// coverage mapping region builders.
195ee02499aSAlex Lorenz class CoverageMappingBuilder {
196ee02499aSAlex Lorenz public:
197ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
198ee02499aSAlex Lorenz   SourceManager &SM;
199ee02499aSAlex Lorenz   const LangOptions &LangOpts;
200ee02499aSAlex Lorenz 
201ee02499aSAlex Lorenz private:
2029fc8faf9SAdrian Prantl   /// Map of clang's FileIDs to IDs used for coverage mapping.
203bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
204bf42cfd7SJustin Bogner       FileIDMapping;
205ee02499aSAlex Lorenz 
206ee02499aSAlex Lorenz public:
2079fc8faf9SAdrian Prantl   /// The coverage mapping regions for this function
208ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
2099fc8faf9SAdrian Prantl   /// The source mapping regions for this function.
210f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
211ee02499aSAlex Lorenz 
2129fc8faf9SAdrian Prantl   /// A set of regions which can be used as a filter.
213fc05ee34SIgor Kudrin   ///
214fc05ee34SIgor Kudrin   /// It is produced by emitExpansionRegions() and is used in
215fc05ee34SIgor Kudrin   /// emitSourceRegions() to suppress producing code regions if
216fc05ee34SIgor Kudrin   /// the same area is covered by expansion regions.
217fc05ee34SIgor Kudrin   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
218fc05ee34SIgor Kudrin       SourceRegionFilter;
219fc05ee34SIgor Kudrin 
220ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
221ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
222bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
223ee02499aSAlex Lorenz 
2249fc8faf9SAdrian Prantl   /// Return the precise end location for the given token.
225ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
226bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
227bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
228bf42cfd7SJustin Bogner     unsigned TokLen =
229bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
230bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
231ee02499aSAlex Lorenz   }
232ee02499aSAlex Lorenz 
2339fc8faf9SAdrian Prantl   /// Return the start location of an included file or expanded macro.
234bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
235bf42cfd7SJustin Bogner     if (Loc.isMacroID())
236bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
237bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
238ee02499aSAlex Lorenz   }
239ee02499aSAlex Lorenz 
2409fc8faf9SAdrian Prantl   /// Return the end location of an included file or expanded macro.
241bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
242bf42cfd7SJustin Bogner     if (Loc.isMacroID())
243bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
244f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
245bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
246bf42cfd7SJustin Bogner   }
247ee02499aSAlex Lorenz 
2489fc8faf9SAdrian Prantl   /// Find out where the current file is included or macro is expanded.
249bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
250b5f8171aSRichard Smith     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
251bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
252bf42cfd7SJustin Bogner   }
253bf42cfd7SJustin Bogner 
2549fc8faf9SAdrian Prantl   /// Return true if \c Loc is a location in a built-in macro.
255682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
25699d1b295SMehdi Amini     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
257682bfbf3SJustin Bogner   }
258682bfbf3SJustin Bogner 
2599fc8faf9SAdrian Prantl   /// Check whether \c Loc is included or expanded from \c Parent.
260d9e1a61dSIgor Kudrin   bool isNestedIn(SourceLocation Loc, FileID Parent) {
261d9e1a61dSIgor Kudrin     do {
262d9e1a61dSIgor Kudrin       Loc = getIncludeOrExpansionLoc(Loc);
263d9e1a61dSIgor Kudrin       if (Loc.isInvalid())
264d9e1a61dSIgor Kudrin         return false;
265d9e1a61dSIgor Kudrin     } while (!SM.isInFileID(Loc, Parent));
266d9e1a61dSIgor Kudrin     return true;
267d9e1a61dSIgor Kudrin   }
268d9e1a61dSIgor Kudrin 
2699fc8faf9SAdrian Prantl   /// Get the start of \c S ignoring macro arguments and builtin macros.
270bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
271f2ceec48SStephen Kelly     SourceLocation Loc = S->getBeginLoc();
272682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
273b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
274bf42cfd7SJustin Bogner     return Loc;
275bf42cfd7SJustin Bogner   }
276bf42cfd7SJustin Bogner 
2779fc8faf9SAdrian Prantl   /// Get the end of \c S ignoring macro arguments and builtin macros.
278bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
2791c301dcbSStephen Kelly     SourceLocation Loc = S->getEndLoc();
280682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
281b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
282f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
283bf42cfd7SJustin Bogner   }
284bf42cfd7SJustin Bogner 
2859fc8faf9SAdrian Prantl   /// Find the set of files we have regions for and assign IDs
286bf42cfd7SJustin Bogner   ///
287bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
288bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
289bf42cfd7SJustin Bogner   /// expansion regions.
290bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
291bf42cfd7SJustin Bogner     FileIDMapping.clear();
292bf42cfd7SJustin Bogner 
293bc6b80a0SVedant Kumar     llvm::SmallSet<FileID, 8> Visited;
294bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
295bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
296a6e4358fSStephen Kelly       SourceLocation Loc = Region.getBeginLoc();
297bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
298bc6b80a0SVedant Kumar       if (!Visited.insert(File).second)
299bf42cfd7SJustin Bogner         continue;
300bf42cfd7SJustin Bogner 
30193205af0SVedant Kumar       // Do not map FileID's associated with system headers.
30293205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
30393205af0SVedant Kumar         continue;
30493205af0SVedant Kumar 
305bf42cfd7SJustin Bogner       unsigned Depth = 0;
306bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
307ed1fe5d0SYaron Keren            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
308bf42cfd7SJustin Bogner         ++Depth;
309bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
310bf42cfd7SJustin Bogner     }
311899d1392SFangrui Song     llvm::stable_sort(FileLocs, llvm::less_second());
312bf42cfd7SJustin Bogner 
313bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
314bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
315bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
316ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
317ee02499aSAlex Lorenz       if (!Entry)
318bf42cfd7SJustin Bogner         continue;
319ee02499aSAlex Lorenz 
320bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
321bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
322bf42cfd7SJustin Bogner     }
323ee02499aSAlex Lorenz   }
324ee02499aSAlex Lorenz 
3259fc8faf9SAdrian Prantl   /// Get the coverage mapping file ID for \c Loc.
326bf42cfd7SJustin Bogner   ///
327bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
328bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
329bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
330bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
331bf42cfd7SJustin Bogner       return Mapping->second.first;
332903678caSJustin Bogner     return None;
333ee02499aSAlex Lorenz   }
334ee02499aSAlex Lorenz 
335b46176bbSZequan Wu   /// This shrinks the skipped range if it spans a line that contains a
336b46176bbSZequan Wu   /// non-comment token. If shrinking the skipped range would make it empty,
337b46176bbSZequan Wu   /// this returns None.
338b46176bbSZequan Wu   Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
33984fffa67SZequan Wu                                               SourceLocation LocStart,
34084fffa67SZequan Wu                                               SourceLocation LocEnd,
341b46176bbSZequan Wu                                               SourceLocation PrevTokLoc,
342b46176bbSZequan Wu                                               SourceLocation NextTokLoc) {
34384fffa67SZequan Wu     SpellingRegion SR{SM, LocStart, LocEnd};
3449caa3fbeSZequan Wu     SR.ColumnStart = 1;
3459caa3fbeSZequan Wu     if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
3469caa3fbeSZequan Wu         SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
3479caa3fbeSZequan Wu       SR.LineStart++;
3489caa3fbeSZequan Wu     if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
3499caa3fbeSZequan Wu         SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
3509caa3fbeSZequan Wu       SR.LineEnd--;
3519caa3fbeSZequan Wu       SR.ColumnEnd++;
3529caa3fbeSZequan Wu     }
3539caa3fbeSZequan Wu     if (SR.isInSourceOrder())
354b46176bbSZequan Wu       return SR;
355b46176bbSZequan Wu     return None;
356b46176bbSZequan Wu   }
357b46176bbSZequan Wu 
3589fc8faf9SAdrian Prantl   /// Gather all the regions that were skipped by the preprocessor
359b46176bbSZequan Wu   /// using the constructs like #if or comments.
360ee02499aSAlex Lorenz   void gatherSkippedRegions() {
361ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
362ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
363ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
364ee02499aSAlex Lorenz     FileLineRanges.resize(
365ee02499aSAlex Lorenz         FileIDMapping.size(),
366ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
367ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
368ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
369ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
370ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
371ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
372ee02499aSAlex Lorenz     }
373ee02499aSAlex Lorenz 
374ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
375b46176bbSZequan Wu     for (auto &I : SkippedRanges) {
376b46176bbSZequan Wu       SourceRange Range = I.Range;
377b46176bbSZequan Wu       auto LocStart = Range.getBegin();
378b46176bbSZequan Wu       auto LocEnd = Range.getEnd();
379bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
380bf42cfd7SJustin Bogner              "region spans multiple files");
381ee02499aSAlex Lorenz 
382bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
383903678caSJustin Bogner       if (!CovFileID)
384ee02499aSAlex Lorenz         continue;
38584fffa67SZequan Wu       Optional<SpellingRegion> SR =
38684fffa67SZequan Wu           adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc, I.NextTokLoc);
38784fffa67SZequan Wu       if (!SR.hasValue())
388b46176bbSZequan Wu         continue;
389fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
39084fffa67SZequan Wu           *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
39184fffa67SZequan Wu           SR->ColumnEnd);
392ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
3932a8c18d9SAlexander Kornienko       // the source code of this function.
394903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
395903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
396ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
397ee02499aSAlex Lorenz     }
398ee02499aSAlex Lorenz   }
399ee02499aSAlex Lorenz 
4009fc8faf9SAdrian Prantl   /// Generate the coverage counter mapping regions from collected
401ee02499aSAlex Lorenz   /// source regions.
402fc05ee34SIgor Kudrin   void emitSourceRegions(const SourceRegionFilter &Filter) {
403bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
404bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
405ee02499aSAlex Lorenz 
406a6e4358fSStephen Kelly       SourceLocation LocStart = Region.getBeginLoc();
4078b563665SYaron Keren       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
408f59329b0SJustin Bogner 
40993205af0SVedant Kumar       // Ignore regions from system headers.
41093205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
41193205af0SVedant Kumar         continue;
41293205af0SVedant Kumar 
413bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
414bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
415bf42cfd7SJustin Bogner       if (!CovFileID)
416ee02499aSAlex Lorenz         continue;
417ee02499aSAlex Lorenz 
418f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
419bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
420bf42cfd7SJustin Bogner              "region spans multiple files");
421bf42cfd7SJustin Bogner 
422fc05ee34SIgor Kudrin       // Don't add code regions for the area covered by expansion regions.
423fc05ee34SIgor Kudrin       // This not only suppresses redundant regions, but sometimes prevents
424fc05ee34SIgor Kudrin       // creating regions with wrong counters if, for example, a statement's
425fc05ee34SIgor Kudrin       // body ends at the end of a nested macro.
426fc05ee34SIgor Kudrin       if (Filter.count(std::make_pair(LocStart, LocEnd)))
427fc05ee34SIgor Kudrin         continue;
428fc05ee34SIgor Kudrin 
429d7369648SVedant Kumar       // Find the spelling locations for the mapping region.
430d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
431d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
432a1c4deb7SVedant Kumar 
433a1c4deb7SVedant Kumar       if (Region.isGap()) {
434a1c4deb7SVedant Kumar         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
435a1c4deb7SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
436a1c4deb7SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
4379f2967bcSAlan Phipps       } else if (Region.isBranch()) {
4389f2967bcSAlan Phipps         MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
4399f2967bcSAlan Phipps             Region.getCounter(), Region.getFalseCounter(), *CovFileID,
4409f2967bcSAlan Phipps             SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
441a1c4deb7SVedant Kumar       } else {
442bf42cfd7SJustin Bogner         MappingRegions.push_back(CounterMappingRegion::makeRegion(
443d7369648SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
444d7369648SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
445bf42cfd7SJustin Bogner       }
446bf42cfd7SJustin Bogner     }
447a1c4deb7SVedant Kumar   }
448bf42cfd7SJustin Bogner 
4499fc8faf9SAdrian Prantl   /// Generate expansion regions for each virtual file we've seen.
450fc05ee34SIgor Kudrin   SourceRegionFilter emitExpansionRegions() {
451fc05ee34SIgor Kudrin     SourceRegionFilter Filter;
452bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
453bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
454bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
455bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
456ee02499aSAlex Lorenz         continue;
457ee02499aSAlex Lorenz 
458bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
459bf42cfd7SJustin Bogner       if (!ParentFileID)
460bf42cfd7SJustin Bogner         continue;
461bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
462bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
463bf42cfd7SJustin Bogner 
464bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
465bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
466bf42cfd7SJustin Bogner              "region spans multiple files");
467fc05ee34SIgor Kudrin       Filter.insert(std::make_pair(ParentLoc, LocEnd));
468bf42cfd7SJustin Bogner 
469d7369648SVedant Kumar       SpellingRegion SR{SM, ParentLoc, LocEnd};
470d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
471bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
472d7369648SVedant Kumar           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
473d7369648SVedant Kumar           SR.LineEnd, SR.ColumnEnd));
474ee02499aSAlex Lorenz     }
475fc05ee34SIgor Kudrin     return Filter;
476ee02499aSAlex Lorenz   }
477ee02499aSAlex Lorenz };
478ee02499aSAlex Lorenz 
4799fc8faf9SAdrian Prantl /// Creates unreachable coverage regions for the functions that
480ee02499aSAlex Lorenz /// are not emitted.
481ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
482ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
483ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
484ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
485ee02499aSAlex Lorenz 
486ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
487ee02499aSAlex Lorenz     if (!D->hasBody())
488ee02499aSAlex Lorenz       return;
489ee02499aSAlex Lorenz     auto Body = D->getBody();
490d9e1a61dSIgor Kudrin     SourceLocation Start = getStart(Body);
491d9e1a61dSIgor Kudrin     SourceLocation End = getEnd(Body);
492d9e1a61dSIgor Kudrin     if (!SM.isWrittenInSameFile(Start, End)) {
493d9e1a61dSIgor Kudrin       // Walk up to find the common ancestor.
494d9e1a61dSIgor Kudrin       // Correct the locations accordingly.
495d9e1a61dSIgor Kudrin       FileID StartFileID = SM.getFileID(Start);
496d9e1a61dSIgor Kudrin       FileID EndFileID = SM.getFileID(End);
497d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
498d9e1a61dSIgor Kudrin         Start = getIncludeOrExpansionLoc(Start);
499d9e1a61dSIgor Kudrin         assert(Start.isValid() &&
500d9e1a61dSIgor Kudrin                "Declaration start location not nested within a known region");
501d9e1a61dSIgor Kudrin         StartFileID = SM.getFileID(Start);
502d9e1a61dSIgor Kudrin       }
503d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID) {
504d9e1a61dSIgor Kudrin         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
505d9e1a61dSIgor Kudrin         assert(End.isValid() &&
506d9e1a61dSIgor Kudrin                "Declaration end location not nested within a known region");
507d9e1a61dSIgor Kudrin         EndFileID = SM.getFileID(End);
508d9e1a61dSIgor Kudrin       }
509d9e1a61dSIgor Kudrin     }
510d9e1a61dSIgor Kudrin     SourceRegions.emplace_back(Counter(), Start, End);
511ee02499aSAlex Lorenz   }
512ee02499aSAlex Lorenz 
5139fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
514ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
515ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
516bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
517fc05ee34SIgor Kudrin     emitSourceRegions(SourceRegionFilter());
518ee02499aSAlex Lorenz 
519efd319a2SVedant Kumar     if (MappingRegions.empty())
520efd319a2SVedant Kumar       return;
521efd319a2SVedant Kumar 
5225fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
523ee02499aSAlex Lorenz     Writer.write(OS);
524ee02499aSAlex Lorenz   }
525ee02499aSAlex Lorenz };
526ee02499aSAlex Lorenz 
5279fc8faf9SAdrian Prantl /// A StmtVisitor that creates coverage mapping regions which map
528ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
529ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
530ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
531ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
5329fc8faf9SAdrian Prantl   /// The map of statements to count values.
533ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
534ee02499aSAlex Lorenz 
5359fc8faf9SAdrian Prantl   /// A stack of currently live regions.
536bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
537ee02499aSAlex Lorenz 
538ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
539ee02499aSAlex Lorenz 
5409fc8faf9SAdrian Prantl   /// A location in the most recently visited file or macro.
541bf42cfd7SJustin Bogner   ///
542bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
543bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
544bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
545bf42cfd7SJustin Bogner 
546*9783e209SZequan Wu   /// Whether the visitor at a terminate statement.
547*9783e209SZequan Wu   bool HasTerminateStmt = false;
548*9783e209SZequan Wu 
549*9783e209SZequan Wu   /// Gap region counter after terminate statement.
550*9783e209SZequan Wu   Counter GapRegionCounter;
5518046d22aSVedant Kumar 
5529fc8faf9SAdrian Prantl   /// Return a counter for the subtraction of \c RHS from \c LHS
553ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
554ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
555ee02499aSAlex Lorenz   }
556ee02499aSAlex Lorenz 
5579fc8faf9SAdrian Prantl   /// Return a counter for the sum of \c LHS and \c RHS.
558ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
559ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
560ee02499aSAlex Lorenz   }
561ee02499aSAlex Lorenz 
562bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
563bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
564bf42cfd7SJustin Bogner   }
565bf42cfd7SJustin Bogner 
5669fc8faf9SAdrian Prantl   /// Return the region counter for the given statement.
567bf42cfd7SJustin Bogner   ///
568ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
569bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
570bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
571ee02499aSAlex Lorenz   }
572ee02499aSAlex Lorenz 
5739fc8faf9SAdrian Prantl   /// Push a region onto the stack.
574bf42cfd7SJustin Bogner   ///
575bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
576bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
577bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
5789f2967bcSAlan Phipps                     Optional<SourceLocation> EndLoc = None,
5799f2967bcSAlan Phipps                     Optional<Counter> FalseCount = None) {
5809f2967bcSAlan Phipps 
5819f2967bcSAlan Phipps     if (StartLoc && !FalseCount.hasValue()) {
582bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
583747b0e29SVedant Kumar     }
5849f2967bcSAlan Phipps 
585*9783e209SZequan Wu     RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc);
586ee02499aSAlex Lorenz 
587bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
588ee02499aSAlex Lorenz   }
589ee02499aSAlex Lorenz 
5900c3e3115SVedant Kumar   size_t locationDepth(SourceLocation Loc) {
5910c3e3115SVedant Kumar     size_t Depth = 0;
5920c3e3115SVedant Kumar     while (Loc.isValid()) {
5930c3e3115SVedant Kumar       Loc = getIncludeOrExpansionLoc(Loc);
5940c3e3115SVedant Kumar       Depth++;
5950c3e3115SVedant Kumar     }
5960c3e3115SVedant Kumar     return Depth;
5970c3e3115SVedant Kumar   }
5980c3e3115SVedant Kumar 
5999fc8faf9SAdrian Prantl   /// Pop regions from the stack into the function's list of regions.
600bf42cfd7SJustin Bogner   ///
601bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
602bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
603bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
604bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
605bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
606bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
607bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
608a6e4358fSStephen Kelly         SourceLocation StartLoc = Region.getBeginLoc();
609bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
610bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
611bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
6129f2967bcSAlan Phipps         bool isBranch = Region.isBranch();
6130c3e3115SVedant Kumar         size_t StartDepth = locationDepth(StartLoc);
6140c3e3115SVedant Kumar         size_t EndDepth = locationDepth(EndLoc);
615bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
6160c3e3115SVedant Kumar           bool UnnestStart = StartDepth >= EndDepth;
6170c3e3115SVedant Kumar           bool UnnestEnd = EndDepth >= StartDepth;
6180c3e3115SVedant Kumar           if (UnnestEnd) {
6199f2967bcSAlan Phipps             // The region ends in a nested file or macro expansion. If the
6209f2967bcSAlan Phipps             // region is not a branch region, create a separate region for each
6219f2967bcSAlan Phipps             // expansion, and for all regions, update the EndLoc. Branch
6229f2967bcSAlan Phipps             // regions should not be split in order to keep a straightforward
6239f2967bcSAlan Phipps             // correspondance between the region and its associated branch
6249f2967bcSAlan Phipps             // condition, even if the condition spans multiple depths.
625bf42cfd7SJustin Bogner             SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
626bf42cfd7SJustin Bogner             assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
627bf42cfd7SJustin Bogner 
6289f2967bcSAlan Phipps             if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
6299f2967bcSAlan Phipps               SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
6309f2967bcSAlan Phipps                                          EndLoc);
631bf42cfd7SJustin Bogner 
632f14b2078SJustin Bogner             EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
633dceaaadfSJustin Bogner             if (EndLoc.isInvalid())
6349f2967bcSAlan Phipps               llvm::report_fatal_error(
6359f2967bcSAlan Phipps                   "File exit not handled before popRegions");
6360c3e3115SVedant Kumar             EndDepth--;
637bf42cfd7SJustin Bogner           }
6380c3e3115SVedant Kumar           if (UnnestStart) {
6399f2967bcSAlan Phipps             // The region ends in a nested file or macro expansion. If the
6409f2967bcSAlan Phipps             // region is not a branch region, create a separate region for each
6419f2967bcSAlan Phipps             // expansion, and for all regions, update the StartLoc. Branch
6429f2967bcSAlan Phipps             // regions should not be split in order to keep a straightforward
6439f2967bcSAlan Phipps             // correspondance between the region and its associated branch
6449f2967bcSAlan Phipps             // condition, even if the condition spans multiple depths.
6450c3e3115SVedant Kumar             SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
6460c3e3115SVedant Kumar             assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
6470c3e3115SVedant Kumar 
6489f2967bcSAlan Phipps             if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
6499f2967bcSAlan Phipps               SourceRegions.emplace_back(Region.getCounter(), StartLoc,
6509f2967bcSAlan Phipps                                          NestedLoc);
6510c3e3115SVedant Kumar 
6520c3e3115SVedant Kumar             StartLoc = getIncludeOrExpansionLoc(StartLoc);
6530c3e3115SVedant Kumar             if (StartLoc.isInvalid())
6549f2967bcSAlan Phipps               llvm::report_fatal_error(
6559f2967bcSAlan Phipps                   "File exit not handled before popRegions");
6560c3e3115SVedant Kumar             StartDepth--;
6570c3e3115SVedant Kumar           }
6580c3e3115SVedant Kumar         }
6590c3e3115SVedant Kumar         Region.setStartLoc(StartLoc);
660bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
661bf42cfd7SJustin Bogner 
6629f2967bcSAlan Phipps         if (!isBranch) {
663bf42cfd7SJustin Bogner           MostRecentLocation = EndLoc;
6649f2967bcSAlan Phipps           // If this region happens to span an entire expansion, we need to
6659f2967bcSAlan Phipps           // make sure we don't overlap the parent region with it.
666bf42cfd7SJustin Bogner           if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
667bf42cfd7SJustin Bogner               EndLoc == getEndOfFileOrMacro(EndLoc))
668bf42cfd7SJustin Bogner             MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
6699f2967bcSAlan Phipps         }
670bf42cfd7SJustin Bogner 
671a6e4358fSStephen Kelly         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
672fa8fa044SVedant Kumar         assert(SpellingRegion(SM, Region).isInSourceOrder());
673f36a5c4aSCraig Topper         SourceRegions.push_back(Region);
674bf42cfd7SJustin Bogner         }
675bf42cfd7SJustin Bogner       RegionStack.pop_back();
676bf42cfd7SJustin Bogner     }
677ee02499aSAlex Lorenz   }
678ee02499aSAlex Lorenz 
6799fc8faf9SAdrian Prantl   /// Return the currently active region.
680bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
681bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
682bf42cfd7SJustin Bogner     return RegionStack.back();
683ee02499aSAlex Lorenz   }
684ee02499aSAlex Lorenz 
6857225a261SVedant Kumar   /// Propagate counts through the children of \p S if \p VisitChildren is true.
6867225a261SVedant Kumar   /// Otherwise, only emit a count for \p S itself.
6877225a261SVedant Kumar   Counter propagateCounts(Counter TopCount, const Stmt *S,
6887225a261SVedant Kumar                           bool VisitChildren = true) {
6897838696eSVedant Kumar     SourceLocation StartLoc = getStart(S);
6907838696eSVedant Kumar     SourceLocation EndLoc = getEnd(S);
6917838696eSVedant Kumar     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
6927225a261SVedant Kumar     if (VisitChildren)
693bf42cfd7SJustin Bogner       Visit(S);
694bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
695bf42cfd7SJustin Bogner     popRegions(Index);
69639f01975SVedant Kumar 
69739f01975SVedant Kumar     // The statement may be spanned by an expansion. Make sure we handle a file
69839f01975SVedant Kumar     // exit out of this expansion before moving to the next statement.
699f2ceec48SStephen Kelly     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
7007838696eSVedant Kumar       MostRecentLocation = EndLoc;
70139f01975SVedant Kumar 
702bf42cfd7SJustin Bogner     return ExitCount;
703ee02499aSAlex Lorenz   }
704ee02499aSAlex Lorenz 
7059f2967bcSAlan Phipps   /// Determine whether the given condition can be constant folded.
7069f2967bcSAlan Phipps   bool ConditionFoldsToBool(const Expr *Cond) {
7079f2967bcSAlan Phipps     Expr::EvalResult Result;
7089f2967bcSAlan Phipps     return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
7099f2967bcSAlan Phipps   }
7109f2967bcSAlan Phipps 
7119f2967bcSAlan Phipps   /// Create a Branch Region around an instrumentable condition for coverage
7129f2967bcSAlan Phipps   /// and add it to the function's SourceRegions.  A branch region tracks a
7139f2967bcSAlan Phipps   /// "True" counter and a "False" counter for boolean expressions that
7149f2967bcSAlan Phipps   /// result in the generation of a branch.
7159f2967bcSAlan Phipps   void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt) {
7169f2967bcSAlan Phipps     // Check for NULL conditions.
7179f2967bcSAlan Phipps     if (!C)
7189f2967bcSAlan Phipps       return;
7199f2967bcSAlan Phipps 
7209f2967bcSAlan Phipps     // Ensure we are an instrumentable condition (i.e. no "&&" or "||").  Push
7219f2967bcSAlan Phipps     // region onto RegionStack but immediately pop it (which adds it to the
7229f2967bcSAlan Phipps     // function's SourceRegions) because it doesn't apply to any other source
7239f2967bcSAlan Phipps     // code other than the Condition.
7249f2967bcSAlan Phipps     if (CodeGenFunction::isInstrumentedCondition(C)) {
7259f2967bcSAlan Phipps       // If a condition can fold to true or false, the corresponding branch
7269f2967bcSAlan Phipps       // will be removed.  Create a region with both counters hard-coded to
7279f2967bcSAlan Phipps       // zero. This allows us to visualize them in a special way.
7289f2967bcSAlan Phipps       // Alternatively, we can prevent any optimization done via
7299f2967bcSAlan Phipps       // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
7309f2967bcSAlan Phipps       // CodeGenFunction.c always returns false, but that is very heavy-handed.
7319f2967bcSAlan Phipps       if (ConditionFoldsToBool(C))
7329f2967bcSAlan Phipps         popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
7339f2967bcSAlan Phipps                               Counter::getZero()));
7349f2967bcSAlan Phipps       else
7359f2967bcSAlan Phipps         // Otherwise, create a region with the True counter and False counter.
7369f2967bcSAlan Phipps         popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt));
7379f2967bcSAlan Phipps     }
7389f2967bcSAlan Phipps   }
7399f2967bcSAlan Phipps 
7409f2967bcSAlan Phipps   /// Create a Branch Region around a SwitchCase for code coverage
7419f2967bcSAlan Phipps   /// and add it to the function's SourceRegions.
7429f2967bcSAlan Phipps   void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt,
7439f2967bcSAlan Phipps                               Counter FalseCnt) {
7449f2967bcSAlan Phipps     // Push region onto RegionStack but immediately pop it (which adds it to
7459f2967bcSAlan Phipps     // the function's SourceRegions) because it doesn't apply to any other
7469f2967bcSAlan Phipps     // source other than the SwitchCase.
7479f2967bcSAlan Phipps     popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
7489f2967bcSAlan Phipps   }
7499f2967bcSAlan Phipps 
7509fc8faf9SAdrian Prantl   /// Check whether a region with bounds \c StartLoc and \c EndLoc
7510a7c9d11SIgor Kudrin   /// is already added to \c SourceRegions.
7529f2967bcSAlan Phipps   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
7539f2967bcSAlan Phipps                             bool isBranch = false) {
7540a7c9d11SIgor Kudrin     return SourceRegions.rend() !=
7550a7c9d11SIgor Kudrin            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
7560a7c9d11SIgor Kudrin                         [&](const SourceMappingRegion &Region) {
757a6e4358fSStephen Kelly                           return Region.getBeginLoc() == StartLoc &&
7589f2967bcSAlan Phipps                                  Region.getEndLoc() == EndLoc &&
7599f2967bcSAlan Phipps                                  Region.isBranch() == isBranch;
7600a7c9d11SIgor Kudrin                         });
7610a7c9d11SIgor Kudrin   }
7620a7c9d11SIgor Kudrin 
7639fc8faf9SAdrian Prantl   /// Adjust the most recently visited location to \c EndLoc.
764bf42cfd7SJustin Bogner   ///
765bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
766bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
767bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
7680a7c9d11SIgor Kudrin     // The code region for a whole macro is created in handleFileExit() when
7690a7c9d11SIgor Kudrin     // it detects exiting of the virtual file of that macro. If we visited
7700a7c9d11SIgor Kudrin     // statements in non-source order, we might already have such a region
7710a7c9d11SIgor Kudrin     // added, for example, if a body of a loop is divided among multiple
7720a7c9d11SIgor Kudrin     // macros. Avoid adding duplicate regions in such case.
77396ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
7740a7c9d11SIgor Kudrin         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
7750a7c9d11SIgor Kudrin         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
7769f2967bcSAlan Phipps                              MostRecentLocation, getRegion().isBranch()))
777bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
778ee02499aSAlex Lorenz   }
779ee02499aSAlex Lorenz 
7809fc8faf9SAdrian Prantl   /// Adjust regions and state when \c NewLoc exits a file.
781bf42cfd7SJustin Bogner   ///
782bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
783bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
784bf42cfd7SJustin Bogner   /// for the exited file.
785bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
786e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
787e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
788bf42cfd7SJustin Bogner       return;
789bf42cfd7SJustin Bogner 
790bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
791bf42cfd7SJustin Bogner     // find the common ancestor.
792bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
793bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
794bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
795bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
796bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
797bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
798bf42cfd7SJustin Bogner         // to adjust our location to the new file.
799bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
800bf42cfd7SJustin Bogner         return;
801bf42cfd7SJustin Bogner       }
802bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
803ee02499aSAlex Lorenz     }
804ee02499aSAlex Lorenz 
805bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
806bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
80757d3f145SPete Cooper     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
80857d3f145SPete Cooper       if (!I.hasStartLoc())
809bf42cfd7SJustin Bogner         continue;
810a6e4358fSStephen Kelly       SourceLocation Loc = I.getBeginLoc();
811bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
81257d3f145SPete Cooper         ParentCounter = I.getCounter();
813bf42cfd7SJustin Bogner         break;
814ee02499aSAlex Lorenz       }
815bf42cfd7SJustin Bogner 
816bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
817bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
818bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
819bf42cfd7SJustin Bogner         // we've seen this region.
8209f2967bcSAlan Phipps         if (StartLocs.insert(Loc).second) {
8219f2967bcSAlan Phipps           if (I.isBranch())
8229f2967bcSAlan Phipps             SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(), Loc,
8239f2967bcSAlan Phipps                                        getEndOfFileOrMacro(Loc), I.isBranch());
8249f2967bcSAlan Phipps           else
82557d3f145SPete Cooper             SourceRegions.emplace_back(I.getCounter(), Loc,
826bf42cfd7SJustin Bogner                                        getEndOfFileOrMacro(Loc));
8279f2967bcSAlan Phipps         }
828bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
829ee02499aSAlex Lorenz       }
83057d3f145SPete Cooper       I.setStartLoc(getPreciseTokenLocEnd(Loc));
831bf42cfd7SJustin Bogner     }
832bf42cfd7SJustin Bogner 
833bf42cfd7SJustin Bogner     if (ParentCounter) {
834bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
835bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
836bf42cfd7SJustin Bogner       // corresponding to the parent.
837bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
838bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
839bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
840fa8fa044SVedant Kumar         if (StartLocs.insert(FileStart).second) {
841bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
842bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
843fa8fa044SVedant Kumar           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
844fa8fa044SVedant Kumar         }
845bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
846bf42cfd7SJustin Bogner       }
847bf42cfd7SJustin Bogner     }
848bf42cfd7SJustin Bogner 
849bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
850bf42cfd7SJustin Bogner   }
851bf42cfd7SJustin Bogner 
8529fc8faf9SAdrian Prantl   /// Ensure that \c S is included in the current region.
853bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
854bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
855bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
856bf42cfd7SJustin Bogner 
857bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
858bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
859bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
860bf42cfd7SJustin Bogner   }
861bf42cfd7SJustin Bogner 
8629fc8faf9SAdrian Prantl   /// Mark \c S as a terminator, starting a zero region.
863bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
864bf42cfd7SJustin Bogner     extendRegion(S);
865bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
8668046d22aSVedant Kumar     SourceLocation EndLoc = getEnd(S);
867bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
8688046d22aSVedant Kumar       Region.setEndLoc(EndLoc);
869bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
870*9783e209SZequan Wu     HasTerminateStmt = true;
871bf42cfd7SJustin Bogner   }
872ee02499aSAlex Lorenz 
873fa8fa044SVedant Kumar   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
874fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
875fa8fa044SVedant Kumar                                            SourceLocation BeforeLoc) {
876*9783e209SZequan Wu     // If AfterLoc is in function-like macro, use the right parenthesis
877*9783e209SZequan Wu     // location.
878*9783e209SZequan Wu     if (AfterLoc.isMacroID()) {
879*9783e209SZequan Wu       FileID FID = SM.getFileID(AfterLoc);
880*9783e209SZequan Wu       const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
881*9783e209SZequan Wu       if (EI->isFunctionMacroExpansion())
882*9783e209SZequan Wu         AfterLoc = EI->getExpansionLocEnd();
883*9783e209SZequan Wu     }
884*9783e209SZequan Wu 
885d83511ddSZequan Wu     size_t StartDepth = locationDepth(AfterLoc);
886d83511ddSZequan Wu     size_t EndDepth = locationDepth(BeforeLoc);
887d83511ddSZequan Wu     while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
888d83511ddSZequan Wu       bool UnnestStart = StartDepth >= EndDepth;
889d83511ddSZequan Wu       bool UnnestEnd = EndDepth >= StartDepth;
890d83511ddSZequan Wu       if (UnnestEnd) {
8914544a63bSSterling Augustine         assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
8924544a63bSSterling Augustine                                       BeforeLoc));
893d83511ddSZequan Wu 
894d83511ddSZequan Wu         BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
895d83511ddSZequan Wu         assert(BeforeLoc.isValid());
896d83511ddSZequan Wu         EndDepth--;
897d83511ddSZequan Wu       }
898d83511ddSZequan Wu       if (UnnestStart) {
899fc97a63dSSterling Augustine         assert(SM.isWrittenInSameFile(AfterLoc,
900fc97a63dSSterling Augustine                                       getEndOfFileOrMacro(AfterLoc)));
901d83511ddSZequan Wu 
902d83511ddSZequan Wu         AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
903d83511ddSZequan Wu         assert(AfterLoc.isValid());
904d83511ddSZequan Wu         AfterLoc = getPreciseTokenLocEnd(AfterLoc);
905d83511ddSZequan Wu         assert(AfterLoc.isValid());
906d83511ddSZequan Wu         StartDepth--;
907d83511ddSZequan Wu       }
908d83511ddSZequan Wu     }
909d83511ddSZequan Wu     AfterLoc = getPreciseTokenLocEnd(AfterLoc);
9109500a720SZequan Wu     // If the start and end locations of the gap are both within the same macro
9119500a720SZequan Wu     // file, the range may not be in source order.
9129500a720SZequan Wu     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
9139500a720SZequan Wu       return None;
914*9783e209SZequan Wu     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
915*9783e209SZequan Wu         !SpellingRegion(SM, AfterLoc, BeforeLoc).isInSourceOrder())
916fa8fa044SVedant Kumar       return None;
917fa8fa044SVedant Kumar     return {{AfterLoc, BeforeLoc}};
918fa8fa044SVedant Kumar   }
919fa8fa044SVedant Kumar 
9202e8c8759SVedant Kumar   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
9212e8c8759SVedant Kumar   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
9222e8c8759SVedant Kumar                             Counter Count) {
923fa8fa044SVedant Kumar     if (StartLoc == EndLoc)
9242e8c8759SVedant Kumar       return;
925fa8fa044SVedant Kumar     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
9262e8c8759SVedant Kumar     handleFileExit(StartLoc);
9272e8c8759SVedant Kumar     size_t Index = pushRegion(Count, StartLoc, EndLoc);
9282e8c8759SVedant Kumar     getRegion().setGap(true);
9292e8c8759SVedant Kumar     handleFileExit(EndLoc);
9302e8c8759SVedant Kumar     popRegions(Index);
9312e8c8759SVedant Kumar   }
9322e8c8759SVedant Kumar 
9339fc8faf9SAdrian Prantl   /// Keep counts of breaks and continues inside loops.
934ee02499aSAlex Lorenz   struct BreakContinue {
935ee02499aSAlex Lorenz     Counter BreakCount;
936ee02499aSAlex Lorenz     Counter ContinueCount;
937ee02499aSAlex Lorenz   };
938ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
939ee02499aSAlex Lorenz 
940ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
941ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
942e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
943ee02499aSAlex Lorenz       const LangOptions &LangOpts)
944*9783e209SZequan Wu       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
945ee02499aSAlex Lorenz 
9469fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
947ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
948ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
949bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
950fc05ee34SIgor Kudrin     SourceRegionFilter Filter = emitExpansionRegions();
951fc05ee34SIgor Kudrin     emitSourceRegions(Filter);
952ee02499aSAlex Lorenz     gatherSkippedRegions();
953ee02499aSAlex Lorenz 
954efd319a2SVedant Kumar     if (MappingRegions.empty())
955efd319a2SVedant Kumar       return;
956efd319a2SVedant Kumar 
9574da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
9584da909b2SJustin Bogner                                  MappingRegions);
959ee02499aSAlex Lorenz     Writer.write(OS);
960ee02499aSAlex Lorenz   }
961ee02499aSAlex Lorenz 
962ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
963f2ceec48SStephen Kelly     if (S->getBeginLoc().isValid())
964bf42cfd7SJustin Bogner       extendRegion(S);
965*9783e209SZequan Wu     const Stmt *LastStmt = nullptr;
966*9783e209SZequan Wu     bool SaveTerminateStmt = HasTerminateStmt;
967*9783e209SZequan Wu     HasTerminateStmt = false;
968*9783e209SZequan Wu     GapRegionCounter = Counter::getZero();
969642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
970*9783e209SZequan Wu       if (Child) {
971*9783e209SZequan Wu         // If last statement contains terminate statements, add a gap area
972*9783e209SZequan Wu         // between the two statements. Skipping attributed statements, because
973*9783e209SZequan Wu         // they don't have valid start location.
974*9783e209SZequan Wu         if (LastStmt && HasTerminateStmt && !dyn_cast<AttributedStmt>(Child)) {
975*9783e209SZequan Wu           auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
976*9783e209SZequan Wu           if (Gap)
977*9783e209SZequan Wu             fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
978*9783e209SZequan Wu                                  GapRegionCounter);
979*9783e209SZequan Wu           SaveTerminateStmt = true;
980*9783e209SZequan Wu           HasTerminateStmt = false;
981*9783e209SZequan Wu         }
982642f173aSBenjamin Kramer         this->Visit(Child);
983*9783e209SZequan Wu         LastStmt = Child;
984*9783e209SZequan Wu       }
985*9783e209SZequan Wu     if (SaveTerminateStmt)
986*9783e209SZequan Wu       HasTerminateStmt = true;
987bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
988ee02499aSAlex Lorenz   }
989ee02499aSAlex Lorenz 
990ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
991bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
992efd319a2SVedant Kumar 
993efd319a2SVedant Kumar     // Do not propagate region counts into system headers.
994efd319a2SVedant Kumar     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
995efd319a2SVedant Kumar       return;
996efd319a2SVedant Kumar 
9977225a261SVedant Kumar     // Do not visit the artificial children nodes of defaulted methods. The
9987225a261SVedant Kumar     // lexer may not be able to report back precise token end locations for
9997225a261SVedant Kumar     // these children nodes (llvm.org/PR39822), and moreover users will not be
10007225a261SVedant Kumar     // able to see coverage for them.
10017225a261SVedant Kumar     bool Defaulted = false;
10027225a261SVedant Kumar     if (auto *Method = dyn_cast<CXXMethodDecl>(D))
10037225a261SVedant Kumar       Defaulted = Method->isDefaulted();
10047225a261SVedant Kumar 
10057225a261SVedant Kumar     propagateCounts(getRegionCounter(Body), Body,
10067225a261SVedant Kumar                     /*VisitChildren=*/!Defaulted);
1007747b0e29SVedant Kumar     assert(RegionStack.empty() && "Regions entered but never exited");
1008341bf429SVedant Kumar   }
1009ee02499aSAlex Lorenz 
1010ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
1011bf42cfd7SJustin Bogner     extendRegion(S);
1012ee02499aSAlex Lorenz     if (S->getRetValue())
1013ee02499aSAlex Lorenz       Visit(S->getRetValue());
1014bf42cfd7SJustin Bogner     terminateRegion(S);
1015ee02499aSAlex Lorenz   }
1016ee02499aSAlex Lorenz 
1017565e37c7SXun Li   void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
1018565e37c7SXun Li     extendRegion(S);
1019565e37c7SXun Li     Visit(S->getBody());
1020565e37c7SXun Li   }
1021565e37c7SXun Li 
1022565e37c7SXun Li   void VisitCoreturnStmt(const CoreturnStmt *S) {
1023565e37c7SXun Li     extendRegion(S);
1024565e37c7SXun Li     if (S->getOperand())
1025565e37c7SXun Li       Visit(S->getOperand());
1026565e37c7SXun Li     terminateRegion(S);
1027565e37c7SXun Li   }
1028565e37c7SXun Li 
1029f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
1030f959febfSJustin Bogner     extendRegion(E);
1031f959febfSJustin Bogner     if (E->getSubExpr())
1032f959febfSJustin Bogner       Visit(E->getSubExpr());
1033f959febfSJustin Bogner     terminateRegion(E);
1034f959febfSJustin Bogner   }
1035f959febfSJustin Bogner 
1036bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
1037ee02499aSAlex Lorenz 
1038ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
10398046d22aSVedant Kumar     Counter LabelCount = getRegionCounter(S);
1040bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
1041bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
1042bf42cfd7SJustin Bogner     handleFileExit(Start);
10438046d22aSVedant Kumar     pushRegion(LabelCount, Start);
1044ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1045ee02499aSAlex Lorenz   }
1046ee02499aSAlex Lorenz 
1047ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
1048ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1049ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
1050bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
10517f53fbfcSEli Friedman     // FIXME: a break in a switch should terminate regions for all preceding
10527f53fbfcSEli Friedman     // case statements, not just the most recent one.
1053bf42cfd7SJustin Bogner     terminateRegion(S);
1054ee02499aSAlex Lorenz   }
1055ee02499aSAlex Lorenz 
1056ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
1057ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1058ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
1059bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1060bf42cfd7SJustin Bogner     terminateRegion(S);
1061ee02499aSAlex Lorenz   }
1062ee02499aSAlex Lorenz 
1063181dfe4cSEli Friedman   void VisitCallExpr(const CallExpr *E) {
1064181dfe4cSEli Friedman     VisitStmt(E);
1065181dfe4cSEli Friedman 
1066181dfe4cSEli Friedman     // Terminate the region when we hit a noreturn function.
1067181dfe4cSEli Friedman     // (This is helpful dealing with switch statements.)
1068181dfe4cSEli Friedman     QualType CalleeType = E->getCallee()->getType();
1069181dfe4cSEli Friedman     if (getFunctionExtInfo(*CalleeType).getNoReturn())
1070181dfe4cSEli Friedman       terminateRegion(E);
1071181dfe4cSEli Friedman   }
1072181dfe4cSEli Friedman 
1073ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
1074bf42cfd7SJustin Bogner     extendRegion(S);
1075ee02499aSAlex Lorenz 
1076bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1077bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1078bf42cfd7SJustin Bogner 
1079bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
1080bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
1081bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1082bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1083ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1084bf42cfd7SJustin Bogner 
1085*9783e209SZequan Wu     bool BodyHasTerminateStmt = HasTerminateStmt;
1086*9783e209SZequan Wu     HasTerminateStmt = false;
1087*9783e209SZequan Wu 
1088bf42cfd7SJustin Bogner     // Go back to handle the condition.
1089bf42cfd7SJustin Bogner     Counter CondCount =
1090bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1091bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
1092bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
1093bf42cfd7SJustin Bogner 
1094fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
1095d83511ddSZequan Wu     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1096fa8fa044SVedant Kumar     if (Gap)
1097fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1098fa8fa044SVedant Kumar 
1099bf42cfd7SJustin Bogner     Counter OutCount =
1100bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1101*9783e209SZequan Wu     if (OutCount != ParentCount) {
1102bf42cfd7SJustin Bogner       pushRegion(OutCount);
1103*9783e209SZequan Wu       GapRegionCounter = OutCount;
1104*9783e209SZequan Wu       if (BodyHasTerminateStmt)
1105*9783e209SZequan Wu         HasTerminateStmt = true;
1106*9783e209SZequan Wu     }
11079f2967bcSAlan Phipps 
11089f2967bcSAlan Phipps     // Create Branch Region around condition.
11099f2967bcSAlan Phipps     createBranchRegion(S->getCond(), BodyCount,
11109f2967bcSAlan Phipps                        subtractCounters(CondCount, BodyCount));
1111ee02499aSAlex Lorenz   }
1112ee02499aSAlex Lorenz 
1113ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
1114bf42cfd7SJustin Bogner     extendRegion(S);
1115ee02499aSAlex Lorenz 
1116bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1117bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1118bf42cfd7SJustin Bogner 
1119bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
1120bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1121bf42cfd7SJustin Bogner     Counter BackedgeCount =
1122bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1123ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1124bf42cfd7SJustin Bogner 
1125*9783e209SZequan Wu     bool BodyHasTerminateStmt = HasTerminateStmt;
1126*9783e209SZequan Wu     HasTerminateStmt = false;
1127*9783e209SZequan Wu 
1128bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1129bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
1130bf42cfd7SJustin Bogner 
1131bf42cfd7SJustin Bogner     Counter OutCount =
1132bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1133*9783e209SZequan Wu     if (OutCount != ParentCount) {
1134bf42cfd7SJustin Bogner       pushRegion(OutCount);
1135*9783e209SZequan Wu       GapRegionCounter = OutCount;
1136*9783e209SZequan Wu     }
11379f2967bcSAlan Phipps 
11389f2967bcSAlan Phipps     // Create Branch Region around condition.
11399f2967bcSAlan Phipps     createBranchRegion(S->getCond(), BodyCount,
11409f2967bcSAlan Phipps                        subtractCounters(CondCount, BodyCount));
1141*9783e209SZequan Wu 
1142*9783e209SZequan Wu     if (BodyHasTerminateStmt)
1143*9783e209SZequan Wu       HasTerminateStmt = true;
1144ee02499aSAlex Lorenz   }
1145ee02499aSAlex Lorenz 
1146ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
1147bf42cfd7SJustin Bogner     extendRegion(S);
1148ee02499aSAlex Lorenz     if (S->getInit())
1149ee02499aSAlex Lorenz       Visit(S->getInit());
1150ee02499aSAlex Lorenz 
1151bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1152bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1153bf42cfd7SJustin Bogner 
11543e2ae49aSVedant Kumar     // The loop increment may contain a break or continue.
11553e2ae49aSVedant Kumar     if (S->getInc())
11563e2ae49aSVedant Kumar       BreakContinueStack.emplace_back();
11573e2ae49aSVedant Kumar 
1158bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
11593e2ae49aSVedant Kumar     BreakContinueStack.emplace_back();
1160bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1161bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
11623e2ae49aSVedant Kumar     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1163ee02499aSAlex Lorenz 
1164*9783e209SZequan Wu     bool BodyHasTerminateStmt = HasTerminateStmt;
1165*9783e209SZequan Wu     HasTerminateStmt = false;
1166*9783e209SZequan Wu 
1167ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
1168ee02499aSAlex Lorenz     // the count for all the continue statements.
11693e2ae49aSVedant Kumar     BreakContinue IncrementBC;
11703e2ae49aSVedant Kumar     if (const Stmt *Inc = S->getInc()) {
11713e2ae49aSVedant Kumar       propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
11723e2ae49aSVedant Kumar       IncrementBC = BreakContinueStack.pop_back_val();
11733e2ae49aSVedant Kumar     }
1174bf42cfd7SJustin Bogner 
1175bf42cfd7SJustin Bogner     // Go back to handle the condition.
11763e2ae49aSVedant Kumar     Counter CondCount = addCounters(
11773e2ae49aSVedant Kumar         addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
11783e2ae49aSVedant Kumar         IncrementBC.ContinueCount);
1179bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
1180bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
1181bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
1182ee02499aSAlex Lorenz     }
1183ee02499aSAlex Lorenz 
1184fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
1185d83511ddSZequan Wu     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1186fa8fa044SVedant Kumar     if (Gap)
1187fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1188fa8fa044SVedant Kumar 
11893e2ae49aSVedant Kumar     Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
11903e2ae49aSVedant Kumar                                    subtractCounters(CondCount, BodyCount));
1191*9783e209SZequan Wu     if (OutCount != ParentCount) {
1192bf42cfd7SJustin Bogner       pushRegion(OutCount);
1193*9783e209SZequan Wu       GapRegionCounter = OutCount;
1194*9783e209SZequan Wu       if (BodyHasTerminateStmt)
1195*9783e209SZequan Wu         HasTerminateStmt = true;
1196*9783e209SZequan Wu     }
11979f2967bcSAlan Phipps 
11989f2967bcSAlan Phipps     // Create Branch Region around condition.
11999f2967bcSAlan Phipps     createBranchRegion(S->getCond(), BodyCount,
12009f2967bcSAlan Phipps                        subtractCounters(CondCount, BodyCount));
1201ee02499aSAlex Lorenz   }
1202ee02499aSAlex Lorenz 
1203ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1204bf42cfd7SJustin Bogner     extendRegion(S);
12058baa5001SRichard Smith     if (S->getInit())
12068baa5001SRichard Smith       Visit(S->getInit());
1207bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
1208ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
1209bf42cfd7SJustin Bogner 
1210bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1211bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1212bf42cfd7SJustin Bogner 
1213ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1214bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1215bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1216ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1217bf42cfd7SJustin Bogner 
1218*9783e209SZequan Wu     bool BodyHasTerminateStmt = HasTerminateStmt;
1219*9783e209SZequan Wu     HasTerminateStmt = false;
1220*9783e209SZequan Wu 
1221fa8fa044SVedant Kumar     // The body count applies to the area immediately after the range.
1222d83511ddSZequan Wu     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1223fa8fa044SVedant Kumar     if (Gap)
1224fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1225fa8fa044SVedant Kumar 
12261587432dSJustin Bogner     Counter LoopCount =
12271587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
12281587432dSJustin Bogner     Counter OutCount =
12291587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1230*9783e209SZequan Wu     if (OutCount != ParentCount) {
1231bf42cfd7SJustin Bogner       pushRegion(OutCount);
1232*9783e209SZequan Wu       GapRegionCounter = OutCount;
1233*9783e209SZequan Wu       if (BodyHasTerminateStmt)
1234*9783e209SZequan Wu         HasTerminateStmt = true;
1235*9783e209SZequan Wu     }
12369f2967bcSAlan Phipps 
12379f2967bcSAlan Phipps     // Create Branch Region around condition.
12389f2967bcSAlan Phipps     createBranchRegion(S->getCond(), BodyCount,
12399f2967bcSAlan Phipps                        subtractCounters(LoopCount, BodyCount));
1240ee02499aSAlex Lorenz   }
1241ee02499aSAlex Lorenz 
1242ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1243bf42cfd7SJustin Bogner     extendRegion(S);
1244ee02499aSAlex Lorenz     Visit(S->getElement());
1245bf42cfd7SJustin Bogner 
1246bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1247bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1248bf42cfd7SJustin Bogner 
1249ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1250bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1251bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1252ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1253bf42cfd7SJustin Bogner 
1254fa8fa044SVedant Kumar     // The body count applies to the area immediately after the collection.
1255d83511ddSZequan Wu     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1256fa8fa044SVedant Kumar     if (Gap)
1257fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1258fa8fa044SVedant Kumar 
12591587432dSJustin Bogner     Counter LoopCount =
12601587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
12611587432dSJustin Bogner     Counter OutCount =
12621587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1263*9783e209SZequan Wu     if (OutCount != ParentCount) {
1264bf42cfd7SJustin Bogner       pushRegion(OutCount);
1265*9783e209SZequan Wu       GapRegionCounter = OutCount;
1266*9783e209SZequan Wu     }
1267ee02499aSAlex Lorenz   }
1268ee02499aSAlex Lorenz 
1269ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
1270bf42cfd7SJustin Bogner     extendRegion(S);
1271f2a6ec55SVedant Kumar     if (S->getInit())
1272f2a6ec55SVedant Kumar       Visit(S->getInit());
1273ee02499aSAlex Lorenz     Visit(S->getCond());
1274bf42cfd7SJustin Bogner 
1275ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1276bf42cfd7SJustin Bogner 
1277bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
1278bf42cfd7SJustin Bogner     extendRegion(Body);
1279bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1280bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
12817f53fbfcSEli Friedman         // Make a region for the body of the switch.  If the body starts with
12827f53fbfcSEli Friedman         // a case, that case will reuse this region; otherwise, this covers
12837f53fbfcSEli Friedman         // the unreachable code at the beginning of the switch body.
1284859bf4d2SVedant Kumar         size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1285859bf4d2SVedant Kumar         getRegion().setGap(true);
1286*9783e209SZequan Wu         Visit(Body);
12877f53fbfcSEli Friedman 
12887f53fbfcSEli Friedman         // Set the end for the body of the switch, if it isn't already set.
12897f53fbfcSEli Friedman         for (size_t i = RegionStack.size(); i != Index; --i) {
12907f53fbfcSEli Friedman           if (!RegionStack[i - 1].hasEndLoc())
12917f53fbfcSEli Friedman             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
12927f53fbfcSEli Friedman         }
12937f53fbfcSEli Friedman 
1294bf42cfd7SJustin Bogner         popRegions(Index);
1295ee02499aSAlex Lorenz       }
129687ea3b05SVedant Kumar     } else
1297bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
1298ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1299bf42cfd7SJustin Bogner 
1300ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
1301ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
1302ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1303bf42cfd7SJustin Bogner 
13049f2967bcSAlan Phipps     Counter ParentCount = getRegion().getCounter();
1305bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
13063836482aSVedant Kumar     SourceLocation ExitLoc = getEnd(S);
130708780529SAlex Lorenz     pushRegion(ExitCount);
1308*9783e209SZequan Wu     GapRegionCounter = ExitCount;
130908780529SAlex Lorenz 
131008780529SAlex Lorenz     // Ensure that handleFileExit recognizes when the end location is located
131108780529SAlex Lorenz     // in a different file.
131208780529SAlex Lorenz     MostRecentLocation = getStart(S);
13133836482aSVedant Kumar     handleFileExit(ExitLoc);
13149f2967bcSAlan Phipps 
13159f2967bcSAlan Phipps     // Create a Branch Region around each Case. Subtract the case's
13169f2967bcSAlan Phipps     // counter from the Parent counter to track the "False" branch count.
13179f2967bcSAlan Phipps     Counter CaseCountSum;
13189f2967bcSAlan Phipps     bool HasDefaultCase = false;
13199f2967bcSAlan Phipps     const SwitchCase *Case = S->getSwitchCaseList();
13209f2967bcSAlan Phipps     for (; Case; Case = Case->getNextSwitchCase()) {
13219f2967bcSAlan Phipps       HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
13229f2967bcSAlan Phipps       CaseCountSum = addCounters(CaseCountSum, getRegionCounter(Case));
13239f2967bcSAlan Phipps       createSwitchCaseRegion(
13249f2967bcSAlan Phipps           Case, getRegionCounter(Case),
13259f2967bcSAlan Phipps           subtractCounters(ParentCount, getRegionCounter(Case)));
13269f2967bcSAlan Phipps     }
13279f2967bcSAlan Phipps 
13289f2967bcSAlan Phipps     // If no explicit default case exists, create a branch region to represent
13299f2967bcSAlan Phipps     // the hidden branch, which will be added later by the CodeGen. This region
13309f2967bcSAlan Phipps     // will be associated with the switch statement's condition.
13319f2967bcSAlan Phipps     if (!HasDefaultCase) {
13329f2967bcSAlan Phipps       Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
13339f2967bcSAlan Phipps       Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
13349f2967bcSAlan Phipps       createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
13359f2967bcSAlan Phipps     }
1336ee02499aSAlex Lorenz   }
1337ee02499aSAlex Lorenz 
1338bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
1339bf42cfd7SJustin Bogner     extendRegion(S);
1340ee02499aSAlex Lorenz 
1341bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
1342bf42cfd7SJustin Bogner 
1343bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1344bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
1345bf42cfd7SJustin Bogner     // the first case in a switch.
1346a6e4358fSStephen Kelly     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1347bf42cfd7SJustin Bogner       Parent.setCounter(Count);
1348bf42cfd7SJustin Bogner     else
1349bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
1350bf42cfd7SJustin Bogner 
1351*9783e209SZequan Wu     GapRegionCounter = Count;
1352*9783e209SZequan Wu 
1353376c06c2SSanjay Patel     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1354bf42cfd7SJustin Bogner       Visit(CS->getLHS());
1355bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
1356bf42cfd7SJustin Bogner         Visit(RHS);
1357bf42cfd7SJustin Bogner     }
1358ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1359ee02499aSAlex Lorenz   }
1360ee02499aSAlex Lorenz 
1361ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
1362bf42cfd7SJustin Bogner     extendRegion(S);
13639d2a16b9SVedant Kumar     if (S->getInit())
13649d2a16b9SVedant Kumar       Visit(S->getInit());
13659d2a16b9SVedant Kumar 
1366055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
1367055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
1368055ebc34SJustin Bogner     extendRegion(S->getCond());
1369ee02499aSAlex Lorenz 
1370bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1371bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
1372ee02499aSAlex Lorenz 
137391f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
137491f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
137591f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
137691f2e3c9SJustin Bogner 
13772e8c8759SVedant Kumar     // The 'then' count applies to the area immediately after the condition.
1378d83511ddSZequan Wu     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
1379fa8fa044SVedant Kumar     if (Gap)
1380fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
13812e8c8759SVedant Kumar 
1382bf42cfd7SJustin Bogner     extendRegion(S->getThen());
1383bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1384bf42cfd7SJustin Bogner 
1385bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1386bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
1387*9783e209SZequan Wu       bool ThenHasTerminateStmt = HasTerminateStmt;
1388*9783e209SZequan Wu       HasTerminateStmt = false;
1389*9783e209SZequan Wu 
13902e8c8759SVedant Kumar       // The 'else' count applies to the area immediately after the 'then'.
1391d83511ddSZequan Wu       Gap = findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
1392fa8fa044SVedant Kumar       if (Gap)
1393fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
13942e8c8759SVedant Kumar       extendRegion(Else);
1395bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1396*9783e209SZequan Wu 
1397*9783e209SZequan Wu       if (ThenHasTerminateStmt)
1398*9783e209SZequan Wu         HasTerminateStmt = true;
1399bf42cfd7SJustin Bogner     } else
1400bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
1401bf42cfd7SJustin Bogner 
1402*9783e209SZequan Wu     if (OutCount != ParentCount) {
1403bf42cfd7SJustin Bogner       pushRegion(OutCount);
1404*9783e209SZequan Wu       GapRegionCounter = OutCount;
1405*9783e209SZequan Wu     }
14069f2967bcSAlan Phipps 
14079f2967bcSAlan Phipps     // Create Branch Region around condition.
14089f2967bcSAlan Phipps     createBranchRegion(S->getCond(), ThenCount,
14099f2967bcSAlan Phipps                        subtractCounters(ParentCount, ThenCount));
1410ee02499aSAlex Lorenz   }
1411ee02499aSAlex Lorenz 
1412ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
1413bf42cfd7SJustin Bogner     extendRegion(S);
1414049908b2SVedant Kumar     // Handle macros that generate the "try" but not the rest.
1415049908b2SVedant Kumar     extendRegion(S->getTryBlock());
1416049908b2SVedant Kumar 
1417049908b2SVedant Kumar     Counter ParentCount = getRegion().getCounter();
1418049908b2SVedant Kumar     propagateCounts(ParentCount, S->getTryBlock());
1419049908b2SVedant Kumar 
1420ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1421ee02499aSAlex Lorenz       Visit(S->getHandler(I));
1422bf42cfd7SJustin Bogner 
1423bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
1424bf42cfd7SJustin Bogner     pushRegion(ExitCount);
1425ee02499aSAlex Lorenz   }
1426ee02499aSAlex Lorenz 
1427ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1428bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1429ee02499aSAlex Lorenz   }
1430ee02499aSAlex Lorenz 
1431ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1432bf42cfd7SJustin Bogner     extendRegion(E);
1433ee02499aSAlex Lorenz 
1434bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1435bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
1436ee02499aSAlex Lorenz 
14374dc08cc3SZequan Wu     propagateCounts(ParentCount, E->getCond());
1438e3654ce7SJustin Bogner 
1439e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
14402e8c8759SVedant Kumar       // The 'then' count applies to the area immediately after the condition.
1441fa8fa044SVedant Kumar       auto Gap =
1442fa8fa044SVedant Kumar           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1443fa8fa044SVedant Kumar       if (Gap)
1444fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
14452e8c8759SVedant Kumar 
1446e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
1447bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
1448e3654ce7SJustin Bogner     }
14492e8c8759SVedant Kumar 
1450e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
1451bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
1452bf42cfd7SJustin Bogner                     E->getFalseExpr());
14539f2967bcSAlan Phipps 
14549f2967bcSAlan Phipps     // Create Branch Region around condition.
14559f2967bcSAlan Phipps     createBranchRegion(E->getCond(), TrueCount,
14569f2967bcSAlan Phipps                        subtractCounters(ParentCount, TrueCount));
1457ee02499aSAlex Lorenz   }
1458ee02499aSAlex Lorenz 
1459ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
1460e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1461e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1462e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1463bf42cfd7SJustin Bogner 
14649f2967bcSAlan Phipps     // Counter tracks the right hand side of a logical and operator.
1465bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1466bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
14679f2967bcSAlan Phipps 
14689f2967bcSAlan Phipps     // Extract the RHS's Execution Counter.
14699f2967bcSAlan Phipps     Counter RHSExecCnt = getRegionCounter(E);
14709f2967bcSAlan Phipps 
14719f2967bcSAlan Phipps     // Extract the RHS's "True" Instance Counter.
14729f2967bcSAlan Phipps     Counter RHSTrueCnt = getRegionCounter(E->getRHS());
14739f2967bcSAlan Phipps 
14749f2967bcSAlan Phipps     // Extract the Parent Region Counter.
14759f2967bcSAlan Phipps     Counter ParentCnt = getRegion().getCounter();
14769f2967bcSAlan Phipps 
14779f2967bcSAlan Phipps     // Create Branch Region around LHS condition.
14789f2967bcSAlan Phipps     createBranchRegion(E->getLHS(), RHSExecCnt,
14799f2967bcSAlan Phipps                        subtractCounters(ParentCnt, RHSExecCnt));
14809f2967bcSAlan Phipps 
14819f2967bcSAlan Phipps     // Create Branch Region around RHS condition.
14829f2967bcSAlan Phipps     createBranchRegion(E->getRHS(), RHSTrueCnt,
14839f2967bcSAlan Phipps                        subtractCounters(RHSExecCnt, RHSTrueCnt));
1484ee02499aSAlex Lorenz   }
1485ee02499aSAlex Lorenz 
1486ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
1487e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1488e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1489e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1490ee02499aSAlex Lorenz 
14919f2967bcSAlan Phipps     // Counter tracks the right hand side of a logical or operator.
1492bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1493bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
14949f2967bcSAlan Phipps 
14959f2967bcSAlan Phipps     // Extract the RHS's Execution Counter.
14969f2967bcSAlan Phipps     Counter RHSExecCnt = getRegionCounter(E);
14979f2967bcSAlan Phipps 
14989f2967bcSAlan Phipps     // Extract the RHS's "False" Instance Counter.
14999f2967bcSAlan Phipps     Counter RHSFalseCnt = getRegionCounter(E->getRHS());
15009f2967bcSAlan Phipps 
15019f2967bcSAlan Phipps     // Extract the Parent Region Counter.
15029f2967bcSAlan Phipps     Counter ParentCnt = getRegion().getCounter();
15039f2967bcSAlan Phipps 
15049f2967bcSAlan Phipps     // Create Branch Region around LHS condition.
15059f2967bcSAlan Phipps     createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
15069f2967bcSAlan Phipps                        RHSExecCnt);
15079f2967bcSAlan Phipps 
15089f2967bcSAlan Phipps     // Create Branch Region around RHS condition.
15099f2967bcSAlan Phipps     createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
15109f2967bcSAlan Phipps                        RHSFalseCnt);
151101a0d062SAlex Lorenz   }
1512c109102eSJustin Bogner 
1513c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
1514c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
1515c109102eSJustin Bogner     // propagate counts into them.
1516c109102eSJustin Bogner   }
1517ee02499aSAlex Lorenz };
1518ee02499aSAlex Lorenz 
151914f8fb68SVedant Kumar } // end anonymous namespace
152014f8fb68SVedant Kumar 
1521a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1522a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
1523a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
1524a432d176SJustin Bogner   OS << FunctionName << ":\n";
1525a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
1526a432d176SJustin Bogner   for (const auto &R : Regions) {
1527f2cf38e0SAlex Lorenz     OS.indent(2);
1528f2cf38e0SAlex Lorenz     switch (R.Kind) {
1529f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
1530f2cf38e0SAlex Lorenz       break;
1531f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
1532f2cf38e0SAlex Lorenz       OS << "Expansion,";
1533f2cf38e0SAlex Lorenz       break;
1534f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
1535f2cf38e0SAlex Lorenz       OS << "Skipped,";
1536f2cf38e0SAlex Lorenz       break;
1537a1c4deb7SVedant Kumar     case CounterMappingRegion::GapRegion:
1538a1c4deb7SVedant Kumar       OS << "Gap,";
1539a1c4deb7SVedant Kumar       break;
15409f2967bcSAlan Phipps     case CounterMappingRegion::BranchRegion:
15419f2967bcSAlan Phipps       OS << "Branch,";
15429f2967bcSAlan Phipps       break;
1543f2cf38e0SAlex Lorenz     }
1544f2cf38e0SAlex Lorenz 
15454da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
15464da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1547f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
15489f2967bcSAlan Phipps 
15499f2967bcSAlan Phipps     if (R.Kind == CounterMappingRegion::BranchRegion) {
15509f2967bcSAlan Phipps       OS << ", ";
15519f2967bcSAlan Phipps       Ctx.dump(R.FalseCount, OS);
15529f2967bcSAlan Phipps     }
15539f2967bcSAlan Phipps 
1554f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
15554da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
15564da909b2SJustin Bogner     OS << "\n";
1557f2cf38e0SAlex Lorenz   }
1558f2cf38e0SAlex Lorenz }
1559f2cf38e0SAlex Lorenz 
1560c3324450SKeith Smiley CoverageMappingModuleGen::CoverageMappingModuleGen(
1561c3324450SKeith Smiley     CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
1562c3324450SKeith Smiley     : CGM(CGM), SourceInfo(SourceInfo) {
15638459b8efSPetr Hosek   CoveragePrefixMap = CGM.getCodeGenOpts().CoveragePrefixMap;
1564c3324450SKeith Smiley }
1565c3324450SKeith Smiley 
15665fbd1a33SPetr Hosek std::string CoverageMappingModuleGen::getCurrentDirname() {
15678459b8efSPetr Hosek   if (!CGM.getCodeGenOpts().CoverageCompilationDir.empty())
15688459b8efSPetr Hosek     return CGM.getCodeGenOpts().CoverageCompilationDir;
15695fbd1a33SPetr Hosek 
15705fbd1a33SPetr Hosek   SmallString<256> CWD;
15715fbd1a33SPetr Hosek   llvm::sys::fs::current_path(CWD);
15725fbd1a33SPetr Hosek   return CWD.str().str();
15735fbd1a33SPetr Hosek }
15745fbd1a33SPetr Hosek 
1575c3324450SKeith Smiley std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
1576c3324450SKeith Smiley   llvm::SmallString<256> Path(Filename);
1577c3324450SKeith Smiley   llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
15788459b8efSPetr Hosek   for (const auto &Entry : CoveragePrefixMap) {
1579c3324450SKeith Smiley     if (llvm::sys::path::replace_path_prefix(Path, Entry.first, Entry.second))
1580c3324450SKeith Smiley       break;
1581c3324450SKeith Smiley   }
1582c3324450SKeith Smiley   return Path.str().str();
1583c3324450SKeith Smiley }
1584c3324450SKeith Smiley 
1585dd1ea9deSVedant Kumar static std::string getInstrProfSection(const CodeGenModule &CGM,
1586dd1ea9deSVedant Kumar                                        llvm::InstrProfSectKind SK) {
1587dd1ea9deSVedant Kumar   return llvm::getInstrProfSectionName(
1588dd1ea9deSVedant Kumar       SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1589dd1ea9deSVedant Kumar }
1590dd1ea9deSVedant Kumar 
1591dd1ea9deSVedant Kumar void CoverageMappingModuleGen::emitFunctionMappingRecord(
1592dd1ea9deSVedant Kumar     const FunctionInfo &Info, uint64_t FilenamesRef) {
159399317124SVedant Kumar   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1594dd1ea9deSVedant Kumar 
1595dd1ea9deSVedant Kumar   // Assign a name to the function record. This is used to merge duplicates.
1596dd1ea9deSVedant Kumar   std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1597dd1ea9deSVedant Kumar 
1598dd1ea9deSVedant Kumar   // A dummy description for a function included-but-not-used in a TU can be
1599dd1ea9deSVedant Kumar   // replaced by full description provided by a different TU. The two kinds of
1600dd1ea9deSVedant Kumar   // descriptions play distinct roles: therefore, assign them different names
1601dd1ea9deSVedant Kumar   // to prevent `linkonce_odr` merging.
1602dd1ea9deSVedant Kumar   if (Info.IsUsed)
1603dd1ea9deSVedant Kumar     FuncRecordName += "u";
1604dd1ea9deSVedant Kumar 
1605dd1ea9deSVedant Kumar   // Create the function record type.
1606dd1ea9deSVedant Kumar   const uint64_t NameHash = Info.NameHash;
1607dd1ea9deSVedant Kumar   const uint64_t FuncHash = Info.FuncHash;
1608dd1ea9deSVedant Kumar   const std::string &CoverageMapping = Info.CoverageMapping;
160933888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
161033888717SVedant Kumar   llvm::Type *FunctionRecordTypes[] = {
161133888717SVedant Kumar #include "llvm/ProfileData/InstrProfData.inc"
161233888717SVedant Kumar   };
1613dd1ea9deSVedant Kumar   auto *FunctionRecordTy =
161433888717SVedant Kumar       llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
161533888717SVedant Kumar                             /*isPacked=*/true);
161699317124SVedant Kumar 
1617dd1ea9deSVedant Kumar   // Create the function record constant.
161833888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
161933888717SVedant Kumar   llvm::Constant *FunctionRecordVals[] = {
162033888717SVedant Kumar       #include "llvm/ProfileData/InstrProfData.inc"
162133888717SVedant Kumar   };
1622dd1ea9deSVedant Kumar   auto *FuncRecordConstant = llvm::ConstantStruct::get(
1623dd1ea9deSVedant Kumar       FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1624dd1ea9deSVedant Kumar 
1625dd1ea9deSVedant Kumar   // Create the function record global.
1626dd1ea9deSVedant Kumar   auto *FuncRecord = new llvm::GlobalVariable(
1627dd1ea9deSVedant Kumar       CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1628dd1ea9deSVedant Kumar       llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1629dd1ea9deSVedant Kumar       FuncRecordName);
1630dd1ea9deSVedant Kumar   FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1631dd1ea9deSVedant Kumar   FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1632dd1ea9deSVedant Kumar   FuncRecord->setAlignment(llvm::Align(8));
1633dd1ea9deSVedant Kumar   if (CGM.supportsCOMDAT())
1634dd1ea9deSVedant Kumar     FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1635dd1ea9deSVedant Kumar 
1636dd1ea9deSVedant Kumar   // Make sure the data doesn't get deleted.
1637dd1ea9deSVedant Kumar   CGM.addUsedGlobal(FuncRecord);
1638dd1ea9deSVedant Kumar }
1639dd1ea9deSVedant Kumar 
1640dd1ea9deSVedant Kumar void CoverageMappingModuleGen::addFunctionMappingRecord(
1641dd1ea9deSVedant Kumar     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1642dd1ea9deSVedant Kumar     const std::string &CoverageMapping, bool IsUsed) {
1643dd1ea9deSVedant Kumar   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1644dd1ea9deSVedant Kumar   const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1645dd1ea9deSVedant Kumar   FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
1646dd1ea9deSVedant Kumar 
1647848da137SXinliang David Li   if (!IsUsed)
16482129ae53SXinliang David Li     FunctionNames.push_back(
16492129ae53SXinliang David Li         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1650f2cf38e0SAlex Lorenz 
1651f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1652f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1653f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1654f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1655f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1656f2cf38e0SAlex Lorenz     // expressions.
16575fbd1a33SPetr Hosek     llvm::SmallVector<std::string, 16> FilenameStrs;
1658f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1659f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1660f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
16615fbd1a33SPetr Hosek     FilenameStrs.resize(FileEntries.size() + 1);
16625fbd1a33SPetr Hosek     FilenameStrs[0] = normalizeFilename(getCurrentDirname());
1663b31ee819SJordan Rose     for (const auto &Entry : FileEntries) {
1664b31ee819SJordan Rose       auto I = Entry.second;
1665b31ee819SJordan Rose       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1666b31ee819SJordan Rose     }
16675fbd1a33SPetr Hosek     ArrayRef<std::string> FilenameRefs = llvm::makeArrayRef(FilenameStrs);
1668a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1669a432d176SJustin Bogner                                     Expressions, Regions);
1670a432d176SJustin Bogner     if (Reader.read())
1671f2cf38e0SAlex Lorenz       return;
1672a026a437SXinliang David Li     dump(llvm::outs(), NameValue, Expressions, Regions);
1673f2cf38e0SAlex Lorenz   }
1674ee02499aSAlex Lorenz }
1675ee02499aSAlex Lorenz 
1676ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1677ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1678ee02499aSAlex Lorenz     return;
1679ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1680ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1681ee02499aSAlex Lorenz 
1682ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1683ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
16845fbd1a33SPetr Hosek   FilenameStrs.resize(FileEntries.size() + 1);
16855fbd1a33SPetr Hosek   // The first filename is the current working directory.
16863275b18fSPetr Hosek   FilenameStrs[0] = normalizeFilename(getCurrentDirname());
1687ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1688ee02499aSAlex Lorenz     auto I = Entry.second;
168914f8fb68SVedant Kumar     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1690ee02499aSAlex Lorenz   }
1691ee02499aSAlex Lorenz 
1692dd1ea9deSVedant Kumar   std::string Filenames;
1693dd1ea9deSVedant Kumar   {
1694dd1ea9deSVedant Kumar     llvm::raw_string_ostream OS(Filenames);
16955fbd1a33SPetr Hosek     CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
16964cd07dbeSSerge Guelton   }
1697dd1ea9deSVedant Kumar   auto *FilenamesVal =
1698dd1ea9deSVedant Kumar       llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1699dd1ea9deSVedant Kumar   const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
17004cd07dbeSSerge Guelton 
1701dd1ea9deSVedant Kumar   // Emit the function records.
1702dd1ea9deSVedant Kumar   for (const FunctionInfo &Info : FunctionRecords)
1703dd1ea9deSVedant Kumar     emitFunctionMappingRecord(Info, FilenamesRef);
1704ee02499aSAlex Lorenz 
1705dd1ea9deSVedant Kumar   const unsigned NRecords = 0;
1706dd1ea9deSVedant Kumar   const size_t FilenamesSize = Filenames.size();
1707dd1ea9deSVedant Kumar   const unsigned CoverageMappingSize = 0;
170820b188c0SXinliang David Li   llvm::Type *CovDataHeaderTypes[] = {
170920b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
171020b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
171120b188c0SXinliang David Li   };
171220b188c0SXinliang David Li   auto CovDataHeaderTy =
171320b188c0SXinliang David Li       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
171420b188c0SXinliang David Li   llvm::Constant *CovDataHeaderVals[] = {
171520b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
171620b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
171720b188c0SXinliang David Li   };
171820b188c0SXinliang David Li   auto CovDataHeaderVal = llvm::ConstantStruct::get(
171920b188c0SXinliang David Li       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
172020b188c0SXinliang David Li 
1721ee02499aSAlex Lorenz   // Create the coverage data record
1722dd1ea9deSVedant Kumar   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
1723ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1724dd1ea9deSVedant Kumar   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
1725ee02499aSAlex Lorenz   auto CovDataVal =
1726ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
172720b188c0SXinliang David Li   auto CovData = new llvm::GlobalVariable(
1728dd1ea9deSVedant Kumar       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
172920b188c0SXinliang David Li       CovDataVal, llvm::getCoverageMappingVarName());
1730ee02499aSAlex Lorenz 
1731dd1ea9deSVedant Kumar   CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
1732c79099e0SGuillaume Chatelet   CovData->setAlignment(llvm::Align(8));
1733ee02499aSAlex Lorenz 
1734ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1735ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
17362129ae53SXinliang David Li   // Create the deferred function records array
17372129ae53SXinliang David Li   if (!FunctionNames.empty()) {
17382129ae53SXinliang David Li     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
17392129ae53SXinliang David Li                                            FunctionNames.size());
17402129ae53SXinliang David Li     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
17412129ae53SXinliang David Li     // This variable will *NOT* be emitted to the object file. It is used
17422129ae53SXinliang David Li     // to pass the list of names referenced to codegen.
17432129ae53SXinliang David Li     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
17442129ae53SXinliang David Li                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
17457077f0afSXinliang David Li                              llvm::getCoverageUnusedNamesVarName());
17462129ae53SXinliang David Li   }
1747ee02499aSAlex Lorenz }
1748ee02499aSAlex Lorenz 
1749ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1750ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1751ee02499aSAlex Lorenz   if (It != FileEntries.end())
1752ee02499aSAlex Lorenz     return It->second;
17535fbd1a33SPetr Hosek   unsigned FileID = FileEntries.size() + 1;
1754ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1755ee02499aSAlex Lorenz   return FileID;
1756ee02499aSAlex Lorenz }
1757ee02499aSAlex Lorenz 
1758ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1759ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1760ee02499aSAlex Lorenz   assert(CounterMap);
1761e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1762ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1763ee02499aSAlex Lorenz   Walker.write(OS);
1764ee02499aSAlex Lorenz }
1765ee02499aSAlex Lorenz 
1766ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1767ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1768ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1769ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1770ee02499aSAlex Lorenz   Walker.write(OS);
1771ee02499aSAlex Lorenz }
1772