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"
17*e08464fbSReid Kleckner #include "clang/Basic/FileManager.h"
18dd1ea9deSVedant Kumar #include "clang/Frontend/FrontendDiagnostic.h"
19ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h"
20*e08464fbSReid 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 
34ee02499aSAlex Lorenz using namespace clang;
35ee02499aSAlex Lorenz using namespace CodeGen;
36ee02499aSAlex Lorenz using namespace llvm::coverage;
37ee02499aSAlex Lorenz 
383919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
39ee02499aSAlex Lorenz   SkippedRanges.push_back(Range);
40ee02499aSAlex Lorenz }
41ee02499aSAlex Lorenz 
42ee02499aSAlex Lorenz namespace {
43ee02499aSAlex Lorenz 
449fc8faf9SAdrian Prantl /// A region of source code that can be mapped to a counter.
4509c7179bSJustin Bogner class SourceMappingRegion {
46ee02499aSAlex Lorenz   Counter Count;
47ee02499aSAlex Lorenz 
489fc8faf9SAdrian Prantl   /// The region's starting location.
49bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
50ee02499aSAlex Lorenz 
519fc8faf9SAdrian Prantl   /// The region's ending location.
52bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
53ee02499aSAlex Lorenz 
54747b0e29SVedant Kumar   /// Whether this region should be emitted after its parent is emitted.
55747b0e29SVedant Kumar   bool DeferRegion;
56747b0e29SVedant Kumar 
57a1c4deb7SVedant Kumar   /// Whether this region is a gap region. The count from a gap region is set
58a1c4deb7SVedant Kumar   /// as the line execution count if there are no other regions on the line.
59a1c4deb7SVedant Kumar   bool GapRegion;
60a1c4deb7SVedant Kumar 
6109c7179bSJustin Bogner public:
62bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
63a1c4deb7SVedant Kumar                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
64a1c4deb7SVedant Kumar                       bool GapRegion = false)
65747b0e29SVedant Kumar       : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
66a1c4deb7SVedant Kumar         DeferRegion(DeferRegion), GapRegion(GapRegion) {}
67ee02499aSAlex Lorenz 
6809c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
6909c7179bSJustin Bogner 
70bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
7109c7179bSJustin Bogner 
72bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
73bf42cfd7SJustin Bogner 
74bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
75bf42cfd7SJustin Bogner 
763cffc4c7SStephen Kelly   SourceLocation getBeginLoc() const {
77bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
78bf42cfd7SJustin Bogner     return *LocStart;
7909c7179bSJustin Bogner   }
8009c7179bSJustin Bogner 
81bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
82ee02499aSAlex Lorenz 
83a14a1f92SVedant Kumar   void setEndLoc(SourceLocation Loc) {
84a14a1f92SVedant Kumar     assert(Loc.isValid() && "Setting an invalid end location");
85a14a1f92SVedant Kumar     LocEnd = Loc;
86a14a1f92SVedant Kumar   }
87ee02499aSAlex Lorenz 
88462c77b4SCraig Topper   SourceLocation getEndLoc() const {
89bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
90bf42cfd7SJustin Bogner     return *LocEnd;
91ee02499aSAlex Lorenz   }
92747b0e29SVedant Kumar 
93747b0e29SVedant Kumar   bool isDeferred() const { return DeferRegion; }
94747b0e29SVedant Kumar 
95747b0e29SVedant Kumar   void setDeferred(bool Deferred) { DeferRegion = Deferred; }
96a1c4deb7SVedant Kumar 
97a1c4deb7SVedant Kumar   bool isGap() const { return GapRegion; }
98a1c4deb7SVedant Kumar 
99a1c4deb7SVedant Kumar   void setGap(bool Gap) { GapRegion = Gap; }
100ee02499aSAlex Lorenz };
101ee02499aSAlex Lorenz 
102d7369648SVedant Kumar /// Spelling locations for the start and end of a source region.
103d7369648SVedant Kumar struct SpellingRegion {
104d7369648SVedant Kumar   /// The line where the region starts.
105d7369648SVedant Kumar   unsigned LineStart;
106d7369648SVedant Kumar 
107d7369648SVedant Kumar   /// The column where the region starts.
108d7369648SVedant Kumar   unsigned ColumnStart;
109d7369648SVedant Kumar 
110d7369648SVedant Kumar   /// The line where the region ends.
111d7369648SVedant Kumar   unsigned LineEnd;
112d7369648SVedant Kumar 
113d7369648SVedant Kumar   /// The column where the region ends.
114d7369648SVedant Kumar   unsigned ColumnEnd;
115d7369648SVedant Kumar 
116d7369648SVedant Kumar   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
117d7369648SVedant Kumar                  SourceLocation LocEnd) {
118d7369648SVedant Kumar     LineStart = SM.getSpellingLineNumber(LocStart);
119d7369648SVedant Kumar     ColumnStart = SM.getSpellingColumnNumber(LocStart);
120d7369648SVedant Kumar     LineEnd = SM.getSpellingLineNumber(LocEnd);
121d7369648SVedant Kumar     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
122d7369648SVedant Kumar   }
123d7369648SVedant Kumar 
124fa8fa044SVedant Kumar   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
125a6e4358fSStephen Kelly       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
126fa8fa044SVedant Kumar 
127d7369648SVedant Kumar   /// Check if the start and end locations appear in source order, i.e
128d7369648SVedant Kumar   /// top->bottom, left->right.
129d7369648SVedant Kumar   bool isInSourceOrder() const {
130d7369648SVedant Kumar     return (LineStart < LineEnd) ||
131d7369648SVedant Kumar            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
132d7369648SVedant Kumar   }
133d7369648SVedant Kumar };
134d7369648SVedant Kumar 
1359fc8faf9SAdrian Prantl /// Provides the common functionality for the different
136ee02499aSAlex Lorenz /// coverage mapping region builders.
137ee02499aSAlex Lorenz class CoverageMappingBuilder {
138ee02499aSAlex Lorenz public:
139ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
140ee02499aSAlex Lorenz   SourceManager &SM;
141ee02499aSAlex Lorenz   const LangOptions &LangOpts;
142ee02499aSAlex Lorenz 
143ee02499aSAlex Lorenz private:
1449fc8faf9SAdrian Prantl   /// Map of clang's FileIDs to IDs used for coverage mapping.
145bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
146bf42cfd7SJustin Bogner       FileIDMapping;
147ee02499aSAlex Lorenz 
148ee02499aSAlex Lorenz public:
1499fc8faf9SAdrian Prantl   /// The coverage mapping regions for this function
150ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
1519fc8faf9SAdrian Prantl   /// The source mapping regions for this function.
152f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
153ee02499aSAlex Lorenz 
1549fc8faf9SAdrian Prantl   /// A set of regions which can be used as a filter.
155fc05ee34SIgor Kudrin   ///
156fc05ee34SIgor Kudrin   /// It is produced by emitExpansionRegions() and is used in
157fc05ee34SIgor Kudrin   /// emitSourceRegions() to suppress producing code regions if
158fc05ee34SIgor Kudrin   /// the same area is covered by expansion regions.
159fc05ee34SIgor Kudrin   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
160fc05ee34SIgor Kudrin       SourceRegionFilter;
161fc05ee34SIgor Kudrin 
162ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
163ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
164bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
165ee02499aSAlex Lorenz 
1669fc8faf9SAdrian Prantl   /// Return the precise end location for the given token.
167ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
168bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
169bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
170bf42cfd7SJustin Bogner     unsigned TokLen =
171bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
172bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
173ee02499aSAlex Lorenz   }
174ee02499aSAlex Lorenz 
1759fc8faf9SAdrian Prantl   /// Return the start location of an included file or expanded macro.
176bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
177bf42cfd7SJustin Bogner     if (Loc.isMacroID())
178bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
179bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
180ee02499aSAlex Lorenz   }
181ee02499aSAlex Lorenz 
1829fc8faf9SAdrian Prantl   /// Return the end location of an included file or expanded macro.
183bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
184bf42cfd7SJustin Bogner     if (Loc.isMacroID())
185bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
186f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
187bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
188bf42cfd7SJustin Bogner   }
189ee02499aSAlex Lorenz 
1909fc8faf9SAdrian Prantl   /// Find out where the current file is included or macro is expanded.
191bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
192b5f8171aSRichard Smith     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
193bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
194bf42cfd7SJustin Bogner   }
195bf42cfd7SJustin Bogner 
1969fc8faf9SAdrian Prantl   /// Return true if \c Loc is a location in a built-in macro.
197682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
19899d1b295SMehdi Amini     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
199682bfbf3SJustin Bogner   }
200682bfbf3SJustin Bogner 
2019fc8faf9SAdrian Prantl   /// Check whether \c Loc is included or expanded from \c Parent.
202d9e1a61dSIgor Kudrin   bool isNestedIn(SourceLocation Loc, FileID Parent) {
203d9e1a61dSIgor Kudrin     do {
204d9e1a61dSIgor Kudrin       Loc = getIncludeOrExpansionLoc(Loc);
205d9e1a61dSIgor Kudrin       if (Loc.isInvalid())
206d9e1a61dSIgor Kudrin         return false;
207d9e1a61dSIgor Kudrin     } while (!SM.isInFileID(Loc, Parent));
208d9e1a61dSIgor Kudrin     return true;
209d9e1a61dSIgor Kudrin   }
210d9e1a61dSIgor Kudrin 
2119fc8faf9SAdrian Prantl   /// Get the start of \c S ignoring macro arguments and builtin macros.
212bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
213f2ceec48SStephen Kelly     SourceLocation Loc = S->getBeginLoc();
214682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
215b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
216bf42cfd7SJustin Bogner     return Loc;
217bf42cfd7SJustin Bogner   }
218bf42cfd7SJustin Bogner 
2199fc8faf9SAdrian Prantl   /// Get the end of \c S ignoring macro arguments and builtin macros.
220bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
2211c301dcbSStephen Kelly     SourceLocation Loc = S->getEndLoc();
222682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
223b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
224f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
225bf42cfd7SJustin Bogner   }
226bf42cfd7SJustin Bogner 
2279fc8faf9SAdrian Prantl   /// Find the set of files we have regions for and assign IDs
228bf42cfd7SJustin Bogner   ///
229bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
230bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
231bf42cfd7SJustin Bogner   /// expansion regions.
232bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
233bf42cfd7SJustin Bogner     FileIDMapping.clear();
234bf42cfd7SJustin Bogner 
235bc6b80a0SVedant Kumar     llvm::SmallSet<FileID, 8> Visited;
236bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
237bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
238a6e4358fSStephen Kelly       SourceLocation Loc = Region.getBeginLoc();
239bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
240bc6b80a0SVedant Kumar       if (!Visited.insert(File).second)
241bf42cfd7SJustin Bogner         continue;
242bf42cfd7SJustin Bogner 
24393205af0SVedant Kumar       // Do not map FileID's associated with system headers.
24493205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
24593205af0SVedant Kumar         continue;
24693205af0SVedant Kumar 
247bf42cfd7SJustin Bogner       unsigned Depth = 0;
248bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
249ed1fe5d0SYaron Keren            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
250bf42cfd7SJustin Bogner         ++Depth;
251bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
252bf42cfd7SJustin Bogner     }
253899d1392SFangrui Song     llvm::stable_sort(FileLocs, llvm::less_second());
254bf42cfd7SJustin Bogner 
255bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
256bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
257bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
258ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
259ee02499aSAlex Lorenz       if (!Entry)
260bf42cfd7SJustin Bogner         continue;
261ee02499aSAlex Lorenz 
262bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
263bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
264bf42cfd7SJustin Bogner     }
265ee02499aSAlex Lorenz   }
266ee02499aSAlex Lorenz 
2679fc8faf9SAdrian Prantl   /// Get the coverage mapping file ID for \c Loc.
268bf42cfd7SJustin Bogner   ///
269bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
270bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
271bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
272bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
273bf42cfd7SJustin Bogner       return Mapping->second.first;
274903678caSJustin Bogner     return None;
275ee02499aSAlex Lorenz   }
276ee02499aSAlex Lorenz 
2779fc8faf9SAdrian Prantl   /// Gather all the regions that were skipped by the preprocessor
278ee02499aSAlex Lorenz   /// using the constructs like #if.
279ee02499aSAlex Lorenz   void gatherSkippedRegions() {
280ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
281ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
282ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
283ee02499aSAlex Lorenz     FileLineRanges.resize(
284ee02499aSAlex Lorenz         FileIDMapping.size(),
285ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
286ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
287ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
288ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
289ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
290ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
291ee02499aSAlex Lorenz     }
292ee02499aSAlex Lorenz 
293ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
294ee02499aSAlex Lorenz     for (const auto &I : SkippedRanges) {
295ee02499aSAlex Lorenz       auto LocStart = I.getBegin();
296ee02499aSAlex Lorenz       auto LocEnd = I.getEnd();
297bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
298bf42cfd7SJustin Bogner              "region spans multiple files");
299ee02499aSAlex Lorenz 
300bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
301903678caSJustin Bogner       if (!CovFileID)
302ee02499aSAlex Lorenz         continue;
303d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
304fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
305d7369648SVedant Kumar           *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
306ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
3072a8c18d9SAlexander Kornienko       // the source code of this function.
308903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
309903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
310ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
311ee02499aSAlex Lorenz     }
312ee02499aSAlex Lorenz   }
313ee02499aSAlex Lorenz 
3149fc8faf9SAdrian Prantl   /// Generate the coverage counter mapping regions from collected
315ee02499aSAlex Lorenz   /// source regions.
316fc05ee34SIgor Kudrin   void emitSourceRegions(const SourceRegionFilter &Filter) {
317bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
318bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
319ee02499aSAlex Lorenz 
320a6e4358fSStephen Kelly       SourceLocation LocStart = Region.getBeginLoc();
3218b563665SYaron Keren       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
322f59329b0SJustin Bogner 
32393205af0SVedant Kumar       // Ignore regions from system headers.
32493205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
32593205af0SVedant Kumar         continue;
32693205af0SVedant Kumar 
327bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
328bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
329bf42cfd7SJustin Bogner       if (!CovFileID)
330ee02499aSAlex Lorenz         continue;
331ee02499aSAlex Lorenz 
332f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
333bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
334bf42cfd7SJustin Bogner              "region spans multiple files");
335bf42cfd7SJustin Bogner 
336fc05ee34SIgor Kudrin       // Don't add code regions for the area covered by expansion regions.
337fc05ee34SIgor Kudrin       // This not only suppresses redundant regions, but sometimes prevents
338fc05ee34SIgor Kudrin       // creating regions with wrong counters if, for example, a statement's
339fc05ee34SIgor Kudrin       // body ends at the end of a nested macro.
340fc05ee34SIgor Kudrin       if (Filter.count(std::make_pair(LocStart, LocEnd)))
341fc05ee34SIgor Kudrin         continue;
342fc05ee34SIgor Kudrin 
343d7369648SVedant Kumar       // Find the spelling locations for the mapping region.
344d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
345d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
346a1c4deb7SVedant Kumar 
347a1c4deb7SVedant Kumar       if (Region.isGap()) {
348a1c4deb7SVedant Kumar         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
349a1c4deb7SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
350a1c4deb7SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
351a1c4deb7SVedant Kumar       } else {
352bf42cfd7SJustin Bogner         MappingRegions.push_back(CounterMappingRegion::makeRegion(
353d7369648SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
354d7369648SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
355bf42cfd7SJustin Bogner       }
356bf42cfd7SJustin Bogner     }
357a1c4deb7SVedant Kumar   }
358bf42cfd7SJustin Bogner 
3599fc8faf9SAdrian Prantl   /// Generate expansion regions for each virtual file we've seen.
360fc05ee34SIgor Kudrin   SourceRegionFilter emitExpansionRegions() {
361fc05ee34SIgor Kudrin     SourceRegionFilter Filter;
362bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
363bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
364bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
365bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
366ee02499aSAlex Lorenz         continue;
367ee02499aSAlex Lorenz 
368bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
369bf42cfd7SJustin Bogner       if (!ParentFileID)
370bf42cfd7SJustin Bogner         continue;
371bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
372bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
373bf42cfd7SJustin Bogner 
374bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
375bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
376bf42cfd7SJustin Bogner              "region spans multiple files");
377fc05ee34SIgor Kudrin       Filter.insert(std::make_pair(ParentLoc, LocEnd));
378bf42cfd7SJustin Bogner 
379d7369648SVedant Kumar       SpellingRegion SR{SM, ParentLoc, LocEnd};
380d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
381bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
382d7369648SVedant Kumar           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
383d7369648SVedant Kumar           SR.LineEnd, SR.ColumnEnd));
384ee02499aSAlex Lorenz     }
385fc05ee34SIgor Kudrin     return Filter;
386ee02499aSAlex Lorenz   }
387ee02499aSAlex Lorenz };
388ee02499aSAlex Lorenz 
3899fc8faf9SAdrian Prantl /// Creates unreachable coverage regions for the functions that
390ee02499aSAlex Lorenz /// are not emitted.
391ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
392ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
393ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
394ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
395ee02499aSAlex Lorenz 
396ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
397ee02499aSAlex Lorenz     if (!D->hasBody())
398ee02499aSAlex Lorenz       return;
399ee02499aSAlex Lorenz     auto Body = D->getBody();
400d9e1a61dSIgor Kudrin     SourceLocation Start = getStart(Body);
401d9e1a61dSIgor Kudrin     SourceLocation End = getEnd(Body);
402d9e1a61dSIgor Kudrin     if (!SM.isWrittenInSameFile(Start, End)) {
403d9e1a61dSIgor Kudrin       // Walk up to find the common ancestor.
404d9e1a61dSIgor Kudrin       // Correct the locations accordingly.
405d9e1a61dSIgor Kudrin       FileID StartFileID = SM.getFileID(Start);
406d9e1a61dSIgor Kudrin       FileID EndFileID = SM.getFileID(End);
407d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
408d9e1a61dSIgor Kudrin         Start = getIncludeOrExpansionLoc(Start);
409d9e1a61dSIgor Kudrin         assert(Start.isValid() &&
410d9e1a61dSIgor Kudrin                "Declaration start location not nested within a known region");
411d9e1a61dSIgor Kudrin         StartFileID = SM.getFileID(Start);
412d9e1a61dSIgor Kudrin       }
413d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID) {
414d9e1a61dSIgor Kudrin         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
415d9e1a61dSIgor Kudrin         assert(End.isValid() &&
416d9e1a61dSIgor Kudrin                "Declaration end location not nested within a known region");
417d9e1a61dSIgor Kudrin         EndFileID = SM.getFileID(End);
418d9e1a61dSIgor Kudrin       }
419d9e1a61dSIgor Kudrin     }
420d9e1a61dSIgor Kudrin     SourceRegions.emplace_back(Counter(), Start, End);
421ee02499aSAlex Lorenz   }
422ee02499aSAlex Lorenz 
4239fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
424ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
425ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
426bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
427fc05ee34SIgor Kudrin     emitSourceRegions(SourceRegionFilter());
428ee02499aSAlex Lorenz 
429efd319a2SVedant Kumar     if (MappingRegions.empty())
430efd319a2SVedant Kumar       return;
431efd319a2SVedant Kumar 
4325fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
433ee02499aSAlex Lorenz     Writer.write(OS);
434ee02499aSAlex Lorenz   }
435ee02499aSAlex Lorenz };
436ee02499aSAlex Lorenz 
4379fc8faf9SAdrian Prantl /// A StmtVisitor that creates coverage mapping regions which map
438ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
439ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
440ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
441ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
4429fc8faf9SAdrian Prantl   /// The map of statements to count values.
443ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
444ee02499aSAlex Lorenz 
4459fc8faf9SAdrian Prantl   /// A stack of currently live regions.
446bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
447ee02499aSAlex Lorenz 
448747b0e29SVedant Kumar   /// The currently deferred region: its end location and count can be set once
449747b0e29SVedant Kumar   /// its parent has been popped from the region stack.
450747b0e29SVedant Kumar   Optional<SourceMappingRegion> DeferredRegion;
451747b0e29SVedant Kumar 
452ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
453ee02499aSAlex Lorenz 
4549fc8faf9SAdrian Prantl   /// A location in the most recently visited file or macro.
455bf42cfd7SJustin Bogner   ///
456bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
457bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
458bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
459bf42cfd7SJustin Bogner 
4608046d22aSVedant Kumar   /// Location of the last terminated region.
4618046d22aSVedant Kumar   Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
4628046d22aSVedant Kumar 
4639fc8faf9SAdrian Prantl   /// Return a counter for the subtraction of \c RHS from \c LHS
464ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
465ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
466ee02499aSAlex Lorenz   }
467ee02499aSAlex Lorenz 
4689fc8faf9SAdrian Prantl   /// Return a counter for the sum of \c LHS and \c RHS.
469ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
470ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
471ee02499aSAlex Lorenz   }
472ee02499aSAlex Lorenz 
473bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
474bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
475bf42cfd7SJustin Bogner   }
476bf42cfd7SJustin Bogner 
4779fc8faf9SAdrian Prantl   /// Return the region counter for the given statement.
478bf42cfd7SJustin Bogner   ///
479ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
480bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
481bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
482ee02499aSAlex Lorenz   }
483ee02499aSAlex Lorenz 
4849fc8faf9SAdrian Prantl   /// Push a region onto the stack.
485bf42cfd7SJustin Bogner   ///
486bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
487bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
488bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
489bf42cfd7SJustin Bogner                     Optional<SourceLocation> EndLoc = None) {
490747b0e29SVedant Kumar     if (StartLoc) {
491bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
492747b0e29SVedant Kumar       completeDeferred(Count, MostRecentLocation);
493747b0e29SVedant Kumar     }
494bf42cfd7SJustin Bogner     RegionStack.emplace_back(Count, StartLoc, EndLoc);
495ee02499aSAlex Lorenz 
496bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
497ee02499aSAlex Lorenz   }
498ee02499aSAlex Lorenz 
499747b0e29SVedant Kumar   /// Complete any pending deferred region by setting its end location and
500747b0e29SVedant Kumar   /// count, and then pushing it onto the region stack.
501747b0e29SVedant Kumar   size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
502747b0e29SVedant Kumar     size_t Index = RegionStack.size();
503747b0e29SVedant Kumar     if (!DeferredRegion)
504747b0e29SVedant Kumar       return Index;
505747b0e29SVedant Kumar 
506747b0e29SVedant Kumar     // Consume the pending region.
507747b0e29SVedant Kumar     SourceMappingRegion DR = DeferredRegion.getValue();
508747b0e29SVedant Kumar     DeferredRegion = None;
509747b0e29SVedant Kumar 
510747b0e29SVedant Kumar     // If the region ends in an expansion, find the expansion site.
511a6e4358fSStephen Kelly     FileID StartFile = SM.getFileID(DR.getBeginLoc());
512f9a0d44eSVedant Kumar     if (SM.getFileID(DeferredEndLoc) != StartFile) {
513747b0e29SVedant Kumar       if (isNestedIn(DeferredEndLoc, StartFile)) {
514747b0e29SVedant Kumar         do {
515747b0e29SVedant Kumar           DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
516747b0e29SVedant Kumar         } while (StartFile != SM.getFileID(DeferredEndLoc));
517f9a0d44eSVedant Kumar       } else {
518f9a0d44eSVedant Kumar         return Index;
519747b0e29SVedant Kumar       }
520747b0e29SVedant Kumar     }
521747b0e29SVedant Kumar 
522747b0e29SVedant Kumar     // The parent of this deferred region ends where the containing decl ends,
523747b0e29SVedant Kumar     // so the region isn't useful.
524a6e4358fSStephen Kelly     if (DR.getBeginLoc() == DeferredEndLoc)
525747b0e29SVedant Kumar       return Index;
526747b0e29SVedant Kumar 
527747b0e29SVedant Kumar     // If we're visiting statements in non-source order (e.g switch cases or
528747b0e29SVedant Kumar     // a loop condition) we can't construct a sensible deferred region.
529a6e4358fSStephen Kelly     if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
530747b0e29SVedant Kumar       return Index;
531747b0e29SVedant Kumar 
532a1c4deb7SVedant Kumar     DR.setGap(true);
533747b0e29SVedant Kumar     DR.setCounter(Count);
534747b0e29SVedant Kumar     DR.setEndLoc(DeferredEndLoc);
535747b0e29SVedant Kumar     handleFileExit(DeferredEndLoc);
536747b0e29SVedant Kumar     RegionStack.push_back(DR);
537747b0e29SVedant Kumar     return Index;
538747b0e29SVedant Kumar   }
539747b0e29SVedant Kumar 
5408046d22aSVedant Kumar   /// Complete a deferred region created after a terminated region at the
5418046d22aSVedant Kumar   /// top-level.
5428046d22aSVedant Kumar   void completeTopLevelDeferredRegion(Counter Count,
5438046d22aSVedant Kumar                                       SourceLocation DeferredEndLoc) {
5448046d22aSVedant Kumar     if (DeferredRegion || !LastTerminatedRegion)
5458046d22aSVedant Kumar       return;
5468046d22aSVedant Kumar 
5478046d22aSVedant Kumar     if (LastTerminatedRegion->second != RegionStack.size())
5488046d22aSVedant Kumar       return;
5498046d22aSVedant Kumar 
5508046d22aSVedant Kumar     SourceLocation Start = LastTerminatedRegion->first;
5518046d22aSVedant Kumar     if (SM.getFileID(Start) != SM.getMainFileID())
5528046d22aSVedant Kumar       return;
5538046d22aSVedant Kumar 
5548046d22aSVedant Kumar     SourceMappingRegion DR = RegionStack.back();
5558046d22aSVedant Kumar     DR.setStartLoc(Start);
5568046d22aSVedant Kumar     DR.setDeferred(false);
5578046d22aSVedant Kumar     DeferredRegion = DR;
5588046d22aSVedant Kumar     completeDeferred(Count, DeferredEndLoc);
5598046d22aSVedant Kumar   }
5608046d22aSVedant Kumar 
5610c3e3115SVedant Kumar   size_t locationDepth(SourceLocation Loc) {
5620c3e3115SVedant Kumar     size_t Depth = 0;
5630c3e3115SVedant Kumar     while (Loc.isValid()) {
5640c3e3115SVedant Kumar       Loc = getIncludeOrExpansionLoc(Loc);
5650c3e3115SVedant Kumar       Depth++;
5660c3e3115SVedant Kumar     }
5670c3e3115SVedant Kumar     return Depth;
5680c3e3115SVedant Kumar   }
5690c3e3115SVedant Kumar 
5709fc8faf9SAdrian Prantl   /// Pop regions from the stack into the function's list of regions.
571bf42cfd7SJustin Bogner   ///
572bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
573bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
574bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
575bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
576747b0e29SVedant Kumar     bool ParentOfDeferredRegion = false;
577bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
578bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
579bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
580a6e4358fSStephen Kelly         SourceLocation StartLoc = Region.getBeginLoc();
581bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
582bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
583bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
5840c3e3115SVedant Kumar         size_t StartDepth = locationDepth(StartLoc);
5850c3e3115SVedant Kumar         size_t EndDepth = locationDepth(EndLoc);
586bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
5870c3e3115SVedant Kumar           bool UnnestStart = StartDepth >= EndDepth;
5880c3e3115SVedant Kumar           bool UnnestEnd = EndDepth >= StartDepth;
5890c3e3115SVedant Kumar           if (UnnestEnd) {
590bf42cfd7SJustin Bogner             // The region ends in a nested file or macro expansion. Create a
591bf42cfd7SJustin Bogner             // separate region for each expansion.
592bf42cfd7SJustin Bogner             SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
593bf42cfd7SJustin Bogner             assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
594bf42cfd7SJustin Bogner 
5958545dae2SIgor Kudrin             if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
596bf42cfd7SJustin Bogner               SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
597bf42cfd7SJustin Bogner 
598f14b2078SJustin Bogner             EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
599dceaaadfSJustin Bogner             if (EndLoc.isInvalid())
600dceaaadfSJustin Bogner               llvm::report_fatal_error("File exit not handled before popRegions");
6010c3e3115SVedant Kumar             EndDepth--;
602bf42cfd7SJustin Bogner           }
6030c3e3115SVedant Kumar           if (UnnestStart) {
6040c3e3115SVedant Kumar             // The region begins in a nested file or macro expansion. Create a
6050c3e3115SVedant Kumar             // separate region for each expansion.
6060c3e3115SVedant Kumar             SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
6070c3e3115SVedant Kumar             assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
6080c3e3115SVedant Kumar 
6090c3e3115SVedant Kumar             if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
6100c3e3115SVedant Kumar               SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
6110c3e3115SVedant Kumar 
6120c3e3115SVedant Kumar             StartLoc = getIncludeOrExpansionLoc(StartLoc);
6130c3e3115SVedant Kumar             if (StartLoc.isInvalid())
6140c3e3115SVedant Kumar               llvm::report_fatal_error("File exit not handled before popRegions");
6150c3e3115SVedant Kumar             StartDepth--;
6160c3e3115SVedant Kumar           }
6170c3e3115SVedant Kumar         }
6180c3e3115SVedant Kumar         Region.setStartLoc(StartLoc);
619bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
620bf42cfd7SJustin Bogner 
621bf42cfd7SJustin Bogner         MostRecentLocation = EndLoc;
622bf42cfd7SJustin Bogner         // If this region happens to span an entire expansion, we need to make
623bf42cfd7SJustin Bogner         // sure we don't overlap the parent region with it.
624bf42cfd7SJustin Bogner         if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
625bf42cfd7SJustin Bogner             EndLoc == getEndOfFileOrMacro(EndLoc))
626bf42cfd7SJustin Bogner           MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
627bf42cfd7SJustin Bogner 
628a6e4358fSStephen Kelly         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
629fa8fa044SVedant Kumar         assert(SpellingRegion(SM, Region).isInSourceOrder());
630f36a5c4aSCraig Topper         SourceRegions.push_back(Region);
631747b0e29SVedant Kumar 
632747b0e29SVedant Kumar         if (ParentOfDeferredRegion) {
633747b0e29SVedant Kumar           ParentOfDeferredRegion = false;
634747b0e29SVedant Kumar 
635747b0e29SVedant Kumar           // If there's an existing deferred region, keep the old one, because
636747b0e29SVedant Kumar           // it means there are two consecutive returns (or a similar pattern).
637747b0e29SVedant Kumar           if (!DeferredRegion.hasValue() &&
638747b0e29SVedant Kumar               // File IDs aren't gathered within macro expansions, so it isn't
639747b0e29SVedant Kumar               // useful to try and create a deferred region inside of one.
640f9a0d44eSVedant Kumar               !EndLoc.isMacroID())
641747b0e29SVedant Kumar             DeferredRegion =
642747b0e29SVedant Kumar                 SourceMappingRegion(Counter::getZero(), EndLoc, None);
643747b0e29SVedant Kumar         }
644747b0e29SVedant Kumar       } else if (Region.isDeferred()) {
645747b0e29SVedant Kumar         assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
646747b0e29SVedant Kumar         ParentOfDeferredRegion = true;
647bf42cfd7SJustin Bogner       }
648bf42cfd7SJustin Bogner       RegionStack.pop_back();
6498046d22aSVedant Kumar 
6508046d22aSVedant Kumar       // If the zero region pushed after the last terminated region no longer
6518046d22aSVedant Kumar       // exists, clear its cached information.
6528046d22aSVedant Kumar       if (LastTerminatedRegion &&
6538046d22aSVedant Kumar           RegionStack.size() < LastTerminatedRegion->second)
6548046d22aSVedant Kumar         LastTerminatedRegion = None;
655bf42cfd7SJustin Bogner     }
656747b0e29SVedant Kumar     assert(!ParentOfDeferredRegion && "Deferred region with no parent");
657ee02499aSAlex Lorenz   }
658ee02499aSAlex Lorenz 
6599fc8faf9SAdrian Prantl   /// Return the currently active region.
660bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
661bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
662bf42cfd7SJustin Bogner     return RegionStack.back();
663ee02499aSAlex Lorenz   }
664ee02499aSAlex Lorenz 
6657225a261SVedant Kumar   /// Propagate counts through the children of \p S if \p VisitChildren is true.
6667225a261SVedant Kumar   /// Otherwise, only emit a count for \p S itself.
6677225a261SVedant Kumar   Counter propagateCounts(Counter TopCount, const Stmt *S,
6687225a261SVedant Kumar                           bool VisitChildren = true) {
6697838696eSVedant Kumar     SourceLocation StartLoc = getStart(S);
6707838696eSVedant Kumar     SourceLocation EndLoc = getEnd(S);
6717838696eSVedant Kumar     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
6727225a261SVedant Kumar     if (VisitChildren)
673bf42cfd7SJustin Bogner       Visit(S);
674bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
675bf42cfd7SJustin Bogner     popRegions(Index);
67639f01975SVedant Kumar 
67739f01975SVedant Kumar     // The statement may be spanned by an expansion. Make sure we handle a file
67839f01975SVedant Kumar     // exit out of this expansion before moving to the next statement.
679f2ceec48SStephen Kelly     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
6807838696eSVedant Kumar       MostRecentLocation = EndLoc;
68139f01975SVedant Kumar 
682bf42cfd7SJustin Bogner     return ExitCount;
683ee02499aSAlex Lorenz   }
684ee02499aSAlex Lorenz 
6859fc8faf9SAdrian Prantl   /// Check whether a region with bounds \c StartLoc and \c EndLoc
6860a7c9d11SIgor Kudrin   /// is already added to \c SourceRegions.
6870a7c9d11SIgor Kudrin   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
6880a7c9d11SIgor Kudrin     return SourceRegions.rend() !=
6890a7c9d11SIgor Kudrin            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
6900a7c9d11SIgor Kudrin                         [&](const SourceMappingRegion &Region) {
691a6e4358fSStephen Kelly                           return Region.getBeginLoc() == StartLoc &&
6920a7c9d11SIgor Kudrin                                  Region.getEndLoc() == EndLoc;
6930a7c9d11SIgor Kudrin                         });
6940a7c9d11SIgor Kudrin   }
6950a7c9d11SIgor Kudrin 
6969fc8faf9SAdrian Prantl   /// Adjust the most recently visited location to \c EndLoc.
697bf42cfd7SJustin Bogner   ///
698bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
699bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
700bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
7010a7c9d11SIgor Kudrin     // The code region for a whole macro is created in handleFileExit() when
7020a7c9d11SIgor Kudrin     // it detects exiting of the virtual file of that macro. If we visited
7030a7c9d11SIgor Kudrin     // statements in non-source order, we might already have such a region
7040a7c9d11SIgor Kudrin     // added, for example, if a body of a loop is divided among multiple
7050a7c9d11SIgor Kudrin     // macros. Avoid adding duplicate regions in such case.
70696ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
7070a7c9d11SIgor Kudrin         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
7080a7c9d11SIgor Kudrin         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
7090a7c9d11SIgor Kudrin                              MostRecentLocation))
710bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
711ee02499aSAlex Lorenz   }
712ee02499aSAlex Lorenz 
7139fc8faf9SAdrian Prantl   /// Adjust regions and state when \c NewLoc exits a file.
714bf42cfd7SJustin Bogner   ///
715bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
716bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
717bf42cfd7SJustin Bogner   /// for the exited file.
718bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
719e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
720e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
721bf42cfd7SJustin Bogner       return;
722bf42cfd7SJustin Bogner 
723bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
724bf42cfd7SJustin Bogner     // find the common ancestor.
725bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
726bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
727bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
728bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
729bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
730bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
731bf42cfd7SJustin Bogner         // to adjust our location to the new file.
732bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
733bf42cfd7SJustin Bogner         return;
734bf42cfd7SJustin Bogner       }
735bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
736ee02499aSAlex Lorenz     }
737ee02499aSAlex Lorenz 
738bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
739bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
74057d3f145SPete Cooper     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
74157d3f145SPete Cooper       if (!I.hasStartLoc())
742bf42cfd7SJustin Bogner         continue;
743a6e4358fSStephen Kelly       SourceLocation Loc = I.getBeginLoc();
744bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
74557d3f145SPete Cooper         ParentCounter = I.getCounter();
746bf42cfd7SJustin Bogner         break;
747ee02499aSAlex Lorenz       }
748bf42cfd7SJustin Bogner 
749bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
750bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
751bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
752bf42cfd7SJustin Bogner         // we've seen this region.
753bf42cfd7SJustin Bogner         if (StartLocs.insert(Loc).second)
75457d3f145SPete Cooper           SourceRegions.emplace_back(I.getCounter(), Loc,
755bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
756bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
757ee02499aSAlex Lorenz       }
75857d3f145SPete Cooper       I.setStartLoc(getPreciseTokenLocEnd(Loc));
759bf42cfd7SJustin Bogner     }
760bf42cfd7SJustin Bogner 
761bf42cfd7SJustin Bogner     if (ParentCounter) {
762bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
763bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
764bf42cfd7SJustin Bogner       // corresponding to the parent.
765bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
766bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
767bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
768fa8fa044SVedant Kumar         if (StartLocs.insert(FileStart).second) {
769bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
770bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
771fa8fa044SVedant Kumar           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
772fa8fa044SVedant Kumar         }
773bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
774bf42cfd7SJustin Bogner       }
775bf42cfd7SJustin Bogner     }
776bf42cfd7SJustin Bogner 
777bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
778bf42cfd7SJustin Bogner   }
779bf42cfd7SJustin Bogner 
7809fc8faf9SAdrian Prantl   /// Ensure that \c S is included in the current region.
781bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
782bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
783bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
784bf42cfd7SJustin Bogner 
785bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
786bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
787bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
788747b0e29SVedant Kumar 
789747b0e29SVedant Kumar     completeDeferred(Region.getCounter(), StartLoc);
790bf42cfd7SJustin Bogner   }
791bf42cfd7SJustin Bogner 
7929fc8faf9SAdrian Prantl   /// Mark \c S as a terminator, starting a zero region.
793bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
794bf42cfd7SJustin Bogner     extendRegion(S);
795bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
7968046d22aSVedant Kumar     SourceLocation EndLoc = getEnd(S);
797bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
7988046d22aSVedant Kumar       Region.setEndLoc(EndLoc);
799bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
8008046d22aSVedant Kumar     auto &ZeroRegion = getRegion();
8018046d22aSVedant Kumar     ZeroRegion.setDeferred(true);
8028046d22aSVedant Kumar     LastTerminatedRegion = {EndLoc, RegionStack.size()};
803bf42cfd7SJustin Bogner   }
804ee02499aSAlex Lorenz 
805fa8fa044SVedant Kumar   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
806fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
807fa8fa044SVedant Kumar                                            SourceLocation BeforeLoc) {
808fa8fa044SVedant Kumar     // If the start and end locations of the gap are both within the same macro
809fa8fa044SVedant Kumar     // file, the range may not be in source order.
810fa8fa044SVedant Kumar     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
811fa8fa044SVedant Kumar       return None;
812fa8fa044SVedant Kumar     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
813fa8fa044SVedant Kumar       return None;
814fa8fa044SVedant Kumar     return {{AfterLoc, BeforeLoc}};
815fa8fa044SVedant Kumar   }
816fa8fa044SVedant Kumar 
817fa8fa044SVedant Kumar   /// Find the source range after \p AfterStmt and before \p BeforeStmt.
818fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
819fa8fa044SVedant Kumar                                            const Stmt *BeforeStmt) {
820fa8fa044SVedant Kumar     return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
821fa8fa044SVedant Kumar                               getStart(BeforeStmt));
822fa8fa044SVedant Kumar   }
823fa8fa044SVedant Kumar 
8242e8c8759SVedant Kumar   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
8252e8c8759SVedant Kumar   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
8262e8c8759SVedant Kumar                             Counter Count) {
827fa8fa044SVedant Kumar     if (StartLoc == EndLoc)
8282e8c8759SVedant Kumar       return;
829fa8fa044SVedant Kumar     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
8302e8c8759SVedant Kumar     handleFileExit(StartLoc);
8312e8c8759SVedant Kumar     size_t Index = pushRegion(Count, StartLoc, EndLoc);
8322e8c8759SVedant Kumar     getRegion().setGap(true);
8332e8c8759SVedant Kumar     handleFileExit(EndLoc);
8342e8c8759SVedant Kumar     popRegions(Index);
8352e8c8759SVedant Kumar   }
8362e8c8759SVedant Kumar 
8379fc8faf9SAdrian Prantl   /// Keep counts of breaks and continues inside loops.
838ee02499aSAlex Lorenz   struct BreakContinue {
839ee02499aSAlex Lorenz     Counter BreakCount;
840ee02499aSAlex Lorenz     Counter ContinueCount;
841ee02499aSAlex Lorenz   };
842ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
843ee02499aSAlex Lorenz 
844ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
845ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
846e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
847ee02499aSAlex Lorenz       const LangOptions &LangOpts)
848747b0e29SVedant Kumar       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
849747b0e29SVedant Kumar         DeferredRegion(None) {}
850ee02499aSAlex Lorenz 
8519fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
852ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
853ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
854bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
855fc05ee34SIgor Kudrin     SourceRegionFilter Filter = emitExpansionRegions();
856747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
857fc05ee34SIgor Kudrin     emitSourceRegions(Filter);
858ee02499aSAlex Lorenz     gatherSkippedRegions();
859ee02499aSAlex Lorenz 
860efd319a2SVedant Kumar     if (MappingRegions.empty())
861efd319a2SVedant Kumar       return;
862efd319a2SVedant Kumar 
8634da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
8644da909b2SJustin Bogner                                  MappingRegions);
865ee02499aSAlex Lorenz     Writer.write(OS);
866ee02499aSAlex Lorenz   }
867ee02499aSAlex Lorenz 
868ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
869f2ceec48SStephen Kelly     if (S->getBeginLoc().isValid())
870bf42cfd7SJustin Bogner       extendRegion(S);
871642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
872642f173aSBenjamin Kramer       if (Child)
873642f173aSBenjamin Kramer         this->Visit(Child);
874bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
875ee02499aSAlex Lorenz   }
876ee02499aSAlex Lorenz 
877ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
878747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
879747b0e29SVedant Kumar 
880bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
881efd319a2SVedant Kumar 
882efd319a2SVedant Kumar     // Do not propagate region counts into system headers.
883efd319a2SVedant Kumar     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
884efd319a2SVedant Kumar       return;
885efd319a2SVedant Kumar 
8867225a261SVedant Kumar     // Do not visit the artificial children nodes of defaulted methods. The
8877225a261SVedant Kumar     // lexer may not be able to report back precise token end locations for
8887225a261SVedant Kumar     // these children nodes (llvm.org/PR39822), and moreover users will not be
8897225a261SVedant Kumar     // able to see coverage for them.
8907225a261SVedant Kumar     bool Defaulted = false;
8917225a261SVedant Kumar     if (auto *Method = dyn_cast<CXXMethodDecl>(D))
8927225a261SVedant Kumar       Defaulted = Method->isDefaulted();
8937225a261SVedant Kumar 
8947225a261SVedant Kumar     propagateCounts(getRegionCounter(Body), Body,
8957225a261SVedant Kumar                     /*VisitChildren=*/!Defaulted);
896747b0e29SVedant Kumar     assert(RegionStack.empty() && "Regions entered but never exited");
897747b0e29SVedant Kumar 
89861763b65SVedant Kumar     // Discard the last uncompleted deferred region in a decl, if one exists.
89961763b65SVedant Kumar     // This prevents lines at the end of a function containing only whitespace
90061763b65SVedant Kumar     // or closing braces from being marked as uncovered.
901ef8e05ffSVedant Kumar     DeferredRegion = None;
902341bf429SVedant Kumar   }
903ee02499aSAlex Lorenz 
904ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
905bf42cfd7SJustin Bogner     extendRegion(S);
906ee02499aSAlex Lorenz     if (S->getRetValue())
907ee02499aSAlex Lorenz       Visit(S->getRetValue());
908bf42cfd7SJustin Bogner     terminateRegion(S);
909ee02499aSAlex Lorenz   }
910ee02499aSAlex Lorenz 
911f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
912f959febfSJustin Bogner     extendRegion(E);
913f959febfSJustin Bogner     if (E->getSubExpr())
914f959febfSJustin Bogner       Visit(E->getSubExpr());
915f959febfSJustin Bogner     terminateRegion(E);
916f959febfSJustin Bogner   }
917f959febfSJustin Bogner 
918bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
919ee02499aSAlex Lorenz 
920ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
9218046d22aSVedant Kumar     Counter LabelCount = getRegionCounter(S);
922bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
9238046d22aSVedant Kumar     completeTopLevelDeferredRegion(LabelCount, Start);
924d781d97eSVedant Kumar     completeDeferred(LabelCount, Start);
925bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
926bf42cfd7SJustin Bogner     handleFileExit(Start);
9278046d22aSVedant Kumar     pushRegion(LabelCount, Start);
928ee02499aSAlex Lorenz     Visit(S->getSubStmt());
929ee02499aSAlex Lorenz   }
930ee02499aSAlex Lorenz 
931ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
932ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
933ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
934bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
9357f53fbfcSEli Friedman     // FIXME: a break in a switch should terminate regions for all preceding
9367f53fbfcSEli Friedman     // case statements, not just the most recent one.
937bf42cfd7SJustin Bogner     terminateRegion(S);
938ee02499aSAlex Lorenz   }
939ee02499aSAlex Lorenz 
940ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
941ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
942ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
943bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
944bf42cfd7SJustin Bogner     terminateRegion(S);
945ee02499aSAlex Lorenz   }
946ee02499aSAlex Lorenz 
947181dfe4cSEli Friedman   void VisitCallExpr(const CallExpr *E) {
948181dfe4cSEli Friedman     VisitStmt(E);
949181dfe4cSEli Friedman 
950181dfe4cSEli Friedman     // Terminate the region when we hit a noreturn function.
951181dfe4cSEli Friedman     // (This is helpful dealing with switch statements.)
952181dfe4cSEli Friedman     QualType CalleeType = E->getCallee()->getType();
953181dfe4cSEli Friedman     if (getFunctionExtInfo(*CalleeType).getNoReturn())
954181dfe4cSEli Friedman       terminateRegion(E);
955181dfe4cSEli Friedman   }
956181dfe4cSEli Friedman 
957ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
958bf42cfd7SJustin Bogner     extendRegion(S);
959ee02499aSAlex Lorenz 
960bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
961bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
962bf42cfd7SJustin Bogner 
963bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
964bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
965bf42cfd7SJustin Bogner     extendRegion(S->getBody());
966bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
967ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
968bf42cfd7SJustin Bogner 
969bf42cfd7SJustin Bogner     // Go back to handle the condition.
970bf42cfd7SJustin Bogner     Counter CondCount =
971bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
972bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
973bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
974bf42cfd7SJustin Bogner 
975fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
976fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
977fa8fa044SVedant Kumar     if (Gap)
978fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
979fa8fa044SVedant Kumar 
980bf42cfd7SJustin Bogner     Counter OutCount =
981bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
982bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
983bf42cfd7SJustin Bogner       pushRegion(OutCount);
984ee02499aSAlex Lorenz   }
985ee02499aSAlex Lorenz 
986ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
987bf42cfd7SJustin Bogner     extendRegion(S);
988ee02499aSAlex Lorenz 
989bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
990bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
991bf42cfd7SJustin Bogner 
992bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
993bf42cfd7SJustin Bogner     extendRegion(S->getBody());
994bf42cfd7SJustin Bogner     Counter BackedgeCount =
995bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
996ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
997bf42cfd7SJustin Bogner 
998bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
999bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
1000bf42cfd7SJustin Bogner 
1001bf42cfd7SJustin Bogner     Counter OutCount =
1002bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1003bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1004bf42cfd7SJustin Bogner       pushRegion(OutCount);
1005ee02499aSAlex Lorenz   }
1006ee02499aSAlex Lorenz 
1007ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
1008bf42cfd7SJustin Bogner     extendRegion(S);
1009ee02499aSAlex Lorenz     if (S->getInit())
1010ee02499aSAlex Lorenz       Visit(S->getInit());
1011ee02499aSAlex Lorenz 
1012bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1013bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1014bf42cfd7SJustin Bogner 
10153e2ae49aSVedant Kumar     // The loop increment may contain a break or continue.
10163e2ae49aSVedant Kumar     if (S->getInc())
10173e2ae49aSVedant Kumar       BreakContinueStack.emplace_back();
10183e2ae49aSVedant Kumar 
1019bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
10203e2ae49aSVedant Kumar     BreakContinueStack.emplace_back();
1021bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1022bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
10233e2ae49aSVedant Kumar     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1024ee02499aSAlex Lorenz 
1025ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
1026ee02499aSAlex Lorenz     // the count for all the continue statements.
10273e2ae49aSVedant Kumar     BreakContinue IncrementBC;
10283e2ae49aSVedant Kumar     if (const Stmt *Inc = S->getInc()) {
10293e2ae49aSVedant Kumar       propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
10303e2ae49aSVedant Kumar       IncrementBC = BreakContinueStack.pop_back_val();
10313e2ae49aSVedant Kumar     }
1032bf42cfd7SJustin Bogner 
1033bf42cfd7SJustin Bogner     // Go back to handle the condition.
10343e2ae49aSVedant Kumar     Counter CondCount = addCounters(
10353e2ae49aSVedant Kumar         addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
10363e2ae49aSVedant Kumar         IncrementBC.ContinueCount);
1037bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
1038bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
1039bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
1040ee02499aSAlex Lorenz     }
1041ee02499aSAlex Lorenz 
1042fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
1043fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1044fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1045fa8fa044SVedant Kumar     if (Gap)
1046fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1047fa8fa044SVedant Kumar 
10483e2ae49aSVedant Kumar     Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
10493e2ae49aSVedant Kumar                                    subtractCounters(CondCount, BodyCount));
1050bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1051bf42cfd7SJustin Bogner       pushRegion(OutCount);
1052ee02499aSAlex Lorenz   }
1053ee02499aSAlex Lorenz 
1054ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1055bf42cfd7SJustin Bogner     extendRegion(S);
10568baa5001SRichard Smith     if (S->getInit())
10578baa5001SRichard Smith       Visit(S->getInit());
1058bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
1059ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
1060bf42cfd7SJustin Bogner 
1061bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1062bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1063bf42cfd7SJustin Bogner 
1064ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1065bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1066bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1067ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1068bf42cfd7SJustin Bogner 
1069fa8fa044SVedant Kumar     // The body count applies to the area immediately after the range.
1070fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1071fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1072fa8fa044SVedant Kumar     if (Gap)
1073fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1074fa8fa044SVedant Kumar 
10751587432dSJustin Bogner     Counter LoopCount =
10761587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
10771587432dSJustin Bogner     Counter OutCount =
10781587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1079bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1080bf42cfd7SJustin Bogner       pushRegion(OutCount);
1081ee02499aSAlex Lorenz   }
1082ee02499aSAlex Lorenz 
1083ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1084bf42cfd7SJustin Bogner     extendRegion(S);
1085ee02499aSAlex Lorenz     Visit(S->getElement());
1086bf42cfd7SJustin Bogner 
1087bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1088bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1089bf42cfd7SJustin Bogner 
1090ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1091bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1092bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1093ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1094bf42cfd7SJustin Bogner 
1095fa8fa044SVedant Kumar     // The body count applies to the area immediately after the collection.
1096fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1097fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1098fa8fa044SVedant Kumar     if (Gap)
1099fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1100fa8fa044SVedant Kumar 
11011587432dSJustin Bogner     Counter LoopCount =
11021587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
11031587432dSJustin Bogner     Counter OutCount =
11041587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1105bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1106bf42cfd7SJustin Bogner       pushRegion(OutCount);
1107ee02499aSAlex Lorenz   }
1108ee02499aSAlex Lorenz 
1109ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
1110bf42cfd7SJustin Bogner     extendRegion(S);
1111f2a6ec55SVedant Kumar     if (S->getInit())
1112f2a6ec55SVedant Kumar       Visit(S->getInit());
1113ee02499aSAlex Lorenz     Visit(S->getCond());
1114bf42cfd7SJustin Bogner 
1115ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1116bf42cfd7SJustin Bogner 
1117bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
1118bf42cfd7SJustin Bogner     extendRegion(Body);
1119bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1120bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
11217f53fbfcSEli Friedman         // Make a region for the body of the switch.  If the body starts with
11227f53fbfcSEli Friedman         // a case, that case will reuse this region; otherwise, this covers
11237f53fbfcSEli Friedman         // the unreachable code at the beginning of the switch body.
1124859bf4d2SVedant Kumar         size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1125859bf4d2SVedant Kumar         getRegion().setGap(true);
1126b5841332SRichard Trieu         for (const auto *Child : CS->children())
1127bf42cfd7SJustin Bogner           Visit(Child);
11287f53fbfcSEli Friedman 
11297f53fbfcSEli Friedman         // Set the end for the body of the switch, if it isn't already set.
11307f53fbfcSEli Friedman         for (size_t i = RegionStack.size(); i != Index; --i) {
11317f53fbfcSEli Friedman           if (!RegionStack[i - 1].hasEndLoc())
11327f53fbfcSEli Friedman             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
11337f53fbfcSEli Friedman         }
11347f53fbfcSEli Friedman 
1135bf42cfd7SJustin Bogner         popRegions(Index);
1136ee02499aSAlex Lorenz       }
113787ea3b05SVedant Kumar     } else
1138bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
1139ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1140bf42cfd7SJustin Bogner 
1141ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
1142ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
1143ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1144bf42cfd7SJustin Bogner 
1145bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
11463836482aSVedant Kumar     SourceLocation ExitLoc = getEnd(S);
114708780529SAlex Lorenz     pushRegion(ExitCount);
114808780529SAlex Lorenz 
114908780529SAlex Lorenz     // Ensure that handleFileExit recognizes when the end location is located
115008780529SAlex Lorenz     // in a different file.
115108780529SAlex Lorenz     MostRecentLocation = getStart(S);
11523836482aSVedant Kumar     handleFileExit(ExitLoc);
1153ee02499aSAlex Lorenz   }
1154ee02499aSAlex Lorenz 
1155bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
1156bf42cfd7SJustin Bogner     extendRegion(S);
1157ee02499aSAlex Lorenz 
1158bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
1159bf42cfd7SJustin Bogner 
1160bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1161bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
1162bf42cfd7SJustin Bogner     // the first case in a switch.
1163a6e4358fSStephen Kelly     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1164bf42cfd7SJustin Bogner       Parent.setCounter(Count);
1165bf42cfd7SJustin Bogner     else
1166bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
1167bf42cfd7SJustin Bogner 
1168376c06c2SSanjay Patel     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1169bf42cfd7SJustin Bogner       Visit(CS->getLHS());
1170bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
1171bf42cfd7SJustin Bogner         Visit(RHS);
1172bf42cfd7SJustin Bogner     }
1173ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1174ee02499aSAlex Lorenz   }
1175ee02499aSAlex Lorenz 
1176ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
1177bf42cfd7SJustin Bogner     extendRegion(S);
11789d2a16b9SVedant Kumar     if (S->getInit())
11799d2a16b9SVedant Kumar       Visit(S->getInit());
11809d2a16b9SVedant Kumar 
1181055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
1182055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
1183055ebc34SJustin Bogner     extendRegion(S->getCond());
1184ee02499aSAlex Lorenz 
1185bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1186bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
1187ee02499aSAlex Lorenz 
118891f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
118991f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
119091f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
119191f2e3c9SJustin Bogner 
11922e8c8759SVedant Kumar     // The 'then' count applies to the area immediately after the condition.
1193fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1194fa8fa044SVedant Kumar     if (Gap)
1195fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
11962e8c8759SVedant Kumar 
1197bf42cfd7SJustin Bogner     extendRegion(S->getThen());
1198bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1199bf42cfd7SJustin Bogner 
1200bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1201bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
12022e8c8759SVedant Kumar       // The 'else' count applies to the area immediately after the 'then'.
1203fa8fa044SVedant Kumar       Gap = findGapAreaBetween(S->getThen(), Else);
1204fa8fa044SVedant Kumar       if (Gap)
1205fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
12062e8c8759SVedant Kumar       extendRegion(Else);
1207bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1208bf42cfd7SJustin Bogner     } else
1209bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
1210bf42cfd7SJustin Bogner 
1211bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1212bf42cfd7SJustin Bogner       pushRegion(OutCount);
1213ee02499aSAlex Lorenz   }
1214ee02499aSAlex Lorenz 
1215ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
1216bf42cfd7SJustin Bogner     extendRegion(S);
1217049908b2SVedant Kumar     // Handle macros that generate the "try" but not the rest.
1218049908b2SVedant Kumar     extendRegion(S->getTryBlock());
1219049908b2SVedant Kumar 
1220049908b2SVedant Kumar     Counter ParentCount = getRegion().getCounter();
1221049908b2SVedant Kumar     propagateCounts(ParentCount, S->getTryBlock());
1222049908b2SVedant Kumar 
1223ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1224ee02499aSAlex Lorenz       Visit(S->getHandler(I));
1225bf42cfd7SJustin Bogner 
1226bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
1227bf42cfd7SJustin Bogner     pushRegion(ExitCount);
1228ee02499aSAlex Lorenz   }
1229ee02499aSAlex Lorenz 
1230ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1231bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1232ee02499aSAlex Lorenz   }
1233ee02499aSAlex Lorenz 
1234ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1235bf42cfd7SJustin Bogner     extendRegion(E);
1236ee02499aSAlex Lorenz 
1237bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1238bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
1239ee02499aSAlex Lorenz 
1240e3654ce7SJustin Bogner     Visit(E->getCond());
1241e3654ce7SJustin Bogner 
1242e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
12432e8c8759SVedant Kumar       // The 'then' count applies to the area immediately after the condition.
1244fa8fa044SVedant Kumar       auto Gap =
1245fa8fa044SVedant Kumar           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1246fa8fa044SVedant Kumar       if (Gap)
1247fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
12482e8c8759SVedant Kumar 
1249e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
1250bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
1251e3654ce7SJustin Bogner     }
12522e8c8759SVedant Kumar 
1253e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
1254bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
1255bf42cfd7SJustin Bogner                     E->getFalseExpr());
1256ee02499aSAlex Lorenz   }
1257ee02499aSAlex Lorenz 
1258ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
1259e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1260e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1261e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1262bf42cfd7SJustin Bogner 
1263bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1264bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
1265ee02499aSAlex Lorenz   }
1266ee02499aSAlex Lorenz 
1267ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
1268e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1269e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1270e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1271ee02499aSAlex Lorenz 
1272bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1273bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
127401a0d062SAlex Lorenz   }
1275c109102eSJustin Bogner 
1276c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
1277c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
1278c109102eSJustin Bogner     // propagate counts into them.
1279c109102eSJustin Bogner   }
1280ee02499aSAlex Lorenz };
1281ee02499aSAlex Lorenz 
12827cd595dfSReid Kleckner std::string normalizeFilename(StringRef Filename) {
12837cd595dfSReid Kleckner   llvm::SmallString<256> Path(Filename);
12847cd595dfSReid Kleckner   llvm::sys::fs::make_absolute(Path);
12857cd595dfSReid Kleckner   llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1286509e21a1SJonas Devlieghere   return std::string(Path);
12877cd595dfSReid Kleckner }
12887cd595dfSReid Kleckner 
128914f8fb68SVedant Kumar } // end anonymous namespace
129014f8fb68SVedant Kumar 
1291a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1292a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
1293a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
1294a432d176SJustin Bogner   OS << FunctionName << ":\n";
1295a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
1296a432d176SJustin Bogner   for (const auto &R : Regions) {
1297f2cf38e0SAlex Lorenz     OS.indent(2);
1298f2cf38e0SAlex Lorenz     switch (R.Kind) {
1299f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
1300f2cf38e0SAlex Lorenz       break;
1301f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
1302f2cf38e0SAlex Lorenz       OS << "Expansion,";
1303f2cf38e0SAlex Lorenz       break;
1304f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
1305f2cf38e0SAlex Lorenz       OS << "Skipped,";
1306f2cf38e0SAlex Lorenz       break;
1307a1c4deb7SVedant Kumar     case CounterMappingRegion::GapRegion:
1308a1c4deb7SVedant Kumar       OS << "Gap,";
1309a1c4deb7SVedant Kumar       break;
1310f2cf38e0SAlex Lorenz     }
1311f2cf38e0SAlex Lorenz 
13124da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
13134da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1314f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
1315f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
13164da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
13174da909b2SJustin Bogner     OS << "\n";
1318f2cf38e0SAlex Lorenz   }
1319f2cf38e0SAlex Lorenz }
1320f2cf38e0SAlex Lorenz 
1321dd1ea9deSVedant Kumar static std::string getInstrProfSection(const CodeGenModule &CGM,
1322dd1ea9deSVedant Kumar                                        llvm::InstrProfSectKind SK) {
1323dd1ea9deSVedant Kumar   return llvm::getInstrProfSectionName(
1324dd1ea9deSVedant Kumar       SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1325dd1ea9deSVedant Kumar }
1326dd1ea9deSVedant Kumar 
1327dd1ea9deSVedant Kumar void CoverageMappingModuleGen::emitFunctionMappingRecord(
1328dd1ea9deSVedant Kumar     const FunctionInfo &Info, uint64_t FilenamesRef) {
132999317124SVedant Kumar   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1330dd1ea9deSVedant Kumar 
1331dd1ea9deSVedant Kumar   // Assign a name to the function record. This is used to merge duplicates.
1332dd1ea9deSVedant Kumar   std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1333dd1ea9deSVedant Kumar 
1334dd1ea9deSVedant Kumar   // A dummy description for a function included-but-not-used in a TU can be
1335dd1ea9deSVedant Kumar   // replaced by full description provided by a different TU. The two kinds of
1336dd1ea9deSVedant Kumar   // descriptions play distinct roles: therefore, assign them different names
1337dd1ea9deSVedant Kumar   // to prevent `linkonce_odr` merging.
1338dd1ea9deSVedant Kumar   if (Info.IsUsed)
1339dd1ea9deSVedant Kumar     FuncRecordName += "u";
1340dd1ea9deSVedant Kumar 
1341dd1ea9deSVedant Kumar   // Create the function record type.
1342dd1ea9deSVedant Kumar   const uint64_t NameHash = Info.NameHash;
1343dd1ea9deSVedant Kumar   const uint64_t FuncHash = Info.FuncHash;
1344dd1ea9deSVedant Kumar   const std::string &CoverageMapping = Info.CoverageMapping;
134533888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
134633888717SVedant Kumar   llvm::Type *FunctionRecordTypes[] = {
134733888717SVedant Kumar #include "llvm/ProfileData/InstrProfData.inc"
134833888717SVedant Kumar   };
1349dd1ea9deSVedant Kumar   auto *FunctionRecordTy =
135033888717SVedant Kumar       llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
135133888717SVedant Kumar                             /*isPacked=*/true);
135299317124SVedant Kumar 
1353dd1ea9deSVedant Kumar   // Create the function record constant.
135433888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
135533888717SVedant Kumar   llvm::Constant *FunctionRecordVals[] = {
135633888717SVedant Kumar       #include "llvm/ProfileData/InstrProfData.inc"
135733888717SVedant Kumar   };
1358dd1ea9deSVedant Kumar   auto *FuncRecordConstant = llvm::ConstantStruct::get(
1359dd1ea9deSVedant Kumar       FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1360dd1ea9deSVedant Kumar 
1361dd1ea9deSVedant Kumar   // Create the function record global.
1362dd1ea9deSVedant Kumar   auto *FuncRecord = new llvm::GlobalVariable(
1363dd1ea9deSVedant Kumar       CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1364dd1ea9deSVedant Kumar       llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1365dd1ea9deSVedant Kumar       FuncRecordName);
1366dd1ea9deSVedant Kumar   FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1367dd1ea9deSVedant Kumar   FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1368dd1ea9deSVedant Kumar   FuncRecord->setAlignment(llvm::Align(8));
1369dd1ea9deSVedant Kumar   if (CGM.supportsCOMDAT())
1370dd1ea9deSVedant Kumar     FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1371dd1ea9deSVedant Kumar 
1372dd1ea9deSVedant Kumar   // Make sure the data doesn't get deleted.
1373dd1ea9deSVedant Kumar   CGM.addUsedGlobal(FuncRecord);
1374dd1ea9deSVedant Kumar }
1375dd1ea9deSVedant Kumar 
1376dd1ea9deSVedant Kumar void CoverageMappingModuleGen::addFunctionMappingRecord(
1377dd1ea9deSVedant Kumar     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1378dd1ea9deSVedant Kumar     const std::string &CoverageMapping, bool IsUsed) {
1379dd1ea9deSVedant Kumar   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1380dd1ea9deSVedant Kumar   const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1381dd1ea9deSVedant Kumar   FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
1382dd1ea9deSVedant Kumar 
1383848da137SXinliang David Li   if (!IsUsed)
13842129ae53SXinliang David Li     FunctionNames.push_back(
13852129ae53SXinliang David Li         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1386f2cf38e0SAlex Lorenz 
1387f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1388f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1389f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1390f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1391f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1392f2cf38e0SAlex Lorenz     // expressions.
1393f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1394f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1395f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
1396b31ee819SJordan Rose     llvm::SmallVector<std::string, 16> FilenameStrs;
1397f2cf38e0SAlex Lorenz     llvm::SmallVector<StringRef, 16> FilenameRefs;
1398b31ee819SJordan Rose     FilenameStrs.resize(FileEntries.size());
1399f2cf38e0SAlex Lorenz     FilenameRefs.resize(FileEntries.size());
1400b31ee819SJordan Rose     for (const auto &Entry : FileEntries) {
1401b31ee819SJordan Rose       auto I = Entry.second;
1402b31ee819SJordan Rose       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1403b31ee819SJordan Rose       FilenameRefs[I] = FilenameStrs[I];
1404b31ee819SJordan Rose     }
1405a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1406a432d176SJustin Bogner                                     Expressions, Regions);
1407a432d176SJustin Bogner     if (Reader.read())
1408f2cf38e0SAlex Lorenz       return;
1409a026a437SXinliang David Li     dump(llvm::outs(), NameValue, Expressions, Regions);
1410f2cf38e0SAlex Lorenz   }
1411ee02499aSAlex Lorenz }
1412ee02499aSAlex Lorenz 
1413ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1414ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1415ee02499aSAlex Lorenz     return;
1416ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1417ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1418ee02499aSAlex Lorenz 
1419ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1420ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
14219e324dd1SVedant Kumar   llvm::SmallVector<StringRef, 16> FilenameRefs;
1422ee02499aSAlex Lorenz   FilenameStrs.resize(FileEntries.size());
14239e324dd1SVedant Kumar   FilenameRefs.resize(FileEntries.size());
1424ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1425ee02499aSAlex Lorenz     auto I = Entry.second;
142614f8fb68SVedant Kumar     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
14279e324dd1SVedant Kumar     FilenameRefs[I] = FilenameStrs[I];
1428ee02499aSAlex Lorenz   }
1429ee02499aSAlex Lorenz 
1430dd1ea9deSVedant Kumar   std::string Filenames;
1431dd1ea9deSVedant Kumar   {
1432dd1ea9deSVedant Kumar     llvm::raw_string_ostream OS(Filenames);
14339e324dd1SVedant Kumar     CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
14344cd07dbeSSerge Guelton   }
1435dd1ea9deSVedant Kumar   auto *FilenamesVal =
1436dd1ea9deSVedant Kumar       llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1437dd1ea9deSVedant Kumar   const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
14384cd07dbeSSerge Guelton 
1439dd1ea9deSVedant Kumar   // Emit the function records.
1440dd1ea9deSVedant Kumar   for (const FunctionInfo &Info : FunctionRecords)
1441dd1ea9deSVedant Kumar     emitFunctionMappingRecord(Info, FilenamesRef);
1442ee02499aSAlex Lorenz 
1443dd1ea9deSVedant Kumar   const unsigned NRecords = 0;
1444dd1ea9deSVedant Kumar   const size_t FilenamesSize = Filenames.size();
1445dd1ea9deSVedant Kumar   const unsigned CoverageMappingSize = 0;
144620b188c0SXinliang David Li   llvm::Type *CovDataHeaderTypes[] = {
144720b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
144820b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
144920b188c0SXinliang David Li   };
145020b188c0SXinliang David Li   auto CovDataHeaderTy =
145120b188c0SXinliang David Li       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
145220b188c0SXinliang David Li   llvm::Constant *CovDataHeaderVals[] = {
145320b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
145420b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
145520b188c0SXinliang David Li   };
145620b188c0SXinliang David Li   auto CovDataHeaderVal = llvm::ConstantStruct::get(
145720b188c0SXinliang David Li       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
145820b188c0SXinliang David Li 
1459ee02499aSAlex Lorenz   // Create the coverage data record
1460dd1ea9deSVedant Kumar   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
1461ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1462dd1ea9deSVedant Kumar   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
1463ee02499aSAlex Lorenz   auto CovDataVal =
1464ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
146520b188c0SXinliang David Li   auto CovData = new llvm::GlobalVariable(
1466dd1ea9deSVedant Kumar       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
146720b188c0SXinliang David Li       CovDataVal, llvm::getCoverageMappingVarName());
1468ee02499aSAlex Lorenz 
1469dd1ea9deSVedant Kumar   CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
1470c79099e0SGuillaume Chatelet   CovData->setAlignment(llvm::Align(8));
1471ee02499aSAlex Lorenz 
1472ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1473ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
14742129ae53SXinliang David Li   // Create the deferred function records array
14752129ae53SXinliang David Li   if (!FunctionNames.empty()) {
14762129ae53SXinliang David Li     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
14772129ae53SXinliang David Li                                            FunctionNames.size());
14782129ae53SXinliang David Li     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
14792129ae53SXinliang David Li     // This variable will *NOT* be emitted to the object file. It is used
14802129ae53SXinliang David Li     // to pass the list of names referenced to codegen.
14812129ae53SXinliang David Li     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
14822129ae53SXinliang David Li                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
14837077f0afSXinliang David Li                              llvm::getCoverageUnusedNamesVarName());
14842129ae53SXinliang David Li   }
1485ee02499aSAlex Lorenz }
1486ee02499aSAlex Lorenz 
1487ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1488ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1489ee02499aSAlex Lorenz   if (It != FileEntries.end())
1490ee02499aSAlex Lorenz     return It->second;
1491ee02499aSAlex Lorenz   unsigned FileID = FileEntries.size();
1492ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1493ee02499aSAlex Lorenz   return FileID;
1494ee02499aSAlex Lorenz }
1495ee02499aSAlex Lorenz 
1496ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1497ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1498ee02499aSAlex Lorenz   assert(CounterMap);
1499e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1500ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1501ee02499aSAlex Lorenz   Walker.write(OS);
1502ee02499aSAlex Lorenz }
1503ee02499aSAlex Lorenz 
1504ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1505ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1506ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1507ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1508ee02499aSAlex Lorenz   Walker.write(OS);
1509ee02499aSAlex Lorenz }
1510