1ee02499aSAlex Lorenz //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2ee02499aSAlex Lorenz //
3ee02499aSAlex Lorenz //                     The LLVM Compiler Infrastructure
4ee02499aSAlex Lorenz //
5ee02499aSAlex Lorenz // This file is distributed under the University of Illinois Open Source
6ee02499aSAlex Lorenz // License. See LICENSE.TXT for details.
7ee02499aSAlex Lorenz //
8ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
9ee02499aSAlex Lorenz //
10ee02499aSAlex Lorenz // Instrumentation-based code coverage mapping generator
11ee02499aSAlex Lorenz //
12ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
13ee02499aSAlex Lorenz 
14ee02499aSAlex Lorenz #include "CoverageMappingGen.h"
15ee02499aSAlex Lorenz #include "CodeGenFunction.h"
16ee02499aSAlex Lorenz #include "clang/AST/StmtVisitor.h"
17ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h"
18bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h"
19ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h"
20bf42cfd7SJustin Bogner #include "llvm/ADT/Optional.h"
21b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h"
22b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
240d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h"
25ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h"
2614f8fb68SVedant Kumar #include "llvm/Support/Path.h"
27ee02499aSAlex Lorenz 
28ee02499aSAlex Lorenz using namespace clang;
29ee02499aSAlex Lorenz using namespace CodeGen;
30ee02499aSAlex Lorenz using namespace llvm::coverage;
31ee02499aSAlex Lorenz 
32ee02499aSAlex Lorenz void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
33ee02499aSAlex Lorenz   SkippedRanges.push_back(Range);
34ee02499aSAlex Lorenz }
35ee02499aSAlex Lorenz 
36ee02499aSAlex Lorenz namespace {
37ee02499aSAlex Lorenz 
38ee02499aSAlex Lorenz /// \brief A region of source code that can be mapped to a counter.
3909c7179bSJustin Bogner class SourceMappingRegion {
40ee02499aSAlex Lorenz   Counter Count;
41ee02499aSAlex Lorenz 
42ee02499aSAlex Lorenz   /// \brief The region's starting location.
43bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
44ee02499aSAlex Lorenz 
45ee02499aSAlex Lorenz   /// \brief The region's ending location.
46bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
47ee02499aSAlex Lorenz 
4809c7179bSJustin Bogner public:
49bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
50a7764adcSVedant Kumar                       Optional<SourceLocation> LocEnd)
51a7764adcSVedant Kumar       : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
52ee02499aSAlex Lorenz 
5309c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
5409c7179bSJustin Bogner 
55bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
5609c7179bSJustin Bogner 
57bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
58bf42cfd7SJustin Bogner 
59bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
60bf42cfd7SJustin Bogner 
61462c77b4SCraig Topper   SourceLocation getStartLoc() const {
62bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
63bf42cfd7SJustin Bogner     return *LocStart;
6409c7179bSJustin Bogner   }
6509c7179bSJustin Bogner 
66bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
67ee02499aSAlex Lorenz 
68bf42cfd7SJustin Bogner   void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
69ee02499aSAlex Lorenz 
70462c77b4SCraig Topper   SourceLocation getEndLoc() const {
71bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
72bf42cfd7SJustin Bogner     return *LocEnd;
73ee02499aSAlex Lorenz   }
74ee02499aSAlex Lorenz };
75ee02499aSAlex Lorenz 
76d7369648SVedant Kumar /// Spelling locations for the start and end of a source region.
77d7369648SVedant Kumar struct SpellingRegion {
78d7369648SVedant Kumar   /// The line where the region starts.
79d7369648SVedant Kumar   unsigned LineStart;
80d7369648SVedant Kumar 
81d7369648SVedant Kumar   /// The column where the region starts.
82d7369648SVedant Kumar   unsigned ColumnStart;
83d7369648SVedant Kumar 
84d7369648SVedant Kumar   /// The line where the region ends.
85d7369648SVedant Kumar   unsigned LineEnd;
86d7369648SVedant Kumar 
87d7369648SVedant Kumar   /// The column where the region ends.
88d7369648SVedant Kumar   unsigned ColumnEnd;
89d7369648SVedant Kumar 
90d7369648SVedant Kumar   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
91d7369648SVedant Kumar                  SourceLocation LocEnd) {
92d7369648SVedant Kumar     LineStart = SM.getSpellingLineNumber(LocStart);
93d7369648SVedant Kumar     ColumnStart = SM.getSpellingColumnNumber(LocStart);
94d7369648SVedant Kumar     LineEnd = SM.getSpellingLineNumber(LocEnd);
95d7369648SVedant Kumar     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
96d7369648SVedant Kumar   }
97d7369648SVedant Kumar 
98d7369648SVedant Kumar   /// Check if the start and end locations appear in source order, i.e
99d7369648SVedant Kumar   /// top->bottom, left->right.
100d7369648SVedant Kumar   bool isInSourceOrder() const {
101d7369648SVedant Kumar     return (LineStart < LineEnd) ||
102d7369648SVedant Kumar            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
103d7369648SVedant Kumar   }
104d7369648SVedant Kumar };
105d7369648SVedant Kumar 
106ee02499aSAlex Lorenz /// \brief Provides the common functionality for the different
107ee02499aSAlex Lorenz /// coverage mapping region builders.
108ee02499aSAlex Lorenz class CoverageMappingBuilder {
109ee02499aSAlex Lorenz public:
110ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
111ee02499aSAlex Lorenz   SourceManager &SM;
112ee02499aSAlex Lorenz   const LangOptions &LangOpts;
113ee02499aSAlex Lorenz 
114ee02499aSAlex Lorenz private:
115bf42cfd7SJustin Bogner   /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
116bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
117bf42cfd7SJustin Bogner       FileIDMapping;
118ee02499aSAlex Lorenz 
119ee02499aSAlex Lorenz public:
120ee02499aSAlex Lorenz   /// \brief The coverage mapping regions for this function
121ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
122ee02499aSAlex Lorenz   /// \brief The source mapping regions for this function.
123f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
124ee02499aSAlex Lorenz 
125fc05ee34SIgor Kudrin   /// \brief A set of regions which can be used as a filter.
126fc05ee34SIgor Kudrin   ///
127fc05ee34SIgor Kudrin   /// It is produced by emitExpansionRegions() and is used in
128fc05ee34SIgor Kudrin   /// emitSourceRegions() to suppress producing code regions if
129fc05ee34SIgor Kudrin   /// the same area is covered by expansion regions.
130fc05ee34SIgor Kudrin   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
131fc05ee34SIgor Kudrin       SourceRegionFilter;
132fc05ee34SIgor Kudrin 
133ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
134ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
135bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
136ee02499aSAlex Lorenz 
137ee02499aSAlex Lorenz   /// \brief Return the precise end location for the given token.
138ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
139bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
140bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
141bf42cfd7SJustin Bogner     unsigned TokLen =
142bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
143bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
144ee02499aSAlex Lorenz   }
145ee02499aSAlex Lorenz 
146bf42cfd7SJustin Bogner   /// \brief Return the start location of an included file or expanded macro.
147bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
148bf42cfd7SJustin Bogner     if (Loc.isMacroID())
149bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
150bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
151ee02499aSAlex Lorenz   }
152ee02499aSAlex Lorenz 
153bf42cfd7SJustin Bogner   /// \brief Return the end location of an included file or expanded macro.
154bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
155bf42cfd7SJustin Bogner     if (Loc.isMacroID())
156bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
157f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
158bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
159bf42cfd7SJustin Bogner   }
160ee02499aSAlex Lorenz 
161bf42cfd7SJustin Bogner   /// \brief Find out where the current file is included or macro is expanded.
162bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
163bf42cfd7SJustin Bogner     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
164bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
165bf42cfd7SJustin Bogner   }
166bf42cfd7SJustin Bogner 
167682bfbf3SJustin Bogner   /// \brief Return true if \c Loc is a location in a built-in macro.
168682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
16999d1b295SMehdi Amini     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
170682bfbf3SJustin Bogner   }
171682bfbf3SJustin Bogner 
172d9e1a61dSIgor Kudrin   /// \brief Check whether \c Loc is included or expanded from \c Parent.
173d9e1a61dSIgor Kudrin   bool isNestedIn(SourceLocation Loc, FileID Parent) {
174d9e1a61dSIgor Kudrin     do {
175d9e1a61dSIgor Kudrin       Loc = getIncludeOrExpansionLoc(Loc);
176d9e1a61dSIgor Kudrin       if (Loc.isInvalid())
177d9e1a61dSIgor Kudrin         return false;
178d9e1a61dSIgor Kudrin     } while (!SM.isInFileID(Loc, Parent));
179d9e1a61dSIgor Kudrin     return true;
180d9e1a61dSIgor Kudrin   }
181d9e1a61dSIgor Kudrin 
182682bfbf3SJustin Bogner   /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
183bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
184bf42cfd7SJustin Bogner     SourceLocation Loc = S->getLocStart();
185682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
186bf42cfd7SJustin Bogner       Loc = SM.getImmediateExpansionRange(Loc).first;
187bf42cfd7SJustin Bogner     return Loc;
188bf42cfd7SJustin Bogner   }
189bf42cfd7SJustin Bogner 
190682bfbf3SJustin Bogner   /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
191bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
192bf42cfd7SJustin Bogner     SourceLocation Loc = S->getLocEnd();
193682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
194bf42cfd7SJustin Bogner       Loc = SM.getImmediateExpansionRange(Loc).first;
195f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
196bf42cfd7SJustin Bogner   }
197bf42cfd7SJustin Bogner 
198bf42cfd7SJustin Bogner   /// \brief Find the set of files we have regions for and assign IDs
199bf42cfd7SJustin Bogner   ///
200bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
201bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
202bf42cfd7SJustin Bogner   /// expansion regions.
203bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
204bf42cfd7SJustin Bogner     FileIDMapping.clear();
205bf42cfd7SJustin Bogner 
206bc6b80a0SVedant Kumar     llvm::SmallSet<FileID, 8> Visited;
207bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
208bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
209bf42cfd7SJustin Bogner       SourceLocation Loc = Region.getStartLoc();
210bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
211bc6b80a0SVedant Kumar       if (!Visited.insert(File).second)
212bf42cfd7SJustin Bogner         continue;
213bf42cfd7SJustin Bogner 
21493205af0SVedant Kumar       // Do not map FileID's associated with system headers.
21593205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
21693205af0SVedant Kumar         continue;
21793205af0SVedant Kumar 
218bf42cfd7SJustin Bogner       unsigned Depth = 0;
219bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
220ed1fe5d0SYaron Keren            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
221bf42cfd7SJustin Bogner         ++Depth;
222bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
223bf42cfd7SJustin Bogner     }
224bf42cfd7SJustin Bogner     std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
225bf42cfd7SJustin Bogner 
226bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
227bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
228bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
229ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
230ee02499aSAlex Lorenz       if (!Entry)
231bf42cfd7SJustin Bogner         continue;
232ee02499aSAlex Lorenz 
233bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
234bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
235bf42cfd7SJustin Bogner     }
236ee02499aSAlex Lorenz   }
237ee02499aSAlex Lorenz 
238bf42cfd7SJustin Bogner   /// \brief Get the coverage mapping file ID for \c Loc.
239bf42cfd7SJustin Bogner   ///
240bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
241bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
242bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
243bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
244bf42cfd7SJustin Bogner       return Mapping->second.first;
245903678caSJustin Bogner     return None;
246ee02499aSAlex Lorenz   }
247ee02499aSAlex Lorenz 
248ee02499aSAlex Lorenz   /// \brief Gather all the regions that were skipped by the preprocessor
249ee02499aSAlex Lorenz   /// using the constructs like #if.
250ee02499aSAlex Lorenz   void gatherSkippedRegions() {
251ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
252ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
253ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
254ee02499aSAlex Lorenz     FileLineRanges.resize(
255ee02499aSAlex Lorenz         FileIDMapping.size(),
256ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
257ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
258ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
259ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
260ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
261ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
262ee02499aSAlex Lorenz     }
263ee02499aSAlex Lorenz 
264ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
265ee02499aSAlex Lorenz     for (const auto &I : SkippedRanges) {
266ee02499aSAlex Lorenz       auto LocStart = I.getBegin();
267ee02499aSAlex Lorenz       auto LocEnd = I.getEnd();
268bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
269bf42cfd7SJustin Bogner              "region spans multiple files");
270ee02499aSAlex Lorenz 
271bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
272903678caSJustin Bogner       if (!CovFileID)
273ee02499aSAlex Lorenz         continue;
274d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
275fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
276d7369648SVedant Kumar           *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
277ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
278ee02499aSAlex Lorenz       // the souce code of this function.
279903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
280903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
281ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
282ee02499aSAlex Lorenz     }
283ee02499aSAlex Lorenz   }
284ee02499aSAlex Lorenz 
285ee02499aSAlex Lorenz   /// \brief Generate the coverage counter mapping regions from collected
286ee02499aSAlex Lorenz   /// source regions.
287fc05ee34SIgor Kudrin   void emitSourceRegions(const SourceRegionFilter &Filter) {
288bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
289bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
290ee02499aSAlex Lorenz 
291bf42cfd7SJustin Bogner       SourceLocation LocStart = Region.getStartLoc();
2928b563665SYaron Keren       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
293f59329b0SJustin Bogner 
29493205af0SVedant Kumar       // Ignore regions from system headers.
29593205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
29693205af0SVedant Kumar         continue;
29793205af0SVedant Kumar 
298bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
299bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
300bf42cfd7SJustin Bogner       if (!CovFileID)
301ee02499aSAlex Lorenz         continue;
302ee02499aSAlex Lorenz 
303f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
304bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
305bf42cfd7SJustin Bogner              "region spans multiple files");
306bf42cfd7SJustin Bogner 
307fc05ee34SIgor Kudrin       // Don't add code regions for the area covered by expansion regions.
308fc05ee34SIgor Kudrin       // This not only suppresses redundant regions, but sometimes prevents
309fc05ee34SIgor Kudrin       // creating regions with wrong counters if, for example, a statement's
310fc05ee34SIgor Kudrin       // body ends at the end of a nested macro.
311fc05ee34SIgor Kudrin       if (Filter.count(std::make_pair(LocStart, LocEnd)))
312fc05ee34SIgor Kudrin         continue;
313fc05ee34SIgor Kudrin 
314d7369648SVedant Kumar       // Find the spelling locations for the mapping region.
315d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
316d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
317bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeRegion(
318d7369648SVedant Kumar           Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
319d7369648SVedant Kumar           SR.LineEnd, SR.ColumnEnd));
320bf42cfd7SJustin Bogner     }
321bf42cfd7SJustin Bogner   }
322bf42cfd7SJustin Bogner 
323bf42cfd7SJustin Bogner   /// \brief Generate expansion regions for each virtual file we've seen.
324fc05ee34SIgor Kudrin   SourceRegionFilter emitExpansionRegions() {
325fc05ee34SIgor Kudrin     SourceRegionFilter Filter;
326bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
327bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
328bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
329bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
330ee02499aSAlex Lorenz         continue;
331ee02499aSAlex Lorenz 
332bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
333bf42cfd7SJustin Bogner       if (!ParentFileID)
334bf42cfd7SJustin Bogner         continue;
335bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
336bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
337bf42cfd7SJustin Bogner 
338bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
339bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
340bf42cfd7SJustin Bogner              "region spans multiple files");
341fc05ee34SIgor Kudrin       Filter.insert(std::make_pair(ParentLoc, LocEnd));
342bf42cfd7SJustin Bogner 
343d7369648SVedant Kumar       SpellingRegion SR{SM, ParentLoc, LocEnd};
344d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
345bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
346d7369648SVedant Kumar           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
347d7369648SVedant Kumar           SR.LineEnd, SR.ColumnEnd));
348ee02499aSAlex Lorenz     }
349fc05ee34SIgor Kudrin     return Filter;
350ee02499aSAlex Lorenz   }
351ee02499aSAlex Lorenz };
352ee02499aSAlex Lorenz 
353ee02499aSAlex Lorenz /// \brief Creates unreachable coverage regions for the functions that
354ee02499aSAlex Lorenz /// are not emitted.
355ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
356ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
357ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
358ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
359ee02499aSAlex Lorenz 
360ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
361ee02499aSAlex Lorenz     if (!D->hasBody())
362ee02499aSAlex Lorenz       return;
363ee02499aSAlex Lorenz     auto Body = D->getBody();
364d9e1a61dSIgor Kudrin     SourceLocation Start = getStart(Body);
365d9e1a61dSIgor Kudrin     SourceLocation End = getEnd(Body);
366d9e1a61dSIgor Kudrin     if (!SM.isWrittenInSameFile(Start, End)) {
367d9e1a61dSIgor Kudrin       // Walk up to find the common ancestor.
368d9e1a61dSIgor Kudrin       // Correct the locations accordingly.
369d9e1a61dSIgor Kudrin       FileID StartFileID = SM.getFileID(Start);
370d9e1a61dSIgor Kudrin       FileID EndFileID = SM.getFileID(End);
371d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
372d9e1a61dSIgor Kudrin         Start = getIncludeOrExpansionLoc(Start);
373d9e1a61dSIgor Kudrin         assert(Start.isValid() &&
374d9e1a61dSIgor Kudrin                "Declaration start location not nested within a known region");
375d9e1a61dSIgor Kudrin         StartFileID = SM.getFileID(Start);
376d9e1a61dSIgor Kudrin       }
377d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID) {
378d9e1a61dSIgor Kudrin         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
379d9e1a61dSIgor Kudrin         assert(End.isValid() &&
380d9e1a61dSIgor Kudrin                "Declaration end location not nested within a known region");
381d9e1a61dSIgor Kudrin         EndFileID = SM.getFileID(End);
382d9e1a61dSIgor Kudrin       }
383d9e1a61dSIgor Kudrin     }
384d9e1a61dSIgor Kudrin     SourceRegions.emplace_back(Counter(), Start, End);
385ee02499aSAlex Lorenz   }
386ee02499aSAlex Lorenz 
387ee02499aSAlex Lorenz   /// \brief Write the mapping data to the output stream
388ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
389ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
390bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
391fc05ee34SIgor Kudrin     emitSourceRegions(SourceRegionFilter());
392ee02499aSAlex Lorenz 
393efd319a2SVedant Kumar     if (MappingRegions.empty())
394efd319a2SVedant Kumar       return;
395efd319a2SVedant Kumar 
3965fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
397ee02499aSAlex Lorenz     Writer.write(OS);
398ee02499aSAlex Lorenz   }
399ee02499aSAlex Lorenz };
400ee02499aSAlex Lorenz 
401ee02499aSAlex Lorenz /// \brief A StmtVisitor that creates coverage mapping regions which map
402ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
403ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
404ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
405ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
406ee02499aSAlex Lorenz   /// \brief The map of statements to count values.
407ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
408ee02499aSAlex Lorenz 
409bf42cfd7SJustin Bogner   /// \brief A stack of currently live regions.
410bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
411ee02499aSAlex Lorenz 
412ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
413ee02499aSAlex Lorenz 
414bf42cfd7SJustin Bogner   /// \brief A location in the most recently visited file or macro.
415bf42cfd7SJustin Bogner   ///
416bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
417bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
418bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
419bf42cfd7SJustin Bogner 
420bf42cfd7SJustin Bogner   /// \brief Return a counter for the subtraction of \c RHS from \c LHS
421ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
422ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
423ee02499aSAlex Lorenz   }
424ee02499aSAlex Lorenz 
425bf42cfd7SJustin Bogner   /// \brief Return a counter for the sum of \c LHS and \c RHS.
426ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
427ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
428ee02499aSAlex Lorenz   }
429ee02499aSAlex Lorenz 
430bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
431bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
432bf42cfd7SJustin Bogner   }
433bf42cfd7SJustin Bogner 
434ee02499aSAlex Lorenz   /// \brief Return the region counter for the given statement.
435bf42cfd7SJustin Bogner   ///
436ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
437bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
438bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
439ee02499aSAlex Lorenz   }
440ee02499aSAlex Lorenz 
441bf42cfd7SJustin Bogner   /// \brief Push a region onto the stack.
442bf42cfd7SJustin Bogner   ///
443bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
444bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
445bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
446bf42cfd7SJustin Bogner                     Optional<SourceLocation> EndLoc = None) {
447a7764adcSVedant Kumar     if (StartLoc)
448bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
449bf42cfd7SJustin Bogner     RegionStack.emplace_back(Count, StartLoc, EndLoc);
450ee02499aSAlex Lorenz 
451bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
452ee02499aSAlex Lorenz   }
453ee02499aSAlex Lorenz 
454bf42cfd7SJustin Bogner   /// \brief Pop regions from the stack into the function's list of regions.
455bf42cfd7SJustin Bogner   ///
456bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
457bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
458bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
459bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
460bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
461bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
462bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
463bf42cfd7SJustin Bogner         SourceLocation StartLoc = Region.getStartLoc();
464bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
465bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
466bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
467bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
468bf42cfd7SJustin Bogner           // The region ends in a nested file or macro expansion. Create a
469bf42cfd7SJustin Bogner           // separate region for each expansion.
470bf42cfd7SJustin Bogner           SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
471bf42cfd7SJustin Bogner           assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
472bf42cfd7SJustin Bogner 
4738545dae2SIgor Kudrin           if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
474bf42cfd7SJustin Bogner             SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
475bf42cfd7SJustin Bogner 
476f14b2078SJustin Bogner           EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
477dceaaadfSJustin Bogner           if (EndLoc.isInvalid())
478dceaaadfSJustin Bogner             llvm::report_fatal_error("File exit not handled before popRegions");
479bf42cfd7SJustin Bogner         }
480bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
481bf42cfd7SJustin Bogner 
482bf42cfd7SJustin Bogner         MostRecentLocation = EndLoc;
483bf42cfd7SJustin Bogner         // If this region happens to span an entire expansion, we need to make
484bf42cfd7SJustin Bogner         // sure we don't overlap the parent region with it.
485bf42cfd7SJustin Bogner         if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
486bf42cfd7SJustin Bogner             EndLoc == getEndOfFileOrMacro(EndLoc))
487bf42cfd7SJustin Bogner           MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
488bf42cfd7SJustin Bogner 
489bf42cfd7SJustin Bogner         assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
490f36a5c4aSCraig Topper         SourceRegions.push_back(Region);
491bf42cfd7SJustin Bogner       }
492bf42cfd7SJustin Bogner       RegionStack.pop_back();
493bf42cfd7SJustin Bogner     }
494ee02499aSAlex Lorenz   }
495ee02499aSAlex Lorenz 
496bf42cfd7SJustin Bogner   /// \brief Return the currently active region.
497bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
498bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
499bf42cfd7SJustin Bogner     return RegionStack.back();
500ee02499aSAlex Lorenz   }
501ee02499aSAlex Lorenz 
502bf42cfd7SJustin Bogner   /// \brief Propagate counts through the children of \c S.
503bf42cfd7SJustin Bogner   Counter propagateCounts(Counter TopCount, const Stmt *S) {
5047838696eSVedant Kumar     SourceLocation StartLoc = getStart(S);
5057838696eSVedant Kumar     SourceLocation EndLoc = getEnd(S);
5067838696eSVedant Kumar     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
507bf42cfd7SJustin Bogner     Visit(S);
508bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
509bf42cfd7SJustin Bogner     popRegions(Index);
51039f01975SVedant Kumar 
51139f01975SVedant Kumar     // The statement may be spanned by an expansion. Make sure we handle a file
51239f01975SVedant Kumar     // exit out of this expansion before moving to the next statement.
5137838696eSVedant Kumar     if (SM.isBeforeInTranslationUnit(StartLoc, S->getLocStart()))
5147838696eSVedant Kumar       MostRecentLocation = EndLoc;
51539f01975SVedant Kumar 
516bf42cfd7SJustin Bogner     return ExitCount;
517ee02499aSAlex Lorenz   }
518ee02499aSAlex Lorenz 
5190a7c9d11SIgor Kudrin   /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc
5200a7c9d11SIgor Kudrin   /// is already added to \c SourceRegions.
5210a7c9d11SIgor Kudrin   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
5220a7c9d11SIgor Kudrin     return SourceRegions.rend() !=
5230a7c9d11SIgor Kudrin            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
5240a7c9d11SIgor Kudrin                         [&](const SourceMappingRegion &Region) {
5250a7c9d11SIgor Kudrin                           return Region.getStartLoc() == StartLoc &&
5260a7c9d11SIgor Kudrin                                  Region.getEndLoc() == EndLoc;
5270a7c9d11SIgor Kudrin                         });
5280a7c9d11SIgor Kudrin   }
5290a7c9d11SIgor Kudrin 
530bf42cfd7SJustin Bogner   /// \brief Adjust the most recently visited location to \c EndLoc.
531bf42cfd7SJustin Bogner   ///
532bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
533bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
534bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
5350a7c9d11SIgor Kudrin     // The code region for a whole macro is created in handleFileExit() when
5360a7c9d11SIgor Kudrin     // it detects exiting of the virtual file of that macro. If we visited
5370a7c9d11SIgor Kudrin     // statements in non-source order, we might already have such a region
5380a7c9d11SIgor Kudrin     // added, for example, if a body of a loop is divided among multiple
5390a7c9d11SIgor Kudrin     // macros. Avoid adding duplicate regions in such case.
54096ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
5410a7c9d11SIgor Kudrin         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
5420a7c9d11SIgor Kudrin         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
5430a7c9d11SIgor Kudrin                              MostRecentLocation))
544bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
545ee02499aSAlex Lorenz   }
546ee02499aSAlex Lorenz 
547bf42cfd7SJustin Bogner   /// \brief Adjust regions and state when \c NewLoc exits a file.
548bf42cfd7SJustin Bogner   ///
549bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
550bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
551bf42cfd7SJustin Bogner   /// for the exited file.
552bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
553e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
554e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
555bf42cfd7SJustin Bogner       return;
556bf42cfd7SJustin Bogner 
557bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
558bf42cfd7SJustin Bogner     // find the common ancestor.
559bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
560bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
561bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
562bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
563bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
564bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
565bf42cfd7SJustin Bogner         // to adjust our location to the new file.
566bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
567bf42cfd7SJustin Bogner         return;
568bf42cfd7SJustin Bogner       }
569bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
570ee02499aSAlex Lorenz     }
571ee02499aSAlex Lorenz 
572bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
573bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
57457d3f145SPete Cooper     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
57557d3f145SPete Cooper       if (!I.hasStartLoc())
576bf42cfd7SJustin Bogner         continue;
57757d3f145SPete Cooper       SourceLocation Loc = I.getStartLoc();
578bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
57957d3f145SPete Cooper         ParentCounter = I.getCounter();
580bf42cfd7SJustin Bogner         break;
581ee02499aSAlex Lorenz       }
582bf42cfd7SJustin Bogner 
583bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
584bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
585bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
586bf42cfd7SJustin Bogner         // we've seen this region.
587bf42cfd7SJustin Bogner         if (StartLocs.insert(Loc).second)
58857d3f145SPete Cooper           SourceRegions.emplace_back(I.getCounter(), Loc,
589bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
590bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
591ee02499aSAlex Lorenz       }
59257d3f145SPete Cooper       I.setStartLoc(getPreciseTokenLocEnd(Loc));
593bf42cfd7SJustin Bogner     }
594bf42cfd7SJustin Bogner 
595bf42cfd7SJustin Bogner     if (ParentCounter) {
596bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
597bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
598bf42cfd7SJustin Bogner       // corresponding to the parent.
599bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
600bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
601bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
602bf42cfd7SJustin Bogner         if (StartLocs.insert(FileStart).second)
603bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
604bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
605bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
606bf42cfd7SJustin Bogner       }
607bf42cfd7SJustin Bogner     }
608bf42cfd7SJustin Bogner 
609bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
610bf42cfd7SJustin Bogner   }
611bf42cfd7SJustin Bogner 
612bf42cfd7SJustin Bogner   /// \brief Ensure that \c S is included in the current region.
613bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
614bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
615bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
616bf42cfd7SJustin Bogner 
617bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
618bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
619bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
620bf42cfd7SJustin Bogner   }
621bf42cfd7SJustin Bogner 
622bf42cfd7SJustin Bogner   /// \brief Mark \c S as a terminator, starting a zero region.
623bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
624bf42cfd7SJustin Bogner     extendRegion(S);
625bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
626bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
627bf42cfd7SJustin Bogner       Region.setEndLoc(getEnd(S));
628bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
629bf42cfd7SJustin Bogner   }
630ee02499aSAlex Lorenz 
631ee02499aSAlex Lorenz   /// \brief Keep counts of breaks and continues inside loops.
632ee02499aSAlex Lorenz   struct BreakContinue {
633ee02499aSAlex Lorenz     Counter BreakCount;
634ee02499aSAlex Lorenz     Counter ContinueCount;
635ee02499aSAlex Lorenz   };
636ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
637ee02499aSAlex Lorenz 
638ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
639ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
640e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
641ee02499aSAlex Lorenz       const LangOptions &LangOpts)
642a7764adcSVedant Kumar       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
643ee02499aSAlex Lorenz 
644ee02499aSAlex Lorenz   /// \brief Write the mapping data to the output stream
645ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
646ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
647bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
648fc05ee34SIgor Kudrin     SourceRegionFilter Filter = emitExpansionRegions();
649fc05ee34SIgor Kudrin     emitSourceRegions(Filter);
650ee02499aSAlex Lorenz     gatherSkippedRegions();
651ee02499aSAlex Lorenz 
652efd319a2SVedant Kumar     if (MappingRegions.empty())
653efd319a2SVedant Kumar       return;
654efd319a2SVedant Kumar 
6554da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
6564da909b2SJustin Bogner                                  MappingRegions);
657ee02499aSAlex Lorenz     Writer.write(OS);
658ee02499aSAlex Lorenz   }
659ee02499aSAlex Lorenz 
660ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
661ed1fe5d0SYaron Keren     if (S->getLocStart().isValid())
662bf42cfd7SJustin Bogner       extendRegion(S);
663642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
664642f173aSBenjamin Kramer       if (Child)
665642f173aSBenjamin Kramer         this->Visit(Child);
666bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
667ee02499aSAlex Lorenz   }
668ee02499aSAlex Lorenz 
669ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
670bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
671efd319a2SVedant Kumar 
672efd319a2SVedant Kumar     // Do not propagate region counts into system headers.
673efd319a2SVedant Kumar     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
674efd319a2SVedant Kumar       return;
675efd319a2SVedant Kumar 
676a7764adcSVedant Kumar     propagateCounts(getRegionCounter(Body), Body);
677ee02499aSAlex Lorenz   }
678ee02499aSAlex Lorenz 
679ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
680bf42cfd7SJustin Bogner     extendRegion(S);
681ee02499aSAlex Lorenz     if (S->getRetValue())
682ee02499aSAlex Lorenz       Visit(S->getRetValue());
683bf42cfd7SJustin Bogner     terminateRegion(S);
684ee02499aSAlex Lorenz   }
685ee02499aSAlex Lorenz 
686f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
687f959febfSJustin Bogner     extendRegion(E);
688f959febfSJustin Bogner     if (E->getSubExpr())
689f959febfSJustin Bogner       Visit(E->getSubExpr());
690f959febfSJustin Bogner     terminateRegion(E);
691f959febfSJustin Bogner   }
692f959febfSJustin Bogner 
693bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
694ee02499aSAlex Lorenz 
695ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
696bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
697bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
698bf42cfd7SJustin Bogner     handleFileExit(Start);
699bf42cfd7SJustin Bogner     pushRegion(getRegionCounter(S), Start);
700ee02499aSAlex Lorenz     Visit(S->getSubStmt());
701ee02499aSAlex Lorenz   }
702ee02499aSAlex Lorenz 
703ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
704ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
705ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
706bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
7077f53fbfcSEli Friedman     // FIXME: a break in a switch should terminate regions for all preceding
7087f53fbfcSEli Friedman     // case statements, not just the most recent one.
709bf42cfd7SJustin Bogner     terminateRegion(S);
710ee02499aSAlex Lorenz   }
711ee02499aSAlex Lorenz 
712ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
713ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
714ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
715bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
716bf42cfd7SJustin Bogner     terminateRegion(S);
717ee02499aSAlex Lorenz   }
718ee02499aSAlex Lorenz 
719*181dfe4cSEli Friedman   void VisitCallExpr(const CallExpr *E) {
720*181dfe4cSEli Friedman     VisitStmt(E);
721*181dfe4cSEli Friedman 
722*181dfe4cSEli Friedman     // Terminate the region when we hit a noreturn function.
723*181dfe4cSEli Friedman     // (This is helpful dealing with switch statements.)
724*181dfe4cSEli Friedman     QualType CalleeType = E->getCallee()->getType();
725*181dfe4cSEli Friedman     if (getFunctionExtInfo(*CalleeType).getNoReturn())
726*181dfe4cSEli Friedman       terminateRegion(E);
727*181dfe4cSEli Friedman   }
728*181dfe4cSEli Friedman 
729ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
730bf42cfd7SJustin Bogner     extendRegion(S);
731ee02499aSAlex Lorenz 
732bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
733bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
734bf42cfd7SJustin Bogner 
735bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
736bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
737bf42cfd7SJustin Bogner     extendRegion(S->getBody());
738bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
739ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
740bf42cfd7SJustin Bogner 
741bf42cfd7SJustin Bogner     // Go back to handle the condition.
742bf42cfd7SJustin Bogner     Counter CondCount =
743bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
744bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
745bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
746bf42cfd7SJustin Bogner 
747bf42cfd7SJustin Bogner     Counter OutCount =
748bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
749bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
750bf42cfd7SJustin Bogner       pushRegion(OutCount);
751ee02499aSAlex Lorenz   }
752ee02499aSAlex Lorenz 
753ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
754bf42cfd7SJustin Bogner     extendRegion(S);
755ee02499aSAlex Lorenz 
756bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
757bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
758bf42cfd7SJustin Bogner 
759bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
760bf42cfd7SJustin Bogner     extendRegion(S->getBody());
761bf42cfd7SJustin Bogner     Counter BackedgeCount =
762bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
763ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
764bf42cfd7SJustin Bogner 
765bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
766bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
767bf42cfd7SJustin Bogner 
768bf42cfd7SJustin Bogner     Counter OutCount =
769bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
770bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
771bf42cfd7SJustin Bogner       pushRegion(OutCount);
772ee02499aSAlex Lorenz   }
773ee02499aSAlex Lorenz 
774ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
775bf42cfd7SJustin Bogner     extendRegion(S);
776ee02499aSAlex Lorenz     if (S->getInit())
777ee02499aSAlex Lorenz       Visit(S->getInit());
778ee02499aSAlex Lorenz 
779bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
780bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
781bf42cfd7SJustin Bogner 
782bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
783ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
784bf42cfd7SJustin Bogner     extendRegion(S->getBody());
785bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
786bf42cfd7SJustin Bogner     BreakContinue BC = BreakContinueStack.pop_back_val();
787ee02499aSAlex Lorenz 
788ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
789ee02499aSAlex Lorenz     // the count for all the continue statements.
790bf42cfd7SJustin Bogner     if (const Stmt *Inc = S->getInc())
791bf42cfd7SJustin Bogner       propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
792bf42cfd7SJustin Bogner 
793bf42cfd7SJustin Bogner     // Go back to handle the condition.
794bf42cfd7SJustin Bogner     Counter CondCount =
795bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
796bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
797bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
798bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
799ee02499aSAlex Lorenz     }
800ee02499aSAlex Lorenz 
801bf42cfd7SJustin Bogner     Counter OutCount =
802bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
803bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
804bf42cfd7SJustin Bogner       pushRegion(OutCount);
805ee02499aSAlex Lorenz   }
806ee02499aSAlex Lorenz 
807ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
808bf42cfd7SJustin Bogner     extendRegion(S);
809bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
810ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
811bf42cfd7SJustin Bogner 
812bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
813bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
814bf42cfd7SJustin Bogner 
815ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
816bf42cfd7SJustin Bogner     extendRegion(S->getBody());
817bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
818ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
819bf42cfd7SJustin Bogner 
8201587432dSJustin Bogner     Counter LoopCount =
8211587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
8221587432dSJustin Bogner     Counter OutCount =
8231587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
824bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
825bf42cfd7SJustin Bogner       pushRegion(OutCount);
826ee02499aSAlex Lorenz   }
827ee02499aSAlex Lorenz 
828ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
829bf42cfd7SJustin Bogner     extendRegion(S);
830ee02499aSAlex Lorenz     Visit(S->getElement());
831bf42cfd7SJustin Bogner 
832bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
833bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
834bf42cfd7SJustin Bogner 
835ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
836bf42cfd7SJustin Bogner     extendRegion(S->getBody());
837bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
838ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
839bf42cfd7SJustin Bogner 
8401587432dSJustin Bogner     Counter LoopCount =
8411587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
8421587432dSJustin Bogner     Counter OutCount =
8431587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
844bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
845bf42cfd7SJustin Bogner       pushRegion(OutCount);
846ee02499aSAlex Lorenz   }
847ee02499aSAlex Lorenz 
848ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
849bf42cfd7SJustin Bogner     extendRegion(S);
850f2a6ec55SVedant Kumar     if (S->getInit())
851f2a6ec55SVedant Kumar       Visit(S->getInit());
852ee02499aSAlex Lorenz     Visit(S->getCond());
853bf42cfd7SJustin Bogner 
854ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
855bf42cfd7SJustin Bogner 
856bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
857bf42cfd7SJustin Bogner     extendRegion(Body);
858bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
859bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
8607f53fbfcSEli Friedman         // Make a region for the body of the switch.  If the body starts with
8617f53fbfcSEli Friedman         // a case, that case will reuse this region; otherwise, this covers
8627f53fbfcSEli Friedman         // the unreachable code at the beginning of the switch body.
863bf42cfd7SJustin Bogner         size_t Index =
8647f53fbfcSEli Friedman             pushRegion(Counter::getZero(), getStart(CS->body_front()));
865b5841332SRichard Trieu         for (const auto *Child : CS->children())
866bf42cfd7SJustin Bogner           Visit(Child);
8677f53fbfcSEli Friedman 
8687f53fbfcSEli Friedman         // Set the end for the body of the switch, if it isn't already set.
8697f53fbfcSEli Friedman         for (size_t i = RegionStack.size(); i != Index; --i) {
8707f53fbfcSEli Friedman           if (!RegionStack[i - 1].hasEndLoc())
8717f53fbfcSEli Friedman             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
8727f53fbfcSEli Friedman         }
8737f53fbfcSEli Friedman 
874bf42cfd7SJustin Bogner         popRegions(Index);
875ee02499aSAlex Lorenz       }
87687ea3b05SVedant Kumar     } else
877bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
878ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
879bf42cfd7SJustin Bogner 
880ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
881ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
882ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
883bf42cfd7SJustin Bogner 
884bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
8853836482aSVedant Kumar     SourceLocation ExitLoc = getEnd(S);
88608780529SAlex Lorenz     pushRegion(ExitCount);
88708780529SAlex Lorenz 
88808780529SAlex Lorenz     // Ensure that handleFileExit recognizes when the end location is located
88908780529SAlex Lorenz     // in a different file.
89008780529SAlex Lorenz     MostRecentLocation = getStart(S);
8913836482aSVedant Kumar     handleFileExit(ExitLoc);
892ee02499aSAlex Lorenz   }
893ee02499aSAlex Lorenz 
894bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
895bf42cfd7SJustin Bogner     extendRegion(S);
896ee02499aSAlex Lorenz 
897bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
898bf42cfd7SJustin Bogner 
899bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
900bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
901bf42cfd7SJustin Bogner     // the first case in a switch.
902bf42cfd7SJustin Bogner     if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
903bf42cfd7SJustin Bogner       Parent.setCounter(Count);
904bf42cfd7SJustin Bogner     else
905bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
906bf42cfd7SJustin Bogner 
907376c06c2SSanjay Patel     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
908bf42cfd7SJustin Bogner       Visit(CS->getLHS());
909bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
910bf42cfd7SJustin Bogner         Visit(RHS);
911bf42cfd7SJustin Bogner     }
912ee02499aSAlex Lorenz     Visit(S->getSubStmt());
913ee02499aSAlex Lorenz   }
914ee02499aSAlex Lorenz 
915ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
916bf42cfd7SJustin Bogner     extendRegion(S);
9179d2a16b9SVedant Kumar     if (S->getInit())
9189d2a16b9SVedant Kumar       Visit(S->getInit());
9199d2a16b9SVedant Kumar 
920055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
921055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
922055ebc34SJustin Bogner     extendRegion(S->getCond());
923ee02499aSAlex Lorenz 
924bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
925bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
926ee02499aSAlex Lorenz 
92791f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
92891f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
92991f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
93091f2e3c9SJustin Bogner 
931bf42cfd7SJustin Bogner     extendRegion(S->getThen());
932bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
933bf42cfd7SJustin Bogner 
934bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
935bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
936bf42cfd7SJustin Bogner       extendRegion(S->getElse());
937bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
938bf42cfd7SJustin Bogner     } else
939bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
940bf42cfd7SJustin Bogner 
941bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
942bf42cfd7SJustin Bogner       pushRegion(OutCount);
943ee02499aSAlex Lorenz   }
944ee02499aSAlex Lorenz 
945ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
946bf42cfd7SJustin Bogner     extendRegion(S);
947049908b2SVedant Kumar     // Handle macros that generate the "try" but not the rest.
948049908b2SVedant Kumar     extendRegion(S->getTryBlock());
949049908b2SVedant Kumar 
950049908b2SVedant Kumar     Counter ParentCount = getRegion().getCounter();
951049908b2SVedant Kumar     propagateCounts(ParentCount, S->getTryBlock());
952049908b2SVedant Kumar 
953ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
954ee02499aSAlex Lorenz       Visit(S->getHandler(I));
955bf42cfd7SJustin Bogner 
956bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
957bf42cfd7SJustin Bogner     pushRegion(ExitCount);
958ee02499aSAlex Lorenz   }
959ee02499aSAlex Lorenz 
960ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
961bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
962ee02499aSAlex Lorenz   }
963ee02499aSAlex Lorenz 
964ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
965bf42cfd7SJustin Bogner     extendRegion(E);
966ee02499aSAlex Lorenz 
967bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
968bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
969ee02499aSAlex Lorenz 
970e3654ce7SJustin Bogner     Visit(E->getCond());
971e3654ce7SJustin Bogner 
972e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
973e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
974bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
975e3654ce7SJustin Bogner     }
976e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
977bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
978bf42cfd7SJustin Bogner                     E->getFalseExpr());
979ee02499aSAlex Lorenz   }
980ee02499aSAlex Lorenz 
981ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
982bf42cfd7SJustin Bogner     extendRegion(E);
983ee02499aSAlex Lorenz     Visit(E->getLHS());
984bf42cfd7SJustin Bogner 
985bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
986bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
987ee02499aSAlex Lorenz   }
988ee02499aSAlex Lorenz 
989ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
990bf42cfd7SJustin Bogner     extendRegion(E);
991ee02499aSAlex Lorenz     Visit(E->getLHS());
992ee02499aSAlex Lorenz 
993bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
994bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
99501a0d062SAlex Lorenz   }
996c109102eSJustin Bogner 
997c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
998c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
999c109102eSJustin Bogner     // propagate counts into them.
1000c109102eSJustin Bogner   }
1001ee02499aSAlex Lorenz };
1002ee02499aSAlex Lorenz 
10031f39fcf2SXinliang David Li std::string getCoverageSection(const CodeGenModule &CGM) {
10048a767a43SVedant Kumar   return llvm::getInstrProfSectionName(
10058a767a43SVedant Kumar       llvm::IPSK_covmap,
10068a767a43SVedant Kumar       CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1007ee02499aSAlex Lorenz }
1008ee02499aSAlex Lorenz 
100914f8fb68SVedant Kumar std::string normalizeFilename(StringRef Filename) {
101014f8fb68SVedant Kumar   llvm::SmallString<256> Path(Filename);
101114f8fb68SVedant Kumar   llvm::sys::fs::make_absolute(Path);
1012d04929d8SVedant Kumar   llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
101314f8fb68SVedant Kumar   return Path.str().str();
101414f8fb68SVedant Kumar }
101514f8fb68SVedant Kumar 
101614f8fb68SVedant Kumar } // end anonymous namespace
101714f8fb68SVedant Kumar 
1018a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1019a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
1020a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
1021a432d176SJustin Bogner   OS << FunctionName << ":\n";
1022a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
1023a432d176SJustin Bogner   for (const auto &R : Regions) {
1024f2cf38e0SAlex Lorenz     OS.indent(2);
1025f2cf38e0SAlex Lorenz     switch (R.Kind) {
1026f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
1027f2cf38e0SAlex Lorenz       break;
1028f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
1029f2cf38e0SAlex Lorenz       OS << "Expansion,";
1030f2cf38e0SAlex Lorenz       break;
1031f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
1032f2cf38e0SAlex Lorenz       OS << "Skipped,";
1033f2cf38e0SAlex Lorenz       break;
1034f2cf38e0SAlex Lorenz     }
1035f2cf38e0SAlex Lorenz 
10364da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
10374da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1038f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
1039f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
10404da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
10414da909b2SJustin Bogner     OS << "\n";
1042f2cf38e0SAlex Lorenz   }
1043f2cf38e0SAlex Lorenz }
1044f2cf38e0SAlex Lorenz 
1045ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord(
10462129ae53SXinliang David Li     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1047848da137SXinliang David Li     const std::string &CoverageMapping, bool IsUsed) {
1048ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1049ee02499aSAlex Lorenz   if (!FunctionRecordTy) {
1050a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1051a026a437SXinliang David Li     llvm::Type *FunctionRecordTypes[] = {
1052a026a437SXinliang David Li       #include "llvm/ProfileData/InstrProfData.inc"
1053a026a437SXinliang David Li     };
1054ee02499aSAlex Lorenz     FunctionRecordTy =
10554dc5adc7SJustin Bogner         llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
10564dc5adc7SJustin Bogner                               /*isPacked=*/true);
1057ee02499aSAlex Lorenz   }
1058ee02499aSAlex Lorenz 
1059a026a437SXinliang David Li   #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1060ee02499aSAlex Lorenz   llvm::Constant *FunctionRecordVals[] = {
1061a026a437SXinliang David Li       #include "llvm/ProfileData/InstrProfData.inc"
1062a026a437SXinliang David Li   };
1063ee02499aSAlex Lorenz   FunctionRecords.push_back(llvm::ConstantStruct::get(
1064ee02499aSAlex Lorenz       FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
1065848da137SXinliang David Li   if (!IsUsed)
10662129ae53SXinliang David Li     FunctionNames.push_back(
10672129ae53SXinliang David Li         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1068ca3326c0SVedant Kumar   CoverageMappings.push_back(CoverageMapping);
1069f2cf38e0SAlex Lorenz 
1070f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1071f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1072f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1073f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1074f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1075f2cf38e0SAlex Lorenz     // expressions.
1076f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1077f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1078f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
1079b31ee819SJordan Rose     llvm::SmallVector<std::string, 16> FilenameStrs;
1080f2cf38e0SAlex Lorenz     llvm::SmallVector<StringRef, 16> FilenameRefs;
1081b31ee819SJordan Rose     FilenameStrs.resize(FileEntries.size());
1082f2cf38e0SAlex Lorenz     FilenameRefs.resize(FileEntries.size());
1083b31ee819SJordan Rose     for (const auto &Entry : FileEntries) {
1084b31ee819SJordan Rose       auto I = Entry.second;
1085b31ee819SJordan Rose       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1086b31ee819SJordan Rose       FilenameRefs[I] = FilenameStrs[I];
1087b31ee819SJordan Rose     }
1088a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1089a432d176SJustin Bogner                                     Expressions, Regions);
1090a432d176SJustin Bogner     if (Reader.read())
1091f2cf38e0SAlex Lorenz       return;
1092a026a437SXinliang David Li     dump(llvm::outs(), NameValue, Expressions, Regions);
1093f2cf38e0SAlex Lorenz   }
1094ee02499aSAlex Lorenz }
1095ee02499aSAlex Lorenz 
1096ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1097ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1098ee02499aSAlex Lorenz     return;
1099ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1100ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1101ee02499aSAlex Lorenz 
1102ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1103ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
11049e324dd1SVedant Kumar   llvm::SmallVector<StringRef, 16> FilenameRefs;
1105ee02499aSAlex Lorenz   FilenameStrs.resize(FileEntries.size());
11069e324dd1SVedant Kumar   FilenameRefs.resize(FileEntries.size());
1107ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1108ee02499aSAlex Lorenz     auto I = Entry.second;
110914f8fb68SVedant Kumar     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
11109e324dd1SVedant Kumar     FilenameRefs[I] = FilenameStrs[I];
1111ee02499aSAlex Lorenz   }
1112ee02499aSAlex Lorenz 
11139e324dd1SVedant Kumar   std::string FilenamesAndCoverageMappings;
11149e324dd1SVedant Kumar   llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
11159e324dd1SVedant Kumar   CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
11169e324dd1SVedant Kumar   std::string RawCoverageMappings =
11179e324dd1SVedant Kumar       llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
11189e324dd1SVedant Kumar   OS << RawCoverageMappings;
11199e324dd1SVedant Kumar   size_t CoverageMappingSize = RawCoverageMappings.size();
11209e324dd1SVedant Kumar   size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
11219e324dd1SVedant Kumar   // Append extra zeroes if necessary to ensure that the size of the filenames
11229e324dd1SVedant Kumar   // and coverage mappings is a multiple of 8.
11239e324dd1SVedant Kumar   if (size_t Rem = OS.str().size() % 8) {
11249e324dd1SVedant Kumar     CoverageMappingSize += 8 - Rem;
11259e324dd1SVedant Kumar     for (size_t I = 0, S = 8 - Rem; I < S; ++I)
11269e324dd1SVedant Kumar       OS << '\0';
1127ee02499aSAlex Lorenz   }
1128ee02499aSAlex Lorenz   auto *FilenamesAndMappingsVal =
11299e324dd1SVedant Kumar       llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
1130ee02499aSAlex Lorenz 
1131ee02499aSAlex Lorenz   // Create the deferred function records array
1132ee02499aSAlex Lorenz   auto RecordsTy =
1133ee02499aSAlex Lorenz       llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1134ee02499aSAlex Lorenz   auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1135ee02499aSAlex Lorenz 
113620b188c0SXinliang David Li   llvm::Type *CovDataHeaderTypes[] = {
113720b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
113820b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
113920b188c0SXinliang David Li   };
114020b188c0SXinliang David Li   auto CovDataHeaderTy =
114120b188c0SXinliang David Li       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
114220b188c0SXinliang David Li   llvm::Constant *CovDataHeaderVals[] = {
114320b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
114420b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
114520b188c0SXinliang David Li   };
114620b188c0SXinliang David Li   auto CovDataHeaderVal = llvm::ConstantStruct::get(
114720b188c0SXinliang David Li       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
114820b188c0SXinliang David Li 
1149ee02499aSAlex Lorenz   // Create the coverage data record
115020b188c0SXinliang David Li   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
115120b188c0SXinliang David Li                                 FilenamesAndMappingsVal->getType()};
1152ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
115320b188c0SXinliang David Li   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
115420b188c0SXinliang David Li                                   FilenamesAndMappingsVal};
1155ee02499aSAlex Lorenz   auto CovDataVal =
1156ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
115720b188c0SXinliang David Li   auto CovData = new llvm::GlobalVariable(
115820b188c0SXinliang David Li       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
115920b188c0SXinliang David Li       CovDataVal, llvm::getCoverageMappingVarName());
1160ee02499aSAlex Lorenz 
1161ee02499aSAlex Lorenz   CovData->setSection(getCoverageSection(CGM));
1162ee02499aSAlex Lorenz   CovData->setAlignment(8);
1163ee02499aSAlex Lorenz 
1164ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1165ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
11662129ae53SXinliang David Li   // Create the deferred function records array
11672129ae53SXinliang David Li   if (!FunctionNames.empty()) {
11682129ae53SXinliang David Li     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
11692129ae53SXinliang David Li                                            FunctionNames.size());
11702129ae53SXinliang David Li     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
11712129ae53SXinliang David Li     // This variable will *NOT* be emitted to the object file. It is used
11722129ae53SXinliang David Li     // to pass the list of names referenced to codegen.
11732129ae53SXinliang David Li     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
11742129ae53SXinliang David Li                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
11757077f0afSXinliang David Li                              llvm::getCoverageUnusedNamesVarName());
11762129ae53SXinliang David Li   }
1177ee02499aSAlex Lorenz }
1178ee02499aSAlex Lorenz 
1179ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1180ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1181ee02499aSAlex Lorenz   if (It != FileEntries.end())
1182ee02499aSAlex Lorenz     return It->second;
1183ee02499aSAlex Lorenz   unsigned FileID = FileEntries.size();
1184ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1185ee02499aSAlex Lorenz   return FileID;
1186ee02499aSAlex Lorenz }
1187ee02499aSAlex Lorenz 
1188ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1189ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1190ee02499aSAlex Lorenz   assert(CounterMap);
1191e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1192ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1193ee02499aSAlex Lorenz   Walker.write(OS);
1194ee02499aSAlex Lorenz }
1195ee02499aSAlex Lorenz 
1196ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1197ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1198ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1199ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1200ee02499aSAlex Lorenz   Walker.write(OS);
1201ee02499aSAlex Lorenz }
1202