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 
34*9caa3fbeSZequan Wu static llvm::cl::opt<bool> EmptyLineCommentCoverage(
35*9caa3fbeSZequan Wu     "emptyline-comment-coverage",
36*9caa3fbeSZequan Wu     llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
37*9caa3fbeSZequan Wu                    "disable it on test)"),
38*9caa3fbeSZequan Wu     llvm::cl::init(true), llvm::cl::Hidden);
39*9caa3fbeSZequan 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) {
46*9caa3fbeSZequan Wu   CoverageSourceInfo *CoverageInfo =
47*9caa3fbeSZequan Wu       new CoverageSourceInfo(PP.getSourceManager());
48b46176bbSZequan Wu   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
49*9caa3fbeSZequan Wu   if (EmptyLineCommentCoverage) {
50b46176bbSZequan Wu     PP.addCommentHandler(CoverageInfo);
51*9caa3fbeSZequan 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     });
59*9caa3fbeSZequan Wu   }
60b46176bbSZequan Wu   return CoverageInfo;
61b46176bbSZequan Wu }
62b46176bbSZequan Wu 
63*9caa3fbeSZequan Wu void CoverageSourceInfo::AddSkippedRange(SourceRange Range) {
64*9caa3fbeSZequan Wu   if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
65*9caa3fbeSZequan Wu       PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
66*9caa3fbeSZequan Wu       SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
67*9caa3fbeSZequan Wu                                     Range.getBegin()))
68*9caa3fbeSZequan Wu     SkippedRanges.back().Range.setEnd(Range.getEnd());
69*9caa3fbeSZequan Wu   else
70*9caa3fbeSZequan Wu     SkippedRanges.push_back({Range, PrevTokLoc});
71*9caa3fbeSZequan Wu }
72*9caa3fbeSZequan Wu 
733919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
74*9caa3fbeSZequan Wu   AddSkippedRange(Range);
75*9caa3fbeSZequan Wu }
76*9caa3fbeSZequan Wu 
77*9caa3fbeSZequan Wu void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
78*9caa3fbeSZequan Wu   AddSkippedRange(Range);
79b46176bbSZequan Wu }
80b46176bbSZequan Wu 
81b46176bbSZequan Wu bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
82*9caa3fbeSZequan Wu   AddSkippedRange(Range);
83b46176bbSZequan Wu   return false;
84b46176bbSZequan Wu }
85b46176bbSZequan Wu 
86b46176bbSZequan Wu void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
87*9caa3fbeSZequan 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 {
95ee02499aSAlex Lorenz   Counter Count;
96ee02499aSAlex Lorenz 
979fc8faf9SAdrian Prantl   /// The region's starting location.
98bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
99ee02499aSAlex Lorenz 
1009fc8faf9SAdrian Prantl   /// The region's ending location.
101bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
102ee02499aSAlex Lorenz 
103747b0e29SVedant Kumar   /// Whether this region should be emitted after its parent is emitted.
104747b0e29SVedant Kumar   bool DeferRegion;
105747b0e29SVedant Kumar 
106a1c4deb7SVedant Kumar   /// Whether this region is a gap region. The count from a gap region is set
107a1c4deb7SVedant Kumar   /// as the line execution count if there are no other regions on the line.
108a1c4deb7SVedant Kumar   bool GapRegion;
109a1c4deb7SVedant Kumar 
11009c7179bSJustin Bogner public:
111bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
112a1c4deb7SVedant Kumar                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
113a1c4deb7SVedant Kumar                       bool GapRegion = false)
114747b0e29SVedant Kumar       : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
115a1c4deb7SVedant Kumar         DeferRegion(DeferRegion), GapRegion(GapRegion) {}
116ee02499aSAlex Lorenz 
11709c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
11809c7179bSJustin Bogner 
119bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
12009c7179bSJustin Bogner 
121bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
122bf42cfd7SJustin Bogner 
123bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
124bf42cfd7SJustin Bogner 
1253cffc4c7SStephen Kelly   SourceLocation getBeginLoc() const {
126bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
127bf42cfd7SJustin Bogner     return *LocStart;
12809c7179bSJustin Bogner   }
12909c7179bSJustin Bogner 
130bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
131ee02499aSAlex Lorenz 
132a14a1f92SVedant Kumar   void setEndLoc(SourceLocation Loc) {
133a14a1f92SVedant Kumar     assert(Loc.isValid() && "Setting an invalid end location");
134a14a1f92SVedant Kumar     LocEnd = Loc;
135a14a1f92SVedant Kumar   }
136ee02499aSAlex Lorenz 
137462c77b4SCraig Topper   SourceLocation getEndLoc() const {
138bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
139bf42cfd7SJustin Bogner     return *LocEnd;
140ee02499aSAlex Lorenz   }
141747b0e29SVedant Kumar 
142747b0e29SVedant Kumar   bool isDeferred() const { return DeferRegion; }
143747b0e29SVedant Kumar 
144747b0e29SVedant Kumar   void setDeferred(bool Deferred) { DeferRegion = Deferred; }
145a1c4deb7SVedant Kumar 
146a1c4deb7SVedant Kumar   bool isGap() const { return GapRegion; }
147a1c4deb7SVedant Kumar 
148a1c4deb7SVedant Kumar   void setGap(bool Gap) { GapRegion = Gap; }
149ee02499aSAlex Lorenz };
150ee02499aSAlex Lorenz 
151d7369648SVedant Kumar /// Spelling locations for the start and end of a source region.
152d7369648SVedant Kumar struct SpellingRegion {
153d7369648SVedant Kumar   /// The line where the region starts.
154d7369648SVedant Kumar   unsigned LineStart;
155d7369648SVedant Kumar 
156d7369648SVedant Kumar   /// The column where the region starts.
157d7369648SVedant Kumar   unsigned ColumnStart;
158d7369648SVedant Kumar 
159d7369648SVedant Kumar   /// The line where the region ends.
160d7369648SVedant Kumar   unsigned LineEnd;
161d7369648SVedant Kumar 
162d7369648SVedant Kumar   /// The column where the region ends.
163d7369648SVedant Kumar   unsigned ColumnEnd;
164d7369648SVedant Kumar 
165d7369648SVedant Kumar   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
166d7369648SVedant Kumar                  SourceLocation LocEnd) {
167d7369648SVedant Kumar     LineStart = SM.getSpellingLineNumber(LocStart);
168d7369648SVedant Kumar     ColumnStart = SM.getSpellingColumnNumber(LocStart);
169d7369648SVedant Kumar     LineEnd = SM.getSpellingLineNumber(LocEnd);
170d7369648SVedant Kumar     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
171d7369648SVedant Kumar   }
172d7369648SVedant Kumar 
173fa8fa044SVedant Kumar   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
174a6e4358fSStephen Kelly       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
175fa8fa044SVedant Kumar 
176d7369648SVedant Kumar   /// Check if the start and end locations appear in source order, i.e
177d7369648SVedant Kumar   /// top->bottom, left->right.
178d7369648SVedant Kumar   bool isInSourceOrder() const {
179d7369648SVedant Kumar     return (LineStart < LineEnd) ||
180d7369648SVedant Kumar            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
181d7369648SVedant Kumar   }
182d7369648SVedant Kumar };
183d7369648SVedant Kumar 
1849fc8faf9SAdrian Prantl /// Provides the common functionality for the different
185ee02499aSAlex Lorenz /// coverage mapping region builders.
186ee02499aSAlex Lorenz class CoverageMappingBuilder {
187ee02499aSAlex Lorenz public:
188ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
189ee02499aSAlex Lorenz   SourceManager &SM;
190ee02499aSAlex Lorenz   const LangOptions &LangOpts;
191ee02499aSAlex Lorenz 
192ee02499aSAlex Lorenz private:
1939fc8faf9SAdrian Prantl   /// Map of clang's FileIDs to IDs used for coverage mapping.
194bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
195bf42cfd7SJustin Bogner       FileIDMapping;
196ee02499aSAlex Lorenz 
197ee02499aSAlex Lorenz public:
1989fc8faf9SAdrian Prantl   /// The coverage mapping regions for this function
199ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
2009fc8faf9SAdrian Prantl   /// The source mapping regions for this function.
201f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
202ee02499aSAlex Lorenz 
2039fc8faf9SAdrian Prantl   /// A set of regions which can be used as a filter.
204fc05ee34SIgor Kudrin   ///
205fc05ee34SIgor Kudrin   /// It is produced by emitExpansionRegions() and is used in
206fc05ee34SIgor Kudrin   /// emitSourceRegions() to suppress producing code regions if
207fc05ee34SIgor Kudrin   /// the same area is covered by expansion regions.
208fc05ee34SIgor Kudrin   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
209fc05ee34SIgor Kudrin       SourceRegionFilter;
210fc05ee34SIgor Kudrin 
211ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
212ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
213bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
214ee02499aSAlex Lorenz 
2159fc8faf9SAdrian Prantl   /// Return the precise end location for the given token.
216ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
217bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
218bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
219bf42cfd7SJustin Bogner     unsigned TokLen =
220bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
221bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
222ee02499aSAlex Lorenz   }
223ee02499aSAlex Lorenz 
2249fc8faf9SAdrian Prantl   /// Return the start location of an included file or expanded macro.
225bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
226bf42cfd7SJustin Bogner     if (Loc.isMacroID())
227bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
228bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
229ee02499aSAlex Lorenz   }
230ee02499aSAlex Lorenz 
2319fc8faf9SAdrian Prantl   /// Return the end location of an included file or expanded macro.
232bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
233bf42cfd7SJustin Bogner     if (Loc.isMacroID())
234bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
235f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
236bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
237bf42cfd7SJustin Bogner   }
238ee02499aSAlex Lorenz 
2399fc8faf9SAdrian Prantl   /// Find out where the current file is included or macro is expanded.
240bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
241b5f8171aSRichard Smith     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
242bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
243bf42cfd7SJustin Bogner   }
244bf42cfd7SJustin Bogner 
2459fc8faf9SAdrian Prantl   /// Return true if \c Loc is a location in a built-in macro.
246682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
24799d1b295SMehdi Amini     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
248682bfbf3SJustin Bogner   }
249682bfbf3SJustin Bogner 
2509fc8faf9SAdrian Prantl   /// Check whether \c Loc is included or expanded from \c Parent.
251d9e1a61dSIgor Kudrin   bool isNestedIn(SourceLocation Loc, FileID Parent) {
252d9e1a61dSIgor Kudrin     do {
253d9e1a61dSIgor Kudrin       Loc = getIncludeOrExpansionLoc(Loc);
254d9e1a61dSIgor Kudrin       if (Loc.isInvalid())
255d9e1a61dSIgor Kudrin         return false;
256d9e1a61dSIgor Kudrin     } while (!SM.isInFileID(Loc, Parent));
257d9e1a61dSIgor Kudrin     return true;
258d9e1a61dSIgor Kudrin   }
259d9e1a61dSIgor Kudrin 
2609fc8faf9SAdrian Prantl   /// Get the start of \c S ignoring macro arguments and builtin macros.
261bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
262f2ceec48SStephen Kelly     SourceLocation Loc = S->getBeginLoc();
263682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
264b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
265bf42cfd7SJustin Bogner     return Loc;
266bf42cfd7SJustin Bogner   }
267bf42cfd7SJustin Bogner 
2689fc8faf9SAdrian Prantl   /// Get the end of \c S ignoring macro arguments and builtin macros.
269bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
2701c301dcbSStephen Kelly     SourceLocation Loc = S->getEndLoc();
271682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
272b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
273f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
274bf42cfd7SJustin Bogner   }
275bf42cfd7SJustin Bogner 
2769fc8faf9SAdrian Prantl   /// Find the set of files we have regions for and assign IDs
277bf42cfd7SJustin Bogner   ///
278bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
279bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
280bf42cfd7SJustin Bogner   /// expansion regions.
281bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
282bf42cfd7SJustin Bogner     FileIDMapping.clear();
283bf42cfd7SJustin Bogner 
284bc6b80a0SVedant Kumar     llvm::SmallSet<FileID, 8> Visited;
285bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
286bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
287a6e4358fSStephen Kelly       SourceLocation Loc = Region.getBeginLoc();
288bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
289bc6b80a0SVedant Kumar       if (!Visited.insert(File).second)
290bf42cfd7SJustin Bogner         continue;
291bf42cfd7SJustin Bogner 
29293205af0SVedant Kumar       // Do not map FileID's associated with system headers.
29393205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
29493205af0SVedant Kumar         continue;
29593205af0SVedant Kumar 
296bf42cfd7SJustin Bogner       unsigned Depth = 0;
297bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
298ed1fe5d0SYaron Keren            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
299bf42cfd7SJustin Bogner         ++Depth;
300bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
301bf42cfd7SJustin Bogner     }
302899d1392SFangrui Song     llvm::stable_sort(FileLocs, llvm::less_second());
303bf42cfd7SJustin Bogner 
304bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
305bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
306bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
307ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
308ee02499aSAlex Lorenz       if (!Entry)
309bf42cfd7SJustin Bogner         continue;
310ee02499aSAlex Lorenz 
311bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
312bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
313bf42cfd7SJustin Bogner     }
314ee02499aSAlex Lorenz   }
315ee02499aSAlex Lorenz 
3169fc8faf9SAdrian Prantl   /// Get the coverage mapping file ID for \c Loc.
317bf42cfd7SJustin Bogner   ///
318bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
319bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
320bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
321bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
322bf42cfd7SJustin Bogner       return Mapping->second.first;
323903678caSJustin Bogner     return None;
324ee02499aSAlex Lorenz   }
325ee02499aSAlex Lorenz 
326b46176bbSZequan Wu   /// This shrinks the skipped range if it spans a line that contains a
327b46176bbSZequan Wu   /// non-comment token. If shrinking the skipped range would make it empty,
328b46176bbSZequan Wu   /// this returns None.
329b46176bbSZequan Wu   Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
33084fffa67SZequan Wu                                               SourceLocation LocStart,
33184fffa67SZequan Wu                                               SourceLocation LocEnd,
332b46176bbSZequan Wu                                               SourceLocation PrevTokLoc,
333b46176bbSZequan Wu                                               SourceLocation NextTokLoc) {
33484fffa67SZequan Wu     SpellingRegion SR{SM, LocStart, LocEnd};
335*9caa3fbeSZequan Wu     SR.ColumnStart = 1;
336*9caa3fbeSZequan Wu     if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
337*9caa3fbeSZequan Wu         SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
338*9caa3fbeSZequan Wu       SR.LineStart++;
339*9caa3fbeSZequan Wu     if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
340*9caa3fbeSZequan Wu         SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
341*9caa3fbeSZequan Wu       SR.LineEnd--;
342*9caa3fbeSZequan Wu       SR.ColumnEnd++;
343*9caa3fbeSZequan Wu     }
344*9caa3fbeSZequan Wu     if (SR.isInSourceOrder())
345b46176bbSZequan Wu       return SR;
346b46176bbSZequan Wu     return None;
347b46176bbSZequan Wu   }
348b46176bbSZequan Wu 
3499fc8faf9SAdrian Prantl   /// Gather all the regions that were skipped by the preprocessor
350b46176bbSZequan Wu   /// using the constructs like #if or comments.
351ee02499aSAlex Lorenz   void gatherSkippedRegions() {
352ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
353ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
354ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
355ee02499aSAlex Lorenz     FileLineRanges.resize(
356ee02499aSAlex Lorenz         FileIDMapping.size(),
357ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
358ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
359ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
360ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
361ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
362ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
363ee02499aSAlex Lorenz     }
364ee02499aSAlex Lorenz 
365ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
366b46176bbSZequan Wu     for (auto &I : SkippedRanges) {
367b46176bbSZequan Wu       SourceRange Range = I.Range;
368b46176bbSZequan Wu       auto LocStart = Range.getBegin();
369b46176bbSZequan Wu       auto LocEnd = Range.getEnd();
370bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
371bf42cfd7SJustin Bogner              "region spans multiple files");
372ee02499aSAlex Lorenz 
373bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
374903678caSJustin Bogner       if (!CovFileID)
375ee02499aSAlex Lorenz         continue;
37684fffa67SZequan Wu       Optional<SpellingRegion> SR =
37784fffa67SZequan Wu           adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc, I.NextTokLoc);
37884fffa67SZequan Wu       if (!SR.hasValue())
379b46176bbSZequan Wu         continue;
380fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
38184fffa67SZequan Wu           *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
38284fffa67SZequan Wu           SR->ColumnEnd);
383ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
3842a8c18d9SAlexander Kornienko       // the source code of this function.
385903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
386903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
387ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
388ee02499aSAlex Lorenz     }
389ee02499aSAlex Lorenz   }
390ee02499aSAlex Lorenz 
3919fc8faf9SAdrian Prantl   /// Generate the coverage counter mapping regions from collected
392ee02499aSAlex Lorenz   /// source regions.
393fc05ee34SIgor Kudrin   void emitSourceRegions(const SourceRegionFilter &Filter) {
394bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
395bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
396ee02499aSAlex Lorenz 
397a6e4358fSStephen Kelly       SourceLocation LocStart = Region.getBeginLoc();
3988b563665SYaron Keren       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
399f59329b0SJustin Bogner 
40093205af0SVedant Kumar       // Ignore regions from system headers.
40193205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
40293205af0SVedant Kumar         continue;
40393205af0SVedant Kumar 
404bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
405bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
406bf42cfd7SJustin Bogner       if (!CovFileID)
407ee02499aSAlex Lorenz         continue;
408ee02499aSAlex Lorenz 
409f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
410bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
411bf42cfd7SJustin Bogner              "region spans multiple files");
412bf42cfd7SJustin Bogner 
413fc05ee34SIgor Kudrin       // Don't add code regions for the area covered by expansion regions.
414fc05ee34SIgor Kudrin       // This not only suppresses redundant regions, but sometimes prevents
415fc05ee34SIgor Kudrin       // creating regions with wrong counters if, for example, a statement's
416fc05ee34SIgor Kudrin       // body ends at the end of a nested macro.
417fc05ee34SIgor Kudrin       if (Filter.count(std::make_pair(LocStart, LocEnd)))
418fc05ee34SIgor Kudrin         continue;
419fc05ee34SIgor Kudrin 
420d7369648SVedant Kumar       // Find the spelling locations for the mapping region.
421d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
422d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
423a1c4deb7SVedant Kumar 
424a1c4deb7SVedant Kumar       if (Region.isGap()) {
425a1c4deb7SVedant Kumar         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
426a1c4deb7SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
427a1c4deb7SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
428a1c4deb7SVedant Kumar       } else {
429bf42cfd7SJustin Bogner         MappingRegions.push_back(CounterMappingRegion::makeRegion(
430d7369648SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
431d7369648SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
432bf42cfd7SJustin Bogner       }
433bf42cfd7SJustin Bogner     }
434a1c4deb7SVedant Kumar   }
435bf42cfd7SJustin Bogner 
4369fc8faf9SAdrian Prantl   /// Generate expansion regions for each virtual file we've seen.
437fc05ee34SIgor Kudrin   SourceRegionFilter emitExpansionRegions() {
438fc05ee34SIgor Kudrin     SourceRegionFilter Filter;
439bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
440bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
441bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
442bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
443ee02499aSAlex Lorenz         continue;
444ee02499aSAlex Lorenz 
445bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
446bf42cfd7SJustin Bogner       if (!ParentFileID)
447bf42cfd7SJustin Bogner         continue;
448bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
449bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
450bf42cfd7SJustin Bogner 
451bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
452bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
453bf42cfd7SJustin Bogner              "region spans multiple files");
454fc05ee34SIgor Kudrin       Filter.insert(std::make_pair(ParentLoc, LocEnd));
455bf42cfd7SJustin Bogner 
456d7369648SVedant Kumar       SpellingRegion SR{SM, ParentLoc, LocEnd};
457d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
458bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
459d7369648SVedant Kumar           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
460d7369648SVedant Kumar           SR.LineEnd, SR.ColumnEnd));
461ee02499aSAlex Lorenz     }
462fc05ee34SIgor Kudrin     return Filter;
463ee02499aSAlex Lorenz   }
464ee02499aSAlex Lorenz };
465ee02499aSAlex Lorenz 
4669fc8faf9SAdrian Prantl /// Creates unreachable coverage regions for the functions that
467ee02499aSAlex Lorenz /// are not emitted.
468ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
469ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
470ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
471ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
472ee02499aSAlex Lorenz 
473ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
474ee02499aSAlex Lorenz     if (!D->hasBody())
475ee02499aSAlex Lorenz       return;
476ee02499aSAlex Lorenz     auto Body = D->getBody();
477d9e1a61dSIgor Kudrin     SourceLocation Start = getStart(Body);
478d9e1a61dSIgor Kudrin     SourceLocation End = getEnd(Body);
479d9e1a61dSIgor Kudrin     if (!SM.isWrittenInSameFile(Start, End)) {
480d9e1a61dSIgor Kudrin       // Walk up to find the common ancestor.
481d9e1a61dSIgor Kudrin       // Correct the locations accordingly.
482d9e1a61dSIgor Kudrin       FileID StartFileID = SM.getFileID(Start);
483d9e1a61dSIgor Kudrin       FileID EndFileID = SM.getFileID(End);
484d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
485d9e1a61dSIgor Kudrin         Start = getIncludeOrExpansionLoc(Start);
486d9e1a61dSIgor Kudrin         assert(Start.isValid() &&
487d9e1a61dSIgor Kudrin                "Declaration start location not nested within a known region");
488d9e1a61dSIgor Kudrin         StartFileID = SM.getFileID(Start);
489d9e1a61dSIgor Kudrin       }
490d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID) {
491d9e1a61dSIgor Kudrin         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
492d9e1a61dSIgor Kudrin         assert(End.isValid() &&
493d9e1a61dSIgor Kudrin                "Declaration end location not nested within a known region");
494d9e1a61dSIgor Kudrin         EndFileID = SM.getFileID(End);
495d9e1a61dSIgor Kudrin       }
496d9e1a61dSIgor Kudrin     }
497d9e1a61dSIgor Kudrin     SourceRegions.emplace_back(Counter(), Start, End);
498ee02499aSAlex Lorenz   }
499ee02499aSAlex Lorenz 
5009fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
501ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
502ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
503bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
504fc05ee34SIgor Kudrin     emitSourceRegions(SourceRegionFilter());
505ee02499aSAlex Lorenz 
506efd319a2SVedant Kumar     if (MappingRegions.empty())
507efd319a2SVedant Kumar       return;
508efd319a2SVedant Kumar 
5095fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
510ee02499aSAlex Lorenz     Writer.write(OS);
511ee02499aSAlex Lorenz   }
512ee02499aSAlex Lorenz };
513ee02499aSAlex Lorenz 
5149fc8faf9SAdrian Prantl /// A StmtVisitor that creates coverage mapping regions which map
515ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
516ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
517ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
518ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
5199fc8faf9SAdrian Prantl   /// The map of statements to count values.
520ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
521ee02499aSAlex Lorenz 
5229fc8faf9SAdrian Prantl   /// A stack of currently live regions.
523bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
524ee02499aSAlex Lorenz 
525747b0e29SVedant Kumar   /// The currently deferred region: its end location and count can be set once
526747b0e29SVedant Kumar   /// its parent has been popped from the region stack.
527747b0e29SVedant Kumar   Optional<SourceMappingRegion> DeferredRegion;
528747b0e29SVedant Kumar 
529ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
530ee02499aSAlex Lorenz 
5319fc8faf9SAdrian Prantl   /// A location in the most recently visited file or macro.
532bf42cfd7SJustin Bogner   ///
533bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
534bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
535bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
536bf42cfd7SJustin Bogner 
5378046d22aSVedant Kumar   /// Location of the last terminated region.
5388046d22aSVedant Kumar   Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
5398046d22aSVedant Kumar 
5409fc8faf9SAdrian Prantl   /// Return a counter for the subtraction of \c RHS from \c LHS
541ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
542ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
543ee02499aSAlex Lorenz   }
544ee02499aSAlex Lorenz 
5459fc8faf9SAdrian Prantl   /// Return a counter for the sum of \c LHS and \c RHS.
546ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
547ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
548ee02499aSAlex Lorenz   }
549ee02499aSAlex Lorenz 
550bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
551bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
552bf42cfd7SJustin Bogner   }
553bf42cfd7SJustin Bogner 
5549fc8faf9SAdrian Prantl   /// Return the region counter for the given statement.
555bf42cfd7SJustin Bogner   ///
556ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
557bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
558bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
559ee02499aSAlex Lorenz   }
560ee02499aSAlex Lorenz 
5619fc8faf9SAdrian Prantl   /// Push a region onto the stack.
562bf42cfd7SJustin Bogner   ///
563bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
564bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
565bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
566bf42cfd7SJustin Bogner                     Optional<SourceLocation> EndLoc = None) {
567747b0e29SVedant Kumar     if (StartLoc) {
568bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
569747b0e29SVedant Kumar       completeDeferred(Count, MostRecentLocation);
570747b0e29SVedant Kumar     }
571bf42cfd7SJustin Bogner     RegionStack.emplace_back(Count, StartLoc, EndLoc);
572ee02499aSAlex Lorenz 
573bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
574ee02499aSAlex Lorenz   }
575ee02499aSAlex Lorenz 
576747b0e29SVedant Kumar   /// Complete any pending deferred region by setting its end location and
577747b0e29SVedant Kumar   /// count, and then pushing it onto the region stack.
578747b0e29SVedant Kumar   size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
579747b0e29SVedant Kumar     size_t Index = RegionStack.size();
580747b0e29SVedant Kumar     if (!DeferredRegion)
581747b0e29SVedant Kumar       return Index;
582747b0e29SVedant Kumar 
583747b0e29SVedant Kumar     // Consume the pending region.
584747b0e29SVedant Kumar     SourceMappingRegion DR = DeferredRegion.getValue();
585747b0e29SVedant Kumar     DeferredRegion = None;
586747b0e29SVedant Kumar 
587747b0e29SVedant Kumar     // If the region ends in an expansion, find the expansion site.
588a6e4358fSStephen Kelly     FileID StartFile = SM.getFileID(DR.getBeginLoc());
589f9a0d44eSVedant Kumar     if (SM.getFileID(DeferredEndLoc) != StartFile) {
590747b0e29SVedant Kumar       if (isNestedIn(DeferredEndLoc, StartFile)) {
591747b0e29SVedant Kumar         do {
592747b0e29SVedant Kumar           DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
593747b0e29SVedant Kumar         } while (StartFile != SM.getFileID(DeferredEndLoc));
594f9a0d44eSVedant Kumar       } else {
595f9a0d44eSVedant Kumar         return Index;
596747b0e29SVedant Kumar       }
597747b0e29SVedant Kumar     }
598747b0e29SVedant Kumar 
599747b0e29SVedant Kumar     // The parent of this deferred region ends where the containing decl ends,
600747b0e29SVedant Kumar     // so the region isn't useful.
601a6e4358fSStephen Kelly     if (DR.getBeginLoc() == DeferredEndLoc)
602747b0e29SVedant Kumar       return Index;
603747b0e29SVedant Kumar 
604747b0e29SVedant Kumar     // If we're visiting statements in non-source order (e.g switch cases or
605747b0e29SVedant Kumar     // a loop condition) we can't construct a sensible deferred region.
606a6e4358fSStephen Kelly     if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
607747b0e29SVedant Kumar       return Index;
608747b0e29SVedant Kumar 
609a1c4deb7SVedant Kumar     DR.setGap(true);
610747b0e29SVedant Kumar     DR.setCounter(Count);
611747b0e29SVedant Kumar     DR.setEndLoc(DeferredEndLoc);
612747b0e29SVedant Kumar     handleFileExit(DeferredEndLoc);
613747b0e29SVedant Kumar     RegionStack.push_back(DR);
614747b0e29SVedant Kumar     return Index;
615747b0e29SVedant Kumar   }
616747b0e29SVedant Kumar 
6178046d22aSVedant Kumar   /// Complete a deferred region created after a terminated region at the
6188046d22aSVedant Kumar   /// top-level.
6198046d22aSVedant Kumar   void completeTopLevelDeferredRegion(Counter Count,
6208046d22aSVedant Kumar                                       SourceLocation DeferredEndLoc) {
6218046d22aSVedant Kumar     if (DeferredRegion || !LastTerminatedRegion)
6228046d22aSVedant Kumar       return;
6238046d22aSVedant Kumar 
6248046d22aSVedant Kumar     if (LastTerminatedRegion->second != RegionStack.size())
6258046d22aSVedant Kumar       return;
6268046d22aSVedant Kumar 
6278046d22aSVedant Kumar     SourceLocation Start = LastTerminatedRegion->first;
6288046d22aSVedant Kumar     if (SM.getFileID(Start) != SM.getMainFileID())
6298046d22aSVedant Kumar       return;
6308046d22aSVedant Kumar 
6318046d22aSVedant Kumar     SourceMappingRegion DR = RegionStack.back();
6328046d22aSVedant Kumar     DR.setStartLoc(Start);
6338046d22aSVedant Kumar     DR.setDeferred(false);
6348046d22aSVedant Kumar     DeferredRegion = DR;
6358046d22aSVedant Kumar     completeDeferred(Count, DeferredEndLoc);
6368046d22aSVedant Kumar   }
6378046d22aSVedant Kumar 
6380c3e3115SVedant Kumar   size_t locationDepth(SourceLocation Loc) {
6390c3e3115SVedant Kumar     size_t Depth = 0;
6400c3e3115SVedant Kumar     while (Loc.isValid()) {
6410c3e3115SVedant Kumar       Loc = getIncludeOrExpansionLoc(Loc);
6420c3e3115SVedant Kumar       Depth++;
6430c3e3115SVedant Kumar     }
6440c3e3115SVedant Kumar     return Depth;
6450c3e3115SVedant Kumar   }
6460c3e3115SVedant Kumar 
6479fc8faf9SAdrian Prantl   /// Pop regions from the stack into the function's list of regions.
648bf42cfd7SJustin Bogner   ///
649bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
650bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
651bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
652bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
653747b0e29SVedant Kumar     bool ParentOfDeferredRegion = false;
654bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
655bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
656bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
657a6e4358fSStephen Kelly         SourceLocation StartLoc = Region.getBeginLoc();
658bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
659bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
660bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
6610c3e3115SVedant Kumar         size_t StartDepth = locationDepth(StartLoc);
6620c3e3115SVedant Kumar         size_t EndDepth = locationDepth(EndLoc);
663bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
6640c3e3115SVedant Kumar           bool UnnestStart = StartDepth >= EndDepth;
6650c3e3115SVedant Kumar           bool UnnestEnd = EndDepth >= StartDepth;
6660c3e3115SVedant Kumar           if (UnnestEnd) {
667bf42cfd7SJustin Bogner             // The region ends in a nested file or macro expansion. Create a
668bf42cfd7SJustin Bogner             // separate region for each expansion.
669bf42cfd7SJustin Bogner             SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
670bf42cfd7SJustin Bogner             assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
671bf42cfd7SJustin Bogner 
6728545dae2SIgor Kudrin             if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
673bf42cfd7SJustin Bogner               SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
674bf42cfd7SJustin Bogner 
675f14b2078SJustin Bogner             EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
676dceaaadfSJustin Bogner             if (EndLoc.isInvalid())
677dceaaadfSJustin Bogner               llvm::report_fatal_error("File exit not handled before popRegions");
6780c3e3115SVedant Kumar             EndDepth--;
679bf42cfd7SJustin Bogner           }
6800c3e3115SVedant Kumar           if (UnnestStart) {
6810c3e3115SVedant Kumar             // The region begins in a nested file or macro expansion. Create a
6820c3e3115SVedant Kumar             // separate region for each expansion.
6830c3e3115SVedant Kumar             SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
6840c3e3115SVedant Kumar             assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
6850c3e3115SVedant Kumar 
6860c3e3115SVedant Kumar             if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
6870c3e3115SVedant Kumar               SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
6880c3e3115SVedant Kumar 
6890c3e3115SVedant Kumar             StartLoc = getIncludeOrExpansionLoc(StartLoc);
6900c3e3115SVedant Kumar             if (StartLoc.isInvalid())
6910c3e3115SVedant Kumar               llvm::report_fatal_error("File exit not handled before popRegions");
6920c3e3115SVedant Kumar             StartDepth--;
6930c3e3115SVedant Kumar           }
6940c3e3115SVedant Kumar         }
6950c3e3115SVedant Kumar         Region.setStartLoc(StartLoc);
696bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
697bf42cfd7SJustin Bogner 
698bf42cfd7SJustin Bogner         MostRecentLocation = EndLoc;
699bf42cfd7SJustin Bogner         // If this region happens to span an entire expansion, we need to make
700bf42cfd7SJustin Bogner         // sure we don't overlap the parent region with it.
701bf42cfd7SJustin Bogner         if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
702bf42cfd7SJustin Bogner             EndLoc == getEndOfFileOrMacro(EndLoc))
703bf42cfd7SJustin Bogner           MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
704bf42cfd7SJustin Bogner 
705a6e4358fSStephen Kelly         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
706fa8fa044SVedant Kumar         assert(SpellingRegion(SM, Region).isInSourceOrder());
707f36a5c4aSCraig Topper         SourceRegions.push_back(Region);
708747b0e29SVedant Kumar 
709747b0e29SVedant Kumar         if (ParentOfDeferredRegion) {
710747b0e29SVedant Kumar           ParentOfDeferredRegion = false;
711747b0e29SVedant Kumar 
712747b0e29SVedant Kumar           // If there's an existing deferred region, keep the old one, because
713747b0e29SVedant Kumar           // it means there are two consecutive returns (or a similar pattern).
714747b0e29SVedant Kumar           if (!DeferredRegion.hasValue() &&
715747b0e29SVedant Kumar               // File IDs aren't gathered within macro expansions, so it isn't
716747b0e29SVedant Kumar               // useful to try and create a deferred region inside of one.
717f9a0d44eSVedant Kumar               !EndLoc.isMacroID())
718747b0e29SVedant Kumar             DeferredRegion =
719747b0e29SVedant Kumar                 SourceMappingRegion(Counter::getZero(), EndLoc, None);
720747b0e29SVedant Kumar         }
721747b0e29SVedant Kumar       } else if (Region.isDeferred()) {
722747b0e29SVedant Kumar         assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
723747b0e29SVedant Kumar         ParentOfDeferredRegion = true;
724bf42cfd7SJustin Bogner       }
725bf42cfd7SJustin Bogner       RegionStack.pop_back();
7268046d22aSVedant Kumar 
7278046d22aSVedant Kumar       // If the zero region pushed after the last terminated region no longer
7288046d22aSVedant Kumar       // exists, clear its cached information.
7298046d22aSVedant Kumar       if (LastTerminatedRegion &&
7308046d22aSVedant Kumar           RegionStack.size() < LastTerminatedRegion->second)
7318046d22aSVedant Kumar         LastTerminatedRegion = None;
732bf42cfd7SJustin Bogner     }
733747b0e29SVedant Kumar     assert(!ParentOfDeferredRegion && "Deferred region with no parent");
734ee02499aSAlex Lorenz   }
735ee02499aSAlex Lorenz 
7369fc8faf9SAdrian Prantl   /// Return the currently active region.
737bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
738bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
739bf42cfd7SJustin Bogner     return RegionStack.back();
740ee02499aSAlex Lorenz   }
741ee02499aSAlex Lorenz 
7427225a261SVedant Kumar   /// Propagate counts through the children of \p S if \p VisitChildren is true.
7437225a261SVedant Kumar   /// Otherwise, only emit a count for \p S itself.
7447225a261SVedant Kumar   Counter propagateCounts(Counter TopCount, const Stmt *S,
7457225a261SVedant Kumar                           bool VisitChildren = true) {
7467838696eSVedant Kumar     SourceLocation StartLoc = getStart(S);
7477838696eSVedant Kumar     SourceLocation EndLoc = getEnd(S);
7487838696eSVedant Kumar     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
7497225a261SVedant Kumar     if (VisitChildren)
750bf42cfd7SJustin Bogner       Visit(S);
751bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
752bf42cfd7SJustin Bogner     popRegions(Index);
75339f01975SVedant Kumar 
75439f01975SVedant Kumar     // The statement may be spanned by an expansion. Make sure we handle a file
75539f01975SVedant Kumar     // exit out of this expansion before moving to the next statement.
756f2ceec48SStephen Kelly     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
7577838696eSVedant Kumar       MostRecentLocation = EndLoc;
75839f01975SVedant Kumar 
759bf42cfd7SJustin Bogner     return ExitCount;
760ee02499aSAlex Lorenz   }
761ee02499aSAlex Lorenz 
7629fc8faf9SAdrian Prantl   /// Check whether a region with bounds \c StartLoc and \c EndLoc
7630a7c9d11SIgor Kudrin   /// is already added to \c SourceRegions.
7640a7c9d11SIgor Kudrin   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
7650a7c9d11SIgor Kudrin     return SourceRegions.rend() !=
7660a7c9d11SIgor Kudrin            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
7670a7c9d11SIgor Kudrin                         [&](const SourceMappingRegion &Region) {
768a6e4358fSStephen Kelly                           return Region.getBeginLoc() == StartLoc &&
7690a7c9d11SIgor Kudrin                                  Region.getEndLoc() == EndLoc;
7700a7c9d11SIgor Kudrin                         });
7710a7c9d11SIgor Kudrin   }
7720a7c9d11SIgor Kudrin 
7739fc8faf9SAdrian Prantl   /// Adjust the most recently visited location to \c EndLoc.
774bf42cfd7SJustin Bogner   ///
775bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
776bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
777bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
7780a7c9d11SIgor Kudrin     // The code region for a whole macro is created in handleFileExit() when
7790a7c9d11SIgor Kudrin     // it detects exiting of the virtual file of that macro. If we visited
7800a7c9d11SIgor Kudrin     // statements in non-source order, we might already have such a region
7810a7c9d11SIgor Kudrin     // added, for example, if a body of a loop is divided among multiple
7820a7c9d11SIgor Kudrin     // macros. Avoid adding duplicate regions in such case.
78396ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
7840a7c9d11SIgor Kudrin         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
7850a7c9d11SIgor Kudrin         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
7860a7c9d11SIgor Kudrin                              MostRecentLocation))
787bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
788ee02499aSAlex Lorenz   }
789ee02499aSAlex Lorenz 
7909fc8faf9SAdrian Prantl   /// Adjust regions and state when \c NewLoc exits a file.
791bf42cfd7SJustin Bogner   ///
792bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
793bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
794bf42cfd7SJustin Bogner   /// for the exited file.
795bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
796e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
797e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
798bf42cfd7SJustin Bogner       return;
799bf42cfd7SJustin Bogner 
800bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
801bf42cfd7SJustin Bogner     // find the common ancestor.
802bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
803bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
804bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
805bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
806bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
807bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
808bf42cfd7SJustin Bogner         // to adjust our location to the new file.
809bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
810bf42cfd7SJustin Bogner         return;
811bf42cfd7SJustin Bogner       }
812bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
813ee02499aSAlex Lorenz     }
814ee02499aSAlex Lorenz 
815bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
816bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
81757d3f145SPete Cooper     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
81857d3f145SPete Cooper       if (!I.hasStartLoc())
819bf42cfd7SJustin Bogner         continue;
820a6e4358fSStephen Kelly       SourceLocation Loc = I.getBeginLoc();
821bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
82257d3f145SPete Cooper         ParentCounter = I.getCounter();
823bf42cfd7SJustin Bogner         break;
824ee02499aSAlex Lorenz       }
825bf42cfd7SJustin Bogner 
826bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
827bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
828bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
829bf42cfd7SJustin Bogner         // we've seen this region.
830bf42cfd7SJustin Bogner         if (StartLocs.insert(Loc).second)
83157d3f145SPete Cooper           SourceRegions.emplace_back(I.getCounter(), Loc,
832bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
833bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
834ee02499aSAlex Lorenz       }
83557d3f145SPete Cooper       I.setStartLoc(getPreciseTokenLocEnd(Loc));
836bf42cfd7SJustin Bogner     }
837bf42cfd7SJustin Bogner 
838bf42cfd7SJustin Bogner     if (ParentCounter) {
839bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
840bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
841bf42cfd7SJustin Bogner       // corresponding to the parent.
842bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
843bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
844bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
845fa8fa044SVedant Kumar         if (StartLocs.insert(FileStart).second) {
846bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
847bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
848fa8fa044SVedant Kumar           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
849fa8fa044SVedant Kumar         }
850bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
851bf42cfd7SJustin Bogner       }
852bf42cfd7SJustin Bogner     }
853bf42cfd7SJustin Bogner 
854bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
855bf42cfd7SJustin Bogner   }
856bf42cfd7SJustin Bogner 
8579fc8faf9SAdrian Prantl   /// Ensure that \c S is included in the current region.
858bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
859bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
860bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
861bf42cfd7SJustin Bogner 
862bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
863bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
864bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
865747b0e29SVedant Kumar 
866747b0e29SVedant Kumar     completeDeferred(Region.getCounter(), StartLoc);
867bf42cfd7SJustin Bogner   }
868bf42cfd7SJustin Bogner 
8699fc8faf9SAdrian Prantl   /// Mark \c S as a terminator, starting a zero region.
870bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
871bf42cfd7SJustin Bogner     extendRegion(S);
872bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
8738046d22aSVedant Kumar     SourceLocation EndLoc = getEnd(S);
874bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
8758046d22aSVedant Kumar       Region.setEndLoc(EndLoc);
876bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
8778046d22aSVedant Kumar     auto &ZeroRegion = getRegion();
8788046d22aSVedant Kumar     ZeroRegion.setDeferred(true);
8798046d22aSVedant Kumar     LastTerminatedRegion = {EndLoc, RegionStack.size()};
880bf42cfd7SJustin Bogner   }
881ee02499aSAlex Lorenz 
882fa8fa044SVedant Kumar   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
883fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
884fa8fa044SVedant Kumar                                            SourceLocation BeforeLoc) {
8859500a720SZequan Wu     // If the start and end locations of the gap are both within the same macro
8869500a720SZequan Wu     // file, the range may not be in source order.
8879500a720SZequan Wu     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
8889500a720SZequan Wu       return None;
889fa8fa044SVedant Kumar     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
890fa8fa044SVedant Kumar       return None;
891fa8fa044SVedant Kumar     return {{AfterLoc, BeforeLoc}};
892fa8fa044SVedant Kumar   }
893fa8fa044SVedant Kumar 
8949500a720SZequan Wu   /// Find the source range after \p AfterStmt and before \p BeforeStmt.
8959500a720SZequan Wu   Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
8969500a720SZequan Wu                                            const Stmt *BeforeStmt) {
8979500a720SZequan Wu     return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
8989500a720SZequan Wu                               getStart(BeforeStmt));
8999500a720SZequan Wu   }
9009500a720SZequan Wu 
9012e8c8759SVedant Kumar   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
9022e8c8759SVedant Kumar   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
9032e8c8759SVedant Kumar                             Counter Count) {
904fa8fa044SVedant Kumar     if (StartLoc == EndLoc)
9052e8c8759SVedant Kumar       return;
906fa8fa044SVedant Kumar     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
9072e8c8759SVedant Kumar     handleFileExit(StartLoc);
9082e8c8759SVedant Kumar     size_t Index = pushRegion(Count, StartLoc, EndLoc);
9092e8c8759SVedant Kumar     getRegion().setGap(true);
9102e8c8759SVedant Kumar     handleFileExit(EndLoc);
9112e8c8759SVedant Kumar     popRegions(Index);
9122e8c8759SVedant Kumar   }
9132e8c8759SVedant Kumar 
9149fc8faf9SAdrian Prantl   /// Keep counts of breaks and continues inside loops.
915ee02499aSAlex Lorenz   struct BreakContinue {
916ee02499aSAlex Lorenz     Counter BreakCount;
917ee02499aSAlex Lorenz     Counter ContinueCount;
918ee02499aSAlex Lorenz   };
919ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
920ee02499aSAlex Lorenz 
921ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
922ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
923e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
924ee02499aSAlex Lorenz       const LangOptions &LangOpts)
925747b0e29SVedant Kumar       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
926747b0e29SVedant Kumar         DeferredRegion(None) {}
927ee02499aSAlex Lorenz 
9289fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
929ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
930ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
931bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
932fc05ee34SIgor Kudrin     SourceRegionFilter Filter = emitExpansionRegions();
933747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
934fc05ee34SIgor Kudrin     emitSourceRegions(Filter);
935ee02499aSAlex Lorenz     gatherSkippedRegions();
936ee02499aSAlex Lorenz 
937efd319a2SVedant Kumar     if (MappingRegions.empty())
938efd319a2SVedant Kumar       return;
939efd319a2SVedant Kumar 
9404da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
9414da909b2SJustin Bogner                                  MappingRegions);
942ee02499aSAlex Lorenz     Writer.write(OS);
943ee02499aSAlex Lorenz   }
944ee02499aSAlex Lorenz 
945ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
946f2ceec48SStephen Kelly     if (S->getBeginLoc().isValid())
947bf42cfd7SJustin Bogner       extendRegion(S);
948642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
949642f173aSBenjamin Kramer       if (Child)
950642f173aSBenjamin Kramer         this->Visit(Child);
951bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
952ee02499aSAlex Lorenz   }
953ee02499aSAlex Lorenz 
954ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
955747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
956747b0e29SVedant Kumar 
957bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
958efd319a2SVedant Kumar 
959efd319a2SVedant Kumar     // Do not propagate region counts into system headers.
960efd319a2SVedant Kumar     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
961efd319a2SVedant Kumar       return;
962efd319a2SVedant Kumar 
9637225a261SVedant Kumar     // Do not visit the artificial children nodes of defaulted methods. The
9647225a261SVedant Kumar     // lexer may not be able to report back precise token end locations for
9657225a261SVedant Kumar     // these children nodes (llvm.org/PR39822), and moreover users will not be
9667225a261SVedant Kumar     // able to see coverage for them.
9677225a261SVedant Kumar     bool Defaulted = false;
9687225a261SVedant Kumar     if (auto *Method = dyn_cast<CXXMethodDecl>(D))
9697225a261SVedant Kumar       Defaulted = Method->isDefaulted();
9707225a261SVedant Kumar 
9717225a261SVedant Kumar     propagateCounts(getRegionCounter(Body), Body,
9727225a261SVedant Kumar                     /*VisitChildren=*/!Defaulted);
973747b0e29SVedant Kumar     assert(RegionStack.empty() && "Regions entered but never exited");
974747b0e29SVedant Kumar 
97561763b65SVedant Kumar     // Discard the last uncompleted deferred region in a decl, if one exists.
97661763b65SVedant Kumar     // This prevents lines at the end of a function containing only whitespace
97761763b65SVedant Kumar     // or closing braces from being marked as uncovered.
978ef8e05ffSVedant Kumar     DeferredRegion = None;
979341bf429SVedant Kumar   }
980ee02499aSAlex Lorenz 
981ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
982bf42cfd7SJustin Bogner     extendRegion(S);
983ee02499aSAlex Lorenz     if (S->getRetValue())
984ee02499aSAlex Lorenz       Visit(S->getRetValue());
985bf42cfd7SJustin Bogner     terminateRegion(S);
986ee02499aSAlex Lorenz   }
987ee02499aSAlex Lorenz 
988565e37c7SXun Li   void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
989565e37c7SXun Li     extendRegion(S);
990565e37c7SXun Li     Visit(S->getBody());
991565e37c7SXun Li   }
992565e37c7SXun Li 
993565e37c7SXun Li   void VisitCoreturnStmt(const CoreturnStmt *S) {
994565e37c7SXun Li     extendRegion(S);
995565e37c7SXun Li     if (S->getOperand())
996565e37c7SXun Li       Visit(S->getOperand());
997565e37c7SXun Li     terminateRegion(S);
998565e37c7SXun Li   }
999565e37c7SXun Li 
1000f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
1001f959febfSJustin Bogner     extendRegion(E);
1002f959febfSJustin Bogner     if (E->getSubExpr())
1003f959febfSJustin Bogner       Visit(E->getSubExpr());
1004f959febfSJustin Bogner     terminateRegion(E);
1005f959febfSJustin Bogner   }
1006f959febfSJustin Bogner 
1007bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
1008ee02499aSAlex Lorenz 
1009ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
10108046d22aSVedant Kumar     Counter LabelCount = getRegionCounter(S);
1011bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
10128046d22aSVedant Kumar     completeTopLevelDeferredRegion(LabelCount, Start);
1013d781d97eSVedant Kumar     completeDeferred(LabelCount, Start);
1014bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
1015bf42cfd7SJustin Bogner     handleFileExit(Start);
10168046d22aSVedant Kumar     pushRegion(LabelCount, Start);
1017ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1018ee02499aSAlex Lorenz   }
1019ee02499aSAlex Lorenz 
1020ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
1021ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1022ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
1023bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
10247f53fbfcSEli Friedman     // FIXME: a break in a switch should terminate regions for all preceding
10257f53fbfcSEli Friedman     // case statements, not just the most recent one.
1026bf42cfd7SJustin Bogner     terminateRegion(S);
1027ee02499aSAlex Lorenz   }
1028ee02499aSAlex Lorenz 
1029ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
1030ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1031ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
1032bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1033bf42cfd7SJustin Bogner     terminateRegion(S);
1034ee02499aSAlex Lorenz   }
1035ee02499aSAlex Lorenz 
1036181dfe4cSEli Friedman   void VisitCallExpr(const CallExpr *E) {
1037181dfe4cSEli Friedman     VisitStmt(E);
1038181dfe4cSEli Friedman 
1039181dfe4cSEli Friedman     // Terminate the region when we hit a noreturn function.
1040181dfe4cSEli Friedman     // (This is helpful dealing with switch statements.)
1041181dfe4cSEli Friedman     QualType CalleeType = E->getCallee()->getType();
1042181dfe4cSEli Friedman     if (getFunctionExtInfo(*CalleeType).getNoReturn())
1043181dfe4cSEli Friedman       terminateRegion(E);
1044181dfe4cSEli Friedman   }
1045181dfe4cSEli Friedman 
1046ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
1047bf42cfd7SJustin Bogner     extendRegion(S);
1048ee02499aSAlex Lorenz 
1049bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1050bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1051bf42cfd7SJustin Bogner 
1052bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
1053bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
1054bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1055bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1056ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1057bf42cfd7SJustin Bogner 
1058bf42cfd7SJustin Bogner     // Go back to handle the condition.
1059bf42cfd7SJustin Bogner     Counter CondCount =
1060bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1061bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
1062bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
1063bf42cfd7SJustin Bogner 
1064fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
10659500a720SZequan Wu     auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
1066fa8fa044SVedant Kumar     if (Gap)
1067fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1068fa8fa044SVedant Kumar 
1069bf42cfd7SJustin Bogner     Counter OutCount =
1070bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1071bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1072bf42cfd7SJustin Bogner       pushRegion(OutCount);
1073ee02499aSAlex Lorenz   }
1074ee02499aSAlex Lorenz 
1075ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
1076bf42cfd7SJustin Bogner     extendRegion(S);
1077ee02499aSAlex Lorenz 
1078bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1079bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1080bf42cfd7SJustin Bogner 
1081bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
1082bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1083bf42cfd7SJustin Bogner     Counter BackedgeCount =
1084bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1085ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1086bf42cfd7SJustin Bogner 
1087bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1088bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
1089bf42cfd7SJustin Bogner 
1090bf42cfd7SJustin Bogner     Counter OutCount =
1091bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1092bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1093bf42cfd7SJustin Bogner       pushRegion(OutCount);
1094ee02499aSAlex Lorenz   }
1095ee02499aSAlex Lorenz 
1096ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
1097bf42cfd7SJustin Bogner     extendRegion(S);
1098ee02499aSAlex Lorenz     if (S->getInit())
1099ee02499aSAlex Lorenz       Visit(S->getInit());
1100ee02499aSAlex Lorenz 
1101bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1102bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1103bf42cfd7SJustin Bogner 
11043e2ae49aSVedant Kumar     // The loop increment may contain a break or continue.
11053e2ae49aSVedant Kumar     if (S->getInc())
11063e2ae49aSVedant Kumar       BreakContinueStack.emplace_back();
11073e2ae49aSVedant Kumar 
1108bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
11093e2ae49aSVedant Kumar     BreakContinueStack.emplace_back();
1110bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1111bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
11123e2ae49aSVedant Kumar     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1113ee02499aSAlex Lorenz 
1114ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
1115ee02499aSAlex Lorenz     // the count for all the continue statements.
11163e2ae49aSVedant Kumar     BreakContinue IncrementBC;
11173e2ae49aSVedant Kumar     if (const Stmt *Inc = S->getInc()) {
11183e2ae49aSVedant Kumar       propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
11193e2ae49aSVedant Kumar       IncrementBC = BreakContinueStack.pop_back_val();
11203e2ae49aSVedant Kumar     }
1121bf42cfd7SJustin Bogner 
1122bf42cfd7SJustin Bogner     // Go back to handle the condition.
11233e2ae49aSVedant Kumar     Counter CondCount = addCounters(
11243e2ae49aSVedant Kumar         addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
11253e2ae49aSVedant Kumar         IncrementBC.ContinueCount);
1126bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
1127bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
1128bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
1129ee02499aSAlex Lorenz     }
1130ee02499aSAlex Lorenz 
1131fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
1132fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1133fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1134fa8fa044SVedant Kumar     if (Gap)
1135fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1136fa8fa044SVedant Kumar 
11373e2ae49aSVedant Kumar     Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
11383e2ae49aSVedant Kumar                                    subtractCounters(CondCount, BodyCount));
1139bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1140bf42cfd7SJustin Bogner       pushRegion(OutCount);
1141ee02499aSAlex Lorenz   }
1142ee02499aSAlex Lorenz 
1143ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1144bf42cfd7SJustin Bogner     extendRegion(S);
11458baa5001SRichard Smith     if (S->getInit())
11468baa5001SRichard Smith       Visit(S->getInit());
1147bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
1148ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
1149bf42cfd7SJustin Bogner 
1150bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1151bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1152bf42cfd7SJustin Bogner 
1153ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1154bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1155bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1156ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1157bf42cfd7SJustin Bogner 
1158fa8fa044SVedant Kumar     // The body count applies to the area immediately after the range.
1159fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1160fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1161fa8fa044SVedant Kumar     if (Gap)
1162fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1163fa8fa044SVedant Kumar 
11641587432dSJustin Bogner     Counter LoopCount =
11651587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
11661587432dSJustin Bogner     Counter OutCount =
11671587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1168bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1169bf42cfd7SJustin Bogner       pushRegion(OutCount);
1170ee02499aSAlex Lorenz   }
1171ee02499aSAlex Lorenz 
1172ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1173bf42cfd7SJustin Bogner     extendRegion(S);
1174ee02499aSAlex Lorenz     Visit(S->getElement());
1175bf42cfd7SJustin Bogner 
1176bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1177bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1178bf42cfd7SJustin Bogner 
1179ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1180bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1181bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1182ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1183bf42cfd7SJustin Bogner 
1184fa8fa044SVedant Kumar     // The body count applies to the area immediately after the collection.
1185fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1186fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1187fa8fa044SVedant Kumar     if (Gap)
1188fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1189fa8fa044SVedant Kumar 
11901587432dSJustin Bogner     Counter LoopCount =
11911587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
11921587432dSJustin Bogner     Counter OutCount =
11931587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1194bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1195bf42cfd7SJustin Bogner       pushRegion(OutCount);
1196ee02499aSAlex Lorenz   }
1197ee02499aSAlex Lorenz 
1198ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
1199bf42cfd7SJustin Bogner     extendRegion(S);
1200f2a6ec55SVedant Kumar     if (S->getInit())
1201f2a6ec55SVedant Kumar       Visit(S->getInit());
1202ee02499aSAlex Lorenz     Visit(S->getCond());
1203bf42cfd7SJustin Bogner 
1204ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1205bf42cfd7SJustin Bogner 
1206bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
1207bf42cfd7SJustin Bogner     extendRegion(Body);
1208bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1209bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
12107f53fbfcSEli Friedman         // Make a region for the body of the switch.  If the body starts with
12117f53fbfcSEli Friedman         // a case, that case will reuse this region; otherwise, this covers
12127f53fbfcSEli Friedman         // the unreachable code at the beginning of the switch body.
1213859bf4d2SVedant Kumar         size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1214859bf4d2SVedant Kumar         getRegion().setGap(true);
1215b5841332SRichard Trieu         for (const auto *Child : CS->children())
1216bf42cfd7SJustin Bogner           Visit(Child);
12177f53fbfcSEli Friedman 
12187f53fbfcSEli Friedman         // Set the end for the body of the switch, if it isn't already set.
12197f53fbfcSEli Friedman         for (size_t i = RegionStack.size(); i != Index; --i) {
12207f53fbfcSEli Friedman           if (!RegionStack[i - 1].hasEndLoc())
12217f53fbfcSEli Friedman             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
12227f53fbfcSEli Friedman         }
12237f53fbfcSEli Friedman 
1224bf42cfd7SJustin Bogner         popRegions(Index);
1225ee02499aSAlex Lorenz       }
122687ea3b05SVedant Kumar     } else
1227bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
1228ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1229bf42cfd7SJustin Bogner 
1230ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
1231ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
1232ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1233bf42cfd7SJustin Bogner 
1234bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
12353836482aSVedant Kumar     SourceLocation ExitLoc = getEnd(S);
123608780529SAlex Lorenz     pushRegion(ExitCount);
123708780529SAlex Lorenz 
123808780529SAlex Lorenz     // Ensure that handleFileExit recognizes when the end location is located
123908780529SAlex Lorenz     // in a different file.
124008780529SAlex Lorenz     MostRecentLocation = getStart(S);
12413836482aSVedant Kumar     handleFileExit(ExitLoc);
1242ee02499aSAlex Lorenz   }
1243ee02499aSAlex Lorenz 
1244bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
1245bf42cfd7SJustin Bogner     extendRegion(S);
1246ee02499aSAlex Lorenz 
1247bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
1248bf42cfd7SJustin Bogner 
1249bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1250bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
1251bf42cfd7SJustin Bogner     // the first case in a switch.
1252a6e4358fSStephen Kelly     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1253bf42cfd7SJustin Bogner       Parent.setCounter(Count);
1254bf42cfd7SJustin Bogner     else
1255bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
1256bf42cfd7SJustin Bogner 
1257376c06c2SSanjay Patel     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1258bf42cfd7SJustin Bogner       Visit(CS->getLHS());
1259bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
1260bf42cfd7SJustin Bogner         Visit(RHS);
1261bf42cfd7SJustin Bogner     }
1262ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1263ee02499aSAlex Lorenz   }
1264ee02499aSAlex Lorenz 
1265ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
1266bf42cfd7SJustin Bogner     extendRegion(S);
12679d2a16b9SVedant Kumar     if (S->getInit())
12689d2a16b9SVedant Kumar       Visit(S->getInit());
12699d2a16b9SVedant Kumar 
1270055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
1271055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
1272055ebc34SJustin Bogner     extendRegion(S->getCond());
1273ee02499aSAlex Lorenz 
1274bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1275bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
1276ee02499aSAlex Lorenz 
127791f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
127891f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
127991f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
128091f2e3c9SJustin Bogner 
12812e8c8759SVedant Kumar     // The 'then' count applies to the area immediately after the condition.
12829500a720SZequan Wu     auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1283fa8fa044SVedant Kumar     if (Gap)
1284fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
12852e8c8759SVedant Kumar 
1286bf42cfd7SJustin Bogner     extendRegion(S->getThen());
1287bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1288bf42cfd7SJustin Bogner 
1289bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1290bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
12912e8c8759SVedant Kumar       // The 'else' count applies to the area immediately after the 'then'.
12929500a720SZequan Wu       Gap = findGapAreaBetween(S->getThen(), Else);
1293fa8fa044SVedant Kumar       if (Gap)
1294fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
12952e8c8759SVedant Kumar       extendRegion(Else);
1296bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1297bf42cfd7SJustin Bogner     } else
1298bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
1299bf42cfd7SJustin Bogner 
1300bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1301bf42cfd7SJustin Bogner       pushRegion(OutCount);
1302ee02499aSAlex Lorenz   }
1303ee02499aSAlex Lorenz 
1304ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
1305bf42cfd7SJustin Bogner     extendRegion(S);
1306049908b2SVedant Kumar     // Handle macros that generate the "try" but not the rest.
1307049908b2SVedant Kumar     extendRegion(S->getTryBlock());
1308049908b2SVedant Kumar 
1309049908b2SVedant Kumar     Counter ParentCount = getRegion().getCounter();
1310049908b2SVedant Kumar     propagateCounts(ParentCount, S->getTryBlock());
1311049908b2SVedant Kumar 
1312ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1313ee02499aSAlex Lorenz       Visit(S->getHandler(I));
1314bf42cfd7SJustin Bogner 
1315bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
1316bf42cfd7SJustin Bogner     pushRegion(ExitCount);
1317ee02499aSAlex Lorenz   }
1318ee02499aSAlex Lorenz 
1319ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1320bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1321ee02499aSAlex Lorenz   }
1322ee02499aSAlex Lorenz 
1323ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1324bf42cfd7SJustin Bogner     extendRegion(E);
1325ee02499aSAlex Lorenz 
1326bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1327bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
1328ee02499aSAlex Lorenz 
1329e3654ce7SJustin Bogner     Visit(E->getCond());
1330e3654ce7SJustin Bogner 
1331e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
13322e8c8759SVedant Kumar       // The 'then' count applies to the area immediately after the condition.
1333fa8fa044SVedant Kumar       auto Gap =
1334fa8fa044SVedant Kumar           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1335fa8fa044SVedant Kumar       if (Gap)
1336fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
13372e8c8759SVedant Kumar 
1338e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
1339bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
1340e3654ce7SJustin Bogner     }
13412e8c8759SVedant Kumar 
1342e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
1343bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
1344bf42cfd7SJustin Bogner                     E->getFalseExpr());
1345ee02499aSAlex Lorenz   }
1346ee02499aSAlex Lorenz 
1347ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
1348e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1349e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1350e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1351bf42cfd7SJustin Bogner 
1352bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1353bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
1354ee02499aSAlex Lorenz   }
1355ee02499aSAlex Lorenz 
1356ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
1357e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1358e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1359e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1360ee02499aSAlex Lorenz 
1361bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1362bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
136301a0d062SAlex Lorenz   }
1364c109102eSJustin Bogner 
1365c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
1366c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
1367c109102eSJustin Bogner     // propagate counts into them.
1368c109102eSJustin Bogner   }
1369ee02499aSAlex Lorenz };
1370ee02499aSAlex Lorenz 
13717cd595dfSReid Kleckner std::string normalizeFilename(StringRef Filename) {
13727cd595dfSReid Kleckner   llvm::SmallString<256> Path(Filename);
13737cd595dfSReid Kleckner   llvm::sys::fs::make_absolute(Path);
13747cd595dfSReid Kleckner   llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1375509e21a1SJonas Devlieghere   return std::string(Path);
13767cd595dfSReid Kleckner }
13777cd595dfSReid Kleckner 
137814f8fb68SVedant Kumar } // end anonymous namespace
137914f8fb68SVedant Kumar 
1380a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1381a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
1382a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
1383a432d176SJustin Bogner   OS << FunctionName << ":\n";
1384a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
1385a432d176SJustin Bogner   for (const auto &R : Regions) {
1386f2cf38e0SAlex Lorenz     OS.indent(2);
1387f2cf38e0SAlex Lorenz     switch (R.Kind) {
1388f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
1389f2cf38e0SAlex Lorenz       break;
1390f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
1391f2cf38e0SAlex Lorenz       OS << "Expansion,";
1392f2cf38e0SAlex Lorenz       break;
1393f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
1394f2cf38e0SAlex Lorenz       OS << "Skipped,";
1395f2cf38e0SAlex Lorenz       break;
1396a1c4deb7SVedant Kumar     case CounterMappingRegion::GapRegion:
1397a1c4deb7SVedant Kumar       OS << "Gap,";
1398a1c4deb7SVedant Kumar       break;
1399f2cf38e0SAlex Lorenz     }
1400f2cf38e0SAlex Lorenz 
14014da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
14024da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1403f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
1404f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
14054da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
14064da909b2SJustin Bogner     OS << "\n";
1407f2cf38e0SAlex Lorenz   }
1408f2cf38e0SAlex Lorenz }
1409f2cf38e0SAlex Lorenz 
1410dd1ea9deSVedant Kumar static std::string getInstrProfSection(const CodeGenModule &CGM,
1411dd1ea9deSVedant Kumar                                        llvm::InstrProfSectKind SK) {
1412dd1ea9deSVedant Kumar   return llvm::getInstrProfSectionName(
1413dd1ea9deSVedant Kumar       SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1414dd1ea9deSVedant Kumar }
1415dd1ea9deSVedant Kumar 
1416dd1ea9deSVedant Kumar void CoverageMappingModuleGen::emitFunctionMappingRecord(
1417dd1ea9deSVedant Kumar     const FunctionInfo &Info, uint64_t FilenamesRef) {
141899317124SVedant Kumar   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1419dd1ea9deSVedant Kumar 
1420dd1ea9deSVedant Kumar   // Assign a name to the function record. This is used to merge duplicates.
1421dd1ea9deSVedant Kumar   std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1422dd1ea9deSVedant Kumar 
1423dd1ea9deSVedant Kumar   // A dummy description for a function included-but-not-used in a TU can be
1424dd1ea9deSVedant Kumar   // replaced by full description provided by a different TU. The two kinds of
1425dd1ea9deSVedant Kumar   // descriptions play distinct roles: therefore, assign them different names
1426dd1ea9deSVedant Kumar   // to prevent `linkonce_odr` merging.
1427dd1ea9deSVedant Kumar   if (Info.IsUsed)
1428dd1ea9deSVedant Kumar     FuncRecordName += "u";
1429dd1ea9deSVedant Kumar 
1430dd1ea9deSVedant Kumar   // Create the function record type.
1431dd1ea9deSVedant Kumar   const uint64_t NameHash = Info.NameHash;
1432dd1ea9deSVedant Kumar   const uint64_t FuncHash = Info.FuncHash;
1433dd1ea9deSVedant Kumar   const std::string &CoverageMapping = Info.CoverageMapping;
143433888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
143533888717SVedant Kumar   llvm::Type *FunctionRecordTypes[] = {
143633888717SVedant Kumar #include "llvm/ProfileData/InstrProfData.inc"
143733888717SVedant Kumar   };
1438dd1ea9deSVedant Kumar   auto *FunctionRecordTy =
143933888717SVedant Kumar       llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
144033888717SVedant Kumar                             /*isPacked=*/true);
144199317124SVedant Kumar 
1442dd1ea9deSVedant Kumar   // Create the function record constant.
144333888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
144433888717SVedant Kumar   llvm::Constant *FunctionRecordVals[] = {
144533888717SVedant Kumar       #include "llvm/ProfileData/InstrProfData.inc"
144633888717SVedant Kumar   };
1447dd1ea9deSVedant Kumar   auto *FuncRecordConstant = llvm::ConstantStruct::get(
1448dd1ea9deSVedant Kumar       FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1449dd1ea9deSVedant Kumar 
1450dd1ea9deSVedant Kumar   // Create the function record global.
1451dd1ea9deSVedant Kumar   auto *FuncRecord = new llvm::GlobalVariable(
1452dd1ea9deSVedant Kumar       CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1453dd1ea9deSVedant Kumar       llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1454dd1ea9deSVedant Kumar       FuncRecordName);
1455dd1ea9deSVedant Kumar   FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1456dd1ea9deSVedant Kumar   FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1457dd1ea9deSVedant Kumar   FuncRecord->setAlignment(llvm::Align(8));
1458dd1ea9deSVedant Kumar   if (CGM.supportsCOMDAT())
1459dd1ea9deSVedant Kumar     FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1460dd1ea9deSVedant Kumar 
1461dd1ea9deSVedant Kumar   // Make sure the data doesn't get deleted.
1462dd1ea9deSVedant Kumar   CGM.addUsedGlobal(FuncRecord);
1463dd1ea9deSVedant Kumar }
1464dd1ea9deSVedant Kumar 
1465dd1ea9deSVedant Kumar void CoverageMappingModuleGen::addFunctionMappingRecord(
1466dd1ea9deSVedant Kumar     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1467dd1ea9deSVedant Kumar     const std::string &CoverageMapping, bool IsUsed) {
1468dd1ea9deSVedant Kumar   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1469dd1ea9deSVedant Kumar   const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1470dd1ea9deSVedant Kumar   FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
1471dd1ea9deSVedant Kumar 
1472848da137SXinliang David Li   if (!IsUsed)
14732129ae53SXinliang David Li     FunctionNames.push_back(
14742129ae53SXinliang David Li         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1475f2cf38e0SAlex Lorenz 
1476f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1477f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1478f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1479f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1480f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1481f2cf38e0SAlex Lorenz     // expressions.
1482f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1483f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1484f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
1485b31ee819SJordan Rose     llvm::SmallVector<std::string, 16> FilenameStrs;
1486f2cf38e0SAlex Lorenz     llvm::SmallVector<StringRef, 16> FilenameRefs;
1487b31ee819SJordan Rose     FilenameStrs.resize(FileEntries.size());
1488f2cf38e0SAlex Lorenz     FilenameRefs.resize(FileEntries.size());
1489b31ee819SJordan Rose     for (const auto &Entry : FileEntries) {
1490b31ee819SJordan Rose       auto I = Entry.second;
1491b31ee819SJordan Rose       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1492b31ee819SJordan Rose       FilenameRefs[I] = FilenameStrs[I];
1493b31ee819SJordan Rose     }
1494a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1495a432d176SJustin Bogner                                     Expressions, Regions);
1496a432d176SJustin Bogner     if (Reader.read())
1497f2cf38e0SAlex Lorenz       return;
1498a026a437SXinliang David Li     dump(llvm::outs(), NameValue, Expressions, Regions);
1499f2cf38e0SAlex Lorenz   }
1500ee02499aSAlex Lorenz }
1501ee02499aSAlex Lorenz 
1502ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1503ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1504ee02499aSAlex Lorenz     return;
1505ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1506ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1507ee02499aSAlex Lorenz 
1508ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1509ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
15109e324dd1SVedant Kumar   llvm::SmallVector<StringRef, 16> FilenameRefs;
1511ee02499aSAlex Lorenz   FilenameStrs.resize(FileEntries.size());
15129e324dd1SVedant Kumar   FilenameRefs.resize(FileEntries.size());
1513ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1514ee02499aSAlex Lorenz     auto I = Entry.second;
151514f8fb68SVedant Kumar     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
15169e324dd1SVedant Kumar     FilenameRefs[I] = FilenameStrs[I];
1517ee02499aSAlex Lorenz   }
1518ee02499aSAlex Lorenz 
1519dd1ea9deSVedant Kumar   std::string Filenames;
1520dd1ea9deSVedant Kumar   {
1521dd1ea9deSVedant Kumar     llvm::raw_string_ostream OS(Filenames);
15229e324dd1SVedant Kumar     CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
15234cd07dbeSSerge Guelton   }
1524dd1ea9deSVedant Kumar   auto *FilenamesVal =
1525dd1ea9deSVedant Kumar       llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1526dd1ea9deSVedant Kumar   const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
15274cd07dbeSSerge Guelton 
1528dd1ea9deSVedant Kumar   // Emit the function records.
1529dd1ea9deSVedant Kumar   for (const FunctionInfo &Info : FunctionRecords)
1530dd1ea9deSVedant Kumar     emitFunctionMappingRecord(Info, FilenamesRef);
1531ee02499aSAlex Lorenz 
1532dd1ea9deSVedant Kumar   const unsigned NRecords = 0;
1533dd1ea9deSVedant Kumar   const size_t FilenamesSize = Filenames.size();
1534dd1ea9deSVedant Kumar   const unsigned CoverageMappingSize = 0;
153520b188c0SXinliang David Li   llvm::Type *CovDataHeaderTypes[] = {
153620b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
153720b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
153820b188c0SXinliang David Li   };
153920b188c0SXinliang David Li   auto CovDataHeaderTy =
154020b188c0SXinliang David Li       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
154120b188c0SXinliang David Li   llvm::Constant *CovDataHeaderVals[] = {
154220b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
154320b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
154420b188c0SXinliang David Li   };
154520b188c0SXinliang David Li   auto CovDataHeaderVal = llvm::ConstantStruct::get(
154620b188c0SXinliang David Li       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
154720b188c0SXinliang David Li 
1548ee02499aSAlex Lorenz   // Create the coverage data record
1549dd1ea9deSVedant Kumar   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
1550ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1551dd1ea9deSVedant Kumar   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
1552ee02499aSAlex Lorenz   auto CovDataVal =
1553ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
155420b188c0SXinliang David Li   auto CovData = new llvm::GlobalVariable(
1555dd1ea9deSVedant Kumar       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
155620b188c0SXinliang David Li       CovDataVal, llvm::getCoverageMappingVarName());
1557ee02499aSAlex Lorenz 
1558dd1ea9deSVedant Kumar   CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
1559c79099e0SGuillaume Chatelet   CovData->setAlignment(llvm::Align(8));
1560ee02499aSAlex Lorenz 
1561ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1562ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
15632129ae53SXinliang David Li   // Create the deferred function records array
15642129ae53SXinliang David Li   if (!FunctionNames.empty()) {
15652129ae53SXinliang David Li     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
15662129ae53SXinliang David Li                                            FunctionNames.size());
15672129ae53SXinliang David Li     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
15682129ae53SXinliang David Li     // This variable will *NOT* be emitted to the object file. It is used
15692129ae53SXinliang David Li     // to pass the list of names referenced to codegen.
15702129ae53SXinliang David Li     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
15712129ae53SXinliang David Li                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
15727077f0afSXinliang David Li                              llvm::getCoverageUnusedNamesVarName());
15732129ae53SXinliang David Li   }
1574ee02499aSAlex Lorenz }
1575ee02499aSAlex Lorenz 
1576ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1577ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1578ee02499aSAlex Lorenz   if (It != FileEntries.end())
1579ee02499aSAlex Lorenz     return It->second;
1580ee02499aSAlex Lorenz   unsigned FileID = FileEntries.size();
1581ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1582ee02499aSAlex Lorenz   return FileID;
1583ee02499aSAlex Lorenz }
1584ee02499aSAlex Lorenz 
1585ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1586ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1587ee02499aSAlex Lorenz   assert(CounterMap);
1588e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1589ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1590ee02499aSAlex Lorenz   Walker.write(OS);
1591ee02499aSAlex Lorenz }
1592ee02499aSAlex Lorenz 
1593ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1594ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1595ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1596ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1597ee02499aSAlex Lorenz   Walker.write(OS);
1598ee02499aSAlex Lorenz }
1599