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 
323919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
33ee02499aSAlex Lorenz   SkippedRanges.push_back(Range);
34ee02499aSAlex Lorenz }
35ee02499aSAlex Lorenz 
36ee02499aSAlex Lorenz namespace {
37ee02499aSAlex Lorenz 
389fc8faf9SAdrian Prantl /// A region of source code that can be mapped to a counter.
3909c7179bSJustin Bogner class SourceMappingRegion {
40ee02499aSAlex Lorenz   Counter Count;
41ee02499aSAlex Lorenz 
429fc8faf9SAdrian Prantl   /// The region's starting location.
43bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
44ee02499aSAlex Lorenz 
459fc8faf9SAdrian Prantl   /// The region's ending location.
46bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
47ee02499aSAlex Lorenz 
48747b0e29SVedant Kumar   /// Whether this region should be emitted after its parent is emitted.
49747b0e29SVedant Kumar   bool DeferRegion;
50747b0e29SVedant Kumar 
51a1c4deb7SVedant Kumar   /// Whether this region is a gap region. The count from a gap region is set
52a1c4deb7SVedant Kumar   /// as the line execution count if there are no other regions on the line.
53a1c4deb7SVedant Kumar   bool GapRegion;
54a1c4deb7SVedant Kumar 
5509c7179bSJustin Bogner public:
56bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
57a1c4deb7SVedant Kumar                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
58a1c4deb7SVedant Kumar                       bool GapRegion = false)
59747b0e29SVedant Kumar       : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
60a1c4deb7SVedant Kumar         DeferRegion(DeferRegion), GapRegion(GapRegion) {}
61ee02499aSAlex Lorenz 
6209c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
6309c7179bSJustin Bogner 
64bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
6509c7179bSJustin Bogner 
66bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
67bf42cfd7SJustin Bogner 
68bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
69bf42cfd7SJustin Bogner 
703cffc4c7SStephen Kelly   SourceLocation getStartLoc() const LLVM_READONLY { return getBeginLoc(); }
713cffc4c7SStephen Kelly   SourceLocation getBeginLoc() const {
72bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
73bf42cfd7SJustin Bogner     return *LocStart;
7409c7179bSJustin Bogner   }
7509c7179bSJustin Bogner 
76bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
77ee02499aSAlex Lorenz 
78a14a1f92SVedant Kumar   void setEndLoc(SourceLocation Loc) {
79a14a1f92SVedant Kumar     assert(Loc.isValid() && "Setting an invalid end location");
80a14a1f92SVedant Kumar     LocEnd = Loc;
81a14a1f92SVedant Kumar   }
82ee02499aSAlex Lorenz 
83462c77b4SCraig Topper   SourceLocation getEndLoc() const {
84bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
85bf42cfd7SJustin Bogner     return *LocEnd;
86ee02499aSAlex Lorenz   }
87747b0e29SVedant Kumar 
88747b0e29SVedant Kumar   bool isDeferred() const { return DeferRegion; }
89747b0e29SVedant Kumar 
90747b0e29SVedant Kumar   void setDeferred(bool Deferred) { DeferRegion = Deferred; }
91a1c4deb7SVedant Kumar 
92a1c4deb7SVedant Kumar   bool isGap() const { return GapRegion; }
93a1c4deb7SVedant Kumar 
94a1c4deb7SVedant Kumar   void setGap(bool Gap) { GapRegion = Gap; }
95ee02499aSAlex Lorenz };
96ee02499aSAlex Lorenz 
97d7369648SVedant Kumar /// Spelling locations for the start and end of a source region.
98d7369648SVedant Kumar struct SpellingRegion {
99d7369648SVedant Kumar   /// The line where the region starts.
100d7369648SVedant Kumar   unsigned LineStart;
101d7369648SVedant Kumar 
102d7369648SVedant Kumar   /// The column where the region starts.
103d7369648SVedant Kumar   unsigned ColumnStart;
104d7369648SVedant Kumar 
105d7369648SVedant Kumar   /// The line where the region ends.
106d7369648SVedant Kumar   unsigned LineEnd;
107d7369648SVedant Kumar 
108d7369648SVedant Kumar   /// The column where the region ends.
109d7369648SVedant Kumar   unsigned ColumnEnd;
110d7369648SVedant Kumar 
111d7369648SVedant Kumar   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
112d7369648SVedant Kumar                  SourceLocation LocEnd) {
113d7369648SVedant Kumar     LineStart = SM.getSpellingLineNumber(LocStart);
114d7369648SVedant Kumar     ColumnStart = SM.getSpellingColumnNumber(LocStart);
115d7369648SVedant Kumar     LineEnd = SM.getSpellingLineNumber(LocEnd);
116d7369648SVedant Kumar     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
117d7369648SVedant Kumar   }
118d7369648SVedant Kumar 
119fa8fa044SVedant Kumar   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
120a6e4358fSStephen Kelly       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
121fa8fa044SVedant Kumar 
122d7369648SVedant Kumar   /// Check if the start and end locations appear in source order, i.e
123d7369648SVedant Kumar   /// top->bottom, left->right.
124d7369648SVedant Kumar   bool isInSourceOrder() const {
125d7369648SVedant Kumar     return (LineStart < LineEnd) ||
126d7369648SVedant Kumar            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
127d7369648SVedant Kumar   }
128d7369648SVedant Kumar };
129d7369648SVedant Kumar 
1309fc8faf9SAdrian Prantl /// Provides the common functionality for the different
131ee02499aSAlex Lorenz /// coverage mapping region builders.
132ee02499aSAlex Lorenz class CoverageMappingBuilder {
133ee02499aSAlex Lorenz public:
134ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
135ee02499aSAlex Lorenz   SourceManager &SM;
136ee02499aSAlex Lorenz   const LangOptions &LangOpts;
137ee02499aSAlex Lorenz 
138ee02499aSAlex Lorenz private:
1399fc8faf9SAdrian Prantl   /// Map of clang's FileIDs to IDs used for coverage mapping.
140bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
141bf42cfd7SJustin Bogner       FileIDMapping;
142ee02499aSAlex Lorenz 
143ee02499aSAlex Lorenz public:
1449fc8faf9SAdrian Prantl   /// The coverage mapping regions for this function
145ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
1469fc8faf9SAdrian Prantl   /// The source mapping regions for this function.
147f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
148ee02499aSAlex Lorenz 
1499fc8faf9SAdrian Prantl   /// A set of regions which can be used as a filter.
150fc05ee34SIgor Kudrin   ///
151fc05ee34SIgor Kudrin   /// It is produced by emitExpansionRegions() and is used in
152fc05ee34SIgor Kudrin   /// emitSourceRegions() to suppress producing code regions if
153fc05ee34SIgor Kudrin   /// the same area is covered by expansion regions.
154fc05ee34SIgor Kudrin   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
155fc05ee34SIgor Kudrin       SourceRegionFilter;
156fc05ee34SIgor Kudrin 
157ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
158ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
159bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
160ee02499aSAlex Lorenz 
1619fc8faf9SAdrian Prantl   /// Return the precise end location for the given token.
162ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
163bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
164bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
165bf42cfd7SJustin Bogner     unsigned TokLen =
166bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
167bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
168ee02499aSAlex Lorenz   }
169ee02499aSAlex Lorenz 
1709fc8faf9SAdrian Prantl   /// Return the start location of an included file or expanded macro.
171bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
172bf42cfd7SJustin Bogner     if (Loc.isMacroID())
173bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
174bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
175ee02499aSAlex Lorenz   }
176ee02499aSAlex Lorenz 
1779fc8faf9SAdrian Prantl   /// Return the end location of an included file or expanded macro.
178bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
179bf42cfd7SJustin Bogner     if (Loc.isMacroID())
180bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
181f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
182bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
183bf42cfd7SJustin Bogner   }
184ee02499aSAlex Lorenz 
1859fc8faf9SAdrian Prantl   /// Find out where the current file is included or macro is expanded.
186bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
187b5f8171aSRichard Smith     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
188bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
189bf42cfd7SJustin Bogner   }
190bf42cfd7SJustin Bogner 
1919fc8faf9SAdrian Prantl   /// Return true if \c Loc is a location in a built-in macro.
192682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
19399d1b295SMehdi Amini     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
194682bfbf3SJustin Bogner   }
195682bfbf3SJustin Bogner 
1969fc8faf9SAdrian Prantl   /// Check whether \c Loc is included or expanded from \c Parent.
197d9e1a61dSIgor Kudrin   bool isNestedIn(SourceLocation Loc, FileID Parent) {
198d9e1a61dSIgor Kudrin     do {
199d9e1a61dSIgor Kudrin       Loc = getIncludeOrExpansionLoc(Loc);
200d9e1a61dSIgor Kudrin       if (Loc.isInvalid())
201d9e1a61dSIgor Kudrin         return false;
202d9e1a61dSIgor Kudrin     } while (!SM.isInFileID(Loc, Parent));
203d9e1a61dSIgor Kudrin     return true;
204d9e1a61dSIgor Kudrin   }
205d9e1a61dSIgor Kudrin 
2069fc8faf9SAdrian Prantl   /// Get the start of \c S ignoring macro arguments and builtin macros.
207bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
208*f2ceec48SStephen Kelly     SourceLocation Loc = S->getBeginLoc();
209682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
210b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
211bf42cfd7SJustin Bogner     return Loc;
212bf42cfd7SJustin Bogner   }
213bf42cfd7SJustin Bogner 
2149fc8faf9SAdrian Prantl   /// Get the end of \c S ignoring macro arguments and builtin macros.
215bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
216bf42cfd7SJustin Bogner     SourceLocation Loc = S->getLocEnd();
217682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
218b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
219f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
220bf42cfd7SJustin Bogner   }
221bf42cfd7SJustin Bogner 
2229fc8faf9SAdrian Prantl   /// Find the set of files we have regions for and assign IDs
223bf42cfd7SJustin Bogner   ///
224bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
225bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
226bf42cfd7SJustin Bogner   /// expansion regions.
227bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
228bf42cfd7SJustin Bogner     FileIDMapping.clear();
229bf42cfd7SJustin Bogner 
230bc6b80a0SVedant Kumar     llvm::SmallSet<FileID, 8> Visited;
231bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
232bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
233a6e4358fSStephen Kelly       SourceLocation Loc = Region.getBeginLoc();
234bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
235bc6b80a0SVedant Kumar       if (!Visited.insert(File).second)
236bf42cfd7SJustin Bogner         continue;
237bf42cfd7SJustin Bogner 
23893205af0SVedant Kumar       // Do not map FileID's associated with system headers.
23993205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
24093205af0SVedant Kumar         continue;
24193205af0SVedant Kumar 
242bf42cfd7SJustin Bogner       unsigned Depth = 0;
243bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
244ed1fe5d0SYaron Keren            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
245bf42cfd7SJustin Bogner         ++Depth;
246bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
247bf42cfd7SJustin Bogner     }
248bf42cfd7SJustin Bogner     std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
249bf42cfd7SJustin Bogner 
250bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
251bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
252bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
253ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
254ee02499aSAlex Lorenz       if (!Entry)
255bf42cfd7SJustin Bogner         continue;
256ee02499aSAlex Lorenz 
257bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
258bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
259bf42cfd7SJustin Bogner     }
260ee02499aSAlex Lorenz   }
261ee02499aSAlex Lorenz 
2629fc8faf9SAdrian Prantl   /// Get the coverage mapping file ID for \c Loc.
263bf42cfd7SJustin Bogner   ///
264bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
265bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
266bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
267bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
268bf42cfd7SJustin Bogner       return Mapping->second.first;
269903678caSJustin Bogner     return None;
270ee02499aSAlex Lorenz   }
271ee02499aSAlex Lorenz 
2729fc8faf9SAdrian Prantl   /// Gather all the regions that were skipped by the preprocessor
273ee02499aSAlex Lorenz   /// using the constructs like #if.
274ee02499aSAlex Lorenz   void gatherSkippedRegions() {
275ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
276ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
277ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
278ee02499aSAlex Lorenz     FileLineRanges.resize(
279ee02499aSAlex Lorenz         FileIDMapping.size(),
280ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
281ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
282ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
283ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
284ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
285ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
286ee02499aSAlex Lorenz     }
287ee02499aSAlex Lorenz 
288ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
289ee02499aSAlex Lorenz     for (const auto &I : SkippedRanges) {
290ee02499aSAlex Lorenz       auto LocStart = I.getBegin();
291ee02499aSAlex Lorenz       auto LocEnd = I.getEnd();
292bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
293bf42cfd7SJustin Bogner              "region spans multiple files");
294ee02499aSAlex Lorenz 
295bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
296903678caSJustin Bogner       if (!CovFileID)
297ee02499aSAlex Lorenz         continue;
298d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
299fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
300d7369648SVedant Kumar           *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
301ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
3022a8c18d9SAlexander Kornienko       // the source code of this function.
303903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
304903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
305ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
306ee02499aSAlex Lorenz     }
307ee02499aSAlex Lorenz   }
308ee02499aSAlex Lorenz 
3099fc8faf9SAdrian Prantl   /// Generate the coverage counter mapping regions from collected
310ee02499aSAlex Lorenz   /// source regions.
311fc05ee34SIgor Kudrin   void emitSourceRegions(const SourceRegionFilter &Filter) {
312bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
313bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
314ee02499aSAlex Lorenz 
315a6e4358fSStephen Kelly       SourceLocation LocStart = Region.getBeginLoc();
3168b563665SYaron Keren       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
317f59329b0SJustin Bogner 
31893205af0SVedant Kumar       // Ignore regions from system headers.
31993205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
32093205af0SVedant Kumar         continue;
32193205af0SVedant Kumar 
322bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
323bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
324bf42cfd7SJustin Bogner       if (!CovFileID)
325ee02499aSAlex Lorenz         continue;
326ee02499aSAlex Lorenz 
327f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
328bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
329bf42cfd7SJustin Bogner              "region spans multiple files");
330bf42cfd7SJustin Bogner 
331fc05ee34SIgor Kudrin       // Don't add code regions for the area covered by expansion regions.
332fc05ee34SIgor Kudrin       // This not only suppresses redundant regions, but sometimes prevents
333fc05ee34SIgor Kudrin       // creating regions with wrong counters if, for example, a statement's
334fc05ee34SIgor Kudrin       // body ends at the end of a nested macro.
335fc05ee34SIgor Kudrin       if (Filter.count(std::make_pair(LocStart, LocEnd)))
336fc05ee34SIgor Kudrin         continue;
337fc05ee34SIgor Kudrin 
338d7369648SVedant Kumar       // Find the spelling locations for the mapping region.
339d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
340d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
341a1c4deb7SVedant Kumar 
342a1c4deb7SVedant Kumar       if (Region.isGap()) {
343a1c4deb7SVedant Kumar         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
344a1c4deb7SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
345a1c4deb7SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
346a1c4deb7SVedant Kumar       } else {
347bf42cfd7SJustin Bogner         MappingRegions.push_back(CounterMappingRegion::makeRegion(
348d7369648SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
349d7369648SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
350bf42cfd7SJustin Bogner       }
351bf42cfd7SJustin Bogner     }
352a1c4deb7SVedant Kumar   }
353bf42cfd7SJustin Bogner 
3549fc8faf9SAdrian Prantl   /// Generate expansion regions for each virtual file we've seen.
355fc05ee34SIgor Kudrin   SourceRegionFilter emitExpansionRegions() {
356fc05ee34SIgor Kudrin     SourceRegionFilter Filter;
357bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
358bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
359bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
360bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
361ee02499aSAlex Lorenz         continue;
362ee02499aSAlex Lorenz 
363bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
364bf42cfd7SJustin Bogner       if (!ParentFileID)
365bf42cfd7SJustin Bogner         continue;
366bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
367bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
368bf42cfd7SJustin Bogner 
369bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
370bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
371bf42cfd7SJustin Bogner              "region spans multiple files");
372fc05ee34SIgor Kudrin       Filter.insert(std::make_pair(ParentLoc, LocEnd));
373bf42cfd7SJustin Bogner 
374d7369648SVedant Kumar       SpellingRegion SR{SM, ParentLoc, LocEnd};
375d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
376bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
377d7369648SVedant Kumar           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
378d7369648SVedant Kumar           SR.LineEnd, SR.ColumnEnd));
379ee02499aSAlex Lorenz     }
380fc05ee34SIgor Kudrin     return Filter;
381ee02499aSAlex Lorenz   }
382ee02499aSAlex Lorenz };
383ee02499aSAlex Lorenz 
3849fc8faf9SAdrian Prantl /// Creates unreachable coverage regions for the functions that
385ee02499aSAlex Lorenz /// are not emitted.
386ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
387ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
388ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
389ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
390ee02499aSAlex Lorenz 
391ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
392ee02499aSAlex Lorenz     if (!D->hasBody())
393ee02499aSAlex Lorenz       return;
394ee02499aSAlex Lorenz     auto Body = D->getBody();
395d9e1a61dSIgor Kudrin     SourceLocation Start = getStart(Body);
396d9e1a61dSIgor Kudrin     SourceLocation End = getEnd(Body);
397d9e1a61dSIgor Kudrin     if (!SM.isWrittenInSameFile(Start, End)) {
398d9e1a61dSIgor Kudrin       // Walk up to find the common ancestor.
399d9e1a61dSIgor Kudrin       // Correct the locations accordingly.
400d9e1a61dSIgor Kudrin       FileID StartFileID = SM.getFileID(Start);
401d9e1a61dSIgor Kudrin       FileID EndFileID = SM.getFileID(End);
402d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
403d9e1a61dSIgor Kudrin         Start = getIncludeOrExpansionLoc(Start);
404d9e1a61dSIgor Kudrin         assert(Start.isValid() &&
405d9e1a61dSIgor Kudrin                "Declaration start location not nested within a known region");
406d9e1a61dSIgor Kudrin         StartFileID = SM.getFileID(Start);
407d9e1a61dSIgor Kudrin       }
408d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID) {
409d9e1a61dSIgor Kudrin         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
410d9e1a61dSIgor Kudrin         assert(End.isValid() &&
411d9e1a61dSIgor Kudrin                "Declaration end location not nested within a known region");
412d9e1a61dSIgor Kudrin         EndFileID = SM.getFileID(End);
413d9e1a61dSIgor Kudrin       }
414d9e1a61dSIgor Kudrin     }
415d9e1a61dSIgor Kudrin     SourceRegions.emplace_back(Counter(), Start, End);
416ee02499aSAlex Lorenz   }
417ee02499aSAlex Lorenz 
4189fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
419ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
420ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
421bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
422fc05ee34SIgor Kudrin     emitSourceRegions(SourceRegionFilter());
423ee02499aSAlex Lorenz 
424efd319a2SVedant Kumar     if (MappingRegions.empty())
425efd319a2SVedant Kumar       return;
426efd319a2SVedant Kumar 
4275fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
428ee02499aSAlex Lorenz     Writer.write(OS);
429ee02499aSAlex Lorenz   }
430ee02499aSAlex Lorenz };
431ee02499aSAlex Lorenz 
4329fc8faf9SAdrian Prantl /// A StmtVisitor that creates coverage mapping regions which map
433ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
434ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
435ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
436ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
4379fc8faf9SAdrian Prantl   /// The map of statements to count values.
438ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
439ee02499aSAlex Lorenz 
4409fc8faf9SAdrian Prantl   /// A stack of currently live regions.
441bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
442ee02499aSAlex Lorenz 
443747b0e29SVedant Kumar   /// The currently deferred region: its end location and count can be set once
444747b0e29SVedant Kumar   /// its parent has been popped from the region stack.
445747b0e29SVedant Kumar   Optional<SourceMappingRegion> DeferredRegion;
446747b0e29SVedant Kumar 
447ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
448ee02499aSAlex Lorenz 
4499fc8faf9SAdrian Prantl   /// A location in the most recently visited file or macro.
450bf42cfd7SJustin Bogner   ///
451bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
452bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
453bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
454bf42cfd7SJustin Bogner 
4558046d22aSVedant Kumar   /// Location of the last terminated region.
4568046d22aSVedant Kumar   Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
4578046d22aSVedant Kumar 
4589fc8faf9SAdrian Prantl   /// Return a counter for the subtraction of \c RHS from \c LHS
459ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
460ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
461ee02499aSAlex Lorenz   }
462ee02499aSAlex Lorenz 
4639fc8faf9SAdrian Prantl   /// Return a counter for the sum of \c LHS and \c RHS.
464ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
465ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
466ee02499aSAlex Lorenz   }
467ee02499aSAlex Lorenz 
468bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
469bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
470bf42cfd7SJustin Bogner   }
471bf42cfd7SJustin Bogner 
4729fc8faf9SAdrian Prantl   /// Return the region counter for the given statement.
473bf42cfd7SJustin Bogner   ///
474ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
475bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
476bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
477ee02499aSAlex Lorenz   }
478ee02499aSAlex Lorenz 
4799fc8faf9SAdrian Prantl   /// Push a region onto the stack.
480bf42cfd7SJustin Bogner   ///
481bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
482bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
483bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
484bf42cfd7SJustin Bogner                     Optional<SourceLocation> EndLoc = None) {
485747b0e29SVedant Kumar     if (StartLoc) {
486bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
487747b0e29SVedant Kumar       completeDeferred(Count, MostRecentLocation);
488747b0e29SVedant Kumar     }
489bf42cfd7SJustin Bogner     RegionStack.emplace_back(Count, StartLoc, EndLoc);
490ee02499aSAlex Lorenz 
491bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
492ee02499aSAlex Lorenz   }
493ee02499aSAlex Lorenz 
494747b0e29SVedant Kumar   /// Complete any pending deferred region by setting its end location and
495747b0e29SVedant Kumar   /// count, and then pushing it onto the region stack.
496747b0e29SVedant Kumar   size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
497747b0e29SVedant Kumar     size_t Index = RegionStack.size();
498747b0e29SVedant Kumar     if (!DeferredRegion)
499747b0e29SVedant Kumar       return Index;
500747b0e29SVedant Kumar 
501747b0e29SVedant Kumar     // Consume the pending region.
502747b0e29SVedant Kumar     SourceMappingRegion DR = DeferredRegion.getValue();
503747b0e29SVedant Kumar     DeferredRegion = None;
504747b0e29SVedant Kumar 
505747b0e29SVedant Kumar     // If the region ends in an expansion, find the expansion site.
506a6e4358fSStephen Kelly     FileID StartFile = SM.getFileID(DR.getBeginLoc());
507f9a0d44eSVedant Kumar     if (SM.getFileID(DeferredEndLoc) != StartFile) {
508747b0e29SVedant Kumar       if (isNestedIn(DeferredEndLoc, StartFile)) {
509747b0e29SVedant Kumar         do {
510747b0e29SVedant Kumar           DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
511747b0e29SVedant Kumar         } while (StartFile != SM.getFileID(DeferredEndLoc));
512f9a0d44eSVedant Kumar       } else {
513f9a0d44eSVedant Kumar         return Index;
514747b0e29SVedant Kumar       }
515747b0e29SVedant Kumar     }
516747b0e29SVedant Kumar 
517747b0e29SVedant Kumar     // The parent of this deferred region ends where the containing decl ends,
518747b0e29SVedant Kumar     // so the region isn't useful.
519a6e4358fSStephen Kelly     if (DR.getBeginLoc() == DeferredEndLoc)
520747b0e29SVedant Kumar       return Index;
521747b0e29SVedant Kumar 
522747b0e29SVedant Kumar     // If we're visiting statements in non-source order (e.g switch cases or
523747b0e29SVedant Kumar     // a loop condition) we can't construct a sensible deferred region.
524a6e4358fSStephen Kelly     if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
525747b0e29SVedant Kumar       return Index;
526747b0e29SVedant Kumar 
527a1c4deb7SVedant Kumar     DR.setGap(true);
528747b0e29SVedant Kumar     DR.setCounter(Count);
529747b0e29SVedant Kumar     DR.setEndLoc(DeferredEndLoc);
530747b0e29SVedant Kumar     handleFileExit(DeferredEndLoc);
531747b0e29SVedant Kumar     RegionStack.push_back(DR);
532747b0e29SVedant Kumar     return Index;
533747b0e29SVedant Kumar   }
534747b0e29SVedant Kumar 
5358046d22aSVedant Kumar   /// Complete a deferred region created after a terminated region at the
5368046d22aSVedant Kumar   /// top-level.
5378046d22aSVedant Kumar   void completeTopLevelDeferredRegion(Counter Count,
5388046d22aSVedant Kumar                                       SourceLocation DeferredEndLoc) {
5398046d22aSVedant Kumar     if (DeferredRegion || !LastTerminatedRegion)
5408046d22aSVedant Kumar       return;
5418046d22aSVedant Kumar 
5428046d22aSVedant Kumar     if (LastTerminatedRegion->second != RegionStack.size())
5438046d22aSVedant Kumar       return;
5448046d22aSVedant Kumar 
5458046d22aSVedant Kumar     SourceLocation Start = LastTerminatedRegion->first;
5468046d22aSVedant Kumar     if (SM.getFileID(Start) != SM.getMainFileID())
5478046d22aSVedant Kumar       return;
5488046d22aSVedant Kumar 
5498046d22aSVedant Kumar     SourceMappingRegion DR = RegionStack.back();
5508046d22aSVedant Kumar     DR.setStartLoc(Start);
5518046d22aSVedant Kumar     DR.setDeferred(false);
5528046d22aSVedant Kumar     DeferredRegion = DR;
5538046d22aSVedant Kumar     completeDeferred(Count, DeferredEndLoc);
5548046d22aSVedant Kumar   }
5558046d22aSVedant Kumar 
5569fc8faf9SAdrian Prantl   /// Pop regions from the stack into the function's list of regions.
557bf42cfd7SJustin Bogner   ///
558bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
559bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
560bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
561bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
562747b0e29SVedant Kumar     bool ParentOfDeferredRegion = false;
563bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
564bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
565bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
566a6e4358fSStephen Kelly         SourceLocation StartLoc = Region.getBeginLoc();
567bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
568bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
569bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
570bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
571bf42cfd7SJustin Bogner           // The region ends in a nested file or macro expansion. Create a
572bf42cfd7SJustin Bogner           // separate region for each expansion.
573bf42cfd7SJustin Bogner           SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
574bf42cfd7SJustin Bogner           assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
575bf42cfd7SJustin Bogner 
5768545dae2SIgor Kudrin           if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
577bf42cfd7SJustin Bogner             SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
578bf42cfd7SJustin Bogner 
579f14b2078SJustin Bogner           EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
580dceaaadfSJustin Bogner           if (EndLoc.isInvalid())
581dceaaadfSJustin Bogner             llvm::report_fatal_error("File exit not handled before popRegions");
582bf42cfd7SJustin Bogner         }
583bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
584bf42cfd7SJustin Bogner 
585bf42cfd7SJustin Bogner         MostRecentLocation = EndLoc;
586bf42cfd7SJustin Bogner         // If this region happens to span an entire expansion, we need to make
587bf42cfd7SJustin Bogner         // sure we don't overlap the parent region with it.
588bf42cfd7SJustin Bogner         if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
589bf42cfd7SJustin Bogner             EndLoc == getEndOfFileOrMacro(EndLoc))
590bf42cfd7SJustin Bogner           MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
591bf42cfd7SJustin Bogner 
592a6e4358fSStephen Kelly         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
593fa8fa044SVedant Kumar         assert(SpellingRegion(SM, Region).isInSourceOrder());
594f36a5c4aSCraig Topper         SourceRegions.push_back(Region);
595747b0e29SVedant Kumar 
596747b0e29SVedant Kumar         if (ParentOfDeferredRegion) {
597747b0e29SVedant Kumar           ParentOfDeferredRegion = false;
598747b0e29SVedant Kumar 
599747b0e29SVedant Kumar           // If there's an existing deferred region, keep the old one, because
600747b0e29SVedant Kumar           // it means there are two consecutive returns (or a similar pattern).
601747b0e29SVedant Kumar           if (!DeferredRegion.hasValue() &&
602747b0e29SVedant Kumar               // File IDs aren't gathered within macro expansions, so it isn't
603747b0e29SVedant Kumar               // useful to try and create a deferred region inside of one.
604f9a0d44eSVedant Kumar               !EndLoc.isMacroID())
605747b0e29SVedant Kumar             DeferredRegion =
606747b0e29SVedant Kumar                 SourceMappingRegion(Counter::getZero(), EndLoc, None);
607747b0e29SVedant Kumar         }
608747b0e29SVedant Kumar       } else if (Region.isDeferred()) {
609747b0e29SVedant Kumar         assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
610747b0e29SVedant Kumar         ParentOfDeferredRegion = true;
611bf42cfd7SJustin Bogner       }
612bf42cfd7SJustin Bogner       RegionStack.pop_back();
6138046d22aSVedant Kumar 
6148046d22aSVedant Kumar       // If the zero region pushed after the last terminated region no longer
6158046d22aSVedant Kumar       // exists, clear its cached information.
6168046d22aSVedant Kumar       if (LastTerminatedRegion &&
6178046d22aSVedant Kumar           RegionStack.size() < LastTerminatedRegion->second)
6188046d22aSVedant Kumar         LastTerminatedRegion = None;
619bf42cfd7SJustin Bogner     }
620747b0e29SVedant Kumar     assert(!ParentOfDeferredRegion && "Deferred region with no parent");
621ee02499aSAlex Lorenz   }
622ee02499aSAlex Lorenz 
6239fc8faf9SAdrian Prantl   /// Return the currently active region.
624bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
625bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
626bf42cfd7SJustin Bogner     return RegionStack.back();
627ee02499aSAlex Lorenz   }
628ee02499aSAlex Lorenz 
6299fc8faf9SAdrian Prantl   /// Propagate counts through the children of \c S.
630bf42cfd7SJustin Bogner   Counter propagateCounts(Counter TopCount, const Stmt *S) {
6317838696eSVedant Kumar     SourceLocation StartLoc = getStart(S);
6327838696eSVedant Kumar     SourceLocation EndLoc = getEnd(S);
6337838696eSVedant Kumar     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
634bf42cfd7SJustin Bogner     Visit(S);
635bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
636bf42cfd7SJustin Bogner     popRegions(Index);
63739f01975SVedant Kumar 
63839f01975SVedant Kumar     // The statement may be spanned by an expansion. Make sure we handle a file
63939f01975SVedant Kumar     // exit out of this expansion before moving to the next statement.
640*f2ceec48SStephen Kelly     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
6417838696eSVedant Kumar       MostRecentLocation = EndLoc;
64239f01975SVedant Kumar 
643bf42cfd7SJustin Bogner     return ExitCount;
644ee02499aSAlex Lorenz   }
645ee02499aSAlex Lorenz 
6469fc8faf9SAdrian Prantl   /// Check whether a region with bounds \c StartLoc and \c EndLoc
6470a7c9d11SIgor Kudrin   /// is already added to \c SourceRegions.
6480a7c9d11SIgor Kudrin   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
6490a7c9d11SIgor Kudrin     return SourceRegions.rend() !=
6500a7c9d11SIgor Kudrin            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
6510a7c9d11SIgor Kudrin                         [&](const SourceMappingRegion &Region) {
652a6e4358fSStephen Kelly                           return Region.getBeginLoc() == StartLoc &&
6530a7c9d11SIgor Kudrin                                  Region.getEndLoc() == EndLoc;
6540a7c9d11SIgor Kudrin                         });
6550a7c9d11SIgor Kudrin   }
6560a7c9d11SIgor Kudrin 
6579fc8faf9SAdrian Prantl   /// Adjust the most recently visited location to \c EndLoc.
658bf42cfd7SJustin Bogner   ///
659bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
660bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
661bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
6620a7c9d11SIgor Kudrin     // The code region for a whole macro is created in handleFileExit() when
6630a7c9d11SIgor Kudrin     // it detects exiting of the virtual file of that macro. If we visited
6640a7c9d11SIgor Kudrin     // statements in non-source order, we might already have such a region
6650a7c9d11SIgor Kudrin     // added, for example, if a body of a loop is divided among multiple
6660a7c9d11SIgor Kudrin     // macros. Avoid adding duplicate regions in such case.
66796ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
6680a7c9d11SIgor Kudrin         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
6690a7c9d11SIgor Kudrin         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
6700a7c9d11SIgor Kudrin                              MostRecentLocation))
671bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
672ee02499aSAlex Lorenz   }
673ee02499aSAlex Lorenz 
6749fc8faf9SAdrian Prantl   /// Adjust regions and state when \c NewLoc exits a file.
675bf42cfd7SJustin Bogner   ///
676bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
677bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
678bf42cfd7SJustin Bogner   /// for the exited file.
679bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
680e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
681e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
682bf42cfd7SJustin Bogner       return;
683bf42cfd7SJustin Bogner 
684bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
685bf42cfd7SJustin Bogner     // find the common ancestor.
686bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
687bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
688bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
689bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
690bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
691bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
692bf42cfd7SJustin Bogner         // to adjust our location to the new file.
693bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
694bf42cfd7SJustin Bogner         return;
695bf42cfd7SJustin Bogner       }
696bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
697ee02499aSAlex Lorenz     }
698ee02499aSAlex Lorenz 
699bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
700bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
70157d3f145SPete Cooper     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
70257d3f145SPete Cooper       if (!I.hasStartLoc())
703bf42cfd7SJustin Bogner         continue;
704a6e4358fSStephen Kelly       SourceLocation Loc = I.getBeginLoc();
705bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
70657d3f145SPete Cooper         ParentCounter = I.getCounter();
707bf42cfd7SJustin Bogner         break;
708ee02499aSAlex Lorenz       }
709bf42cfd7SJustin Bogner 
710bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
711bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
712bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
713bf42cfd7SJustin Bogner         // we've seen this region.
714bf42cfd7SJustin Bogner         if (StartLocs.insert(Loc).second)
71557d3f145SPete Cooper           SourceRegions.emplace_back(I.getCounter(), Loc,
716bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
717bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
718ee02499aSAlex Lorenz       }
71957d3f145SPete Cooper       I.setStartLoc(getPreciseTokenLocEnd(Loc));
720bf42cfd7SJustin Bogner     }
721bf42cfd7SJustin Bogner 
722bf42cfd7SJustin Bogner     if (ParentCounter) {
723bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
724bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
725bf42cfd7SJustin Bogner       // corresponding to the parent.
726bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
727bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
728bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
729fa8fa044SVedant Kumar         if (StartLocs.insert(FileStart).second) {
730bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
731bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
732fa8fa044SVedant Kumar           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
733fa8fa044SVedant Kumar         }
734bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
735bf42cfd7SJustin Bogner       }
736bf42cfd7SJustin Bogner     }
737bf42cfd7SJustin Bogner 
738bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
739bf42cfd7SJustin Bogner   }
740bf42cfd7SJustin Bogner 
7419fc8faf9SAdrian Prantl   /// Ensure that \c S is included in the current region.
742bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
743bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
744bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
745bf42cfd7SJustin Bogner 
746bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
747bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
748bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
749747b0e29SVedant Kumar 
750747b0e29SVedant Kumar     completeDeferred(Region.getCounter(), StartLoc);
751bf42cfd7SJustin Bogner   }
752bf42cfd7SJustin Bogner 
7539fc8faf9SAdrian Prantl   /// Mark \c S as a terminator, starting a zero region.
754bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
755bf42cfd7SJustin Bogner     extendRegion(S);
756bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
7578046d22aSVedant Kumar     SourceLocation EndLoc = getEnd(S);
758bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
7598046d22aSVedant Kumar       Region.setEndLoc(EndLoc);
760bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
7618046d22aSVedant Kumar     auto &ZeroRegion = getRegion();
7628046d22aSVedant Kumar     ZeroRegion.setDeferred(true);
7638046d22aSVedant Kumar     LastTerminatedRegion = {EndLoc, RegionStack.size()};
764bf42cfd7SJustin Bogner   }
765ee02499aSAlex Lorenz 
766fa8fa044SVedant Kumar   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
767fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
768fa8fa044SVedant Kumar                                            SourceLocation BeforeLoc) {
769fa8fa044SVedant Kumar     // If the start and end locations of the gap are both within the same macro
770fa8fa044SVedant Kumar     // file, the range may not be in source order.
771fa8fa044SVedant Kumar     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
772fa8fa044SVedant Kumar       return None;
773fa8fa044SVedant Kumar     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
774fa8fa044SVedant Kumar       return None;
775fa8fa044SVedant Kumar     return {{AfterLoc, BeforeLoc}};
776fa8fa044SVedant Kumar   }
777fa8fa044SVedant Kumar 
778fa8fa044SVedant Kumar   /// Find the source range after \p AfterStmt and before \p BeforeStmt.
779fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
780fa8fa044SVedant Kumar                                            const Stmt *BeforeStmt) {
781fa8fa044SVedant Kumar     return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
782fa8fa044SVedant Kumar                               getStart(BeforeStmt));
783fa8fa044SVedant Kumar   }
784fa8fa044SVedant Kumar 
7852e8c8759SVedant Kumar   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
7862e8c8759SVedant Kumar   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
7872e8c8759SVedant Kumar                             Counter Count) {
788fa8fa044SVedant Kumar     if (StartLoc == EndLoc)
7892e8c8759SVedant Kumar       return;
790fa8fa044SVedant Kumar     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
7912e8c8759SVedant Kumar     handleFileExit(StartLoc);
7922e8c8759SVedant Kumar     size_t Index = pushRegion(Count, StartLoc, EndLoc);
7932e8c8759SVedant Kumar     getRegion().setGap(true);
7942e8c8759SVedant Kumar     handleFileExit(EndLoc);
7952e8c8759SVedant Kumar     popRegions(Index);
7962e8c8759SVedant Kumar   }
7972e8c8759SVedant Kumar 
7989fc8faf9SAdrian Prantl   /// Keep counts of breaks and continues inside loops.
799ee02499aSAlex Lorenz   struct BreakContinue {
800ee02499aSAlex Lorenz     Counter BreakCount;
801ee02499aSAlex Lorenz     Counter ContinueCount;
802ee02499aSAlex Lorenz   };
803ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
804ee02499aSAlex Lorenz 
805ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
806ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
807e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
808ee02499aSAlex Lorenz       const LangOptions &LangOpts)
809747b0e29SVedant Kumar       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
810747b0e29SVedant Kumar         DeferredRegion(None) {}
811ee02499aSAlex Lorenz 
8129fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
813ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
814ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
815bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
816fc05ee34SIgor Kudrin     SourceRegionFilter Filter = emitExpansionRegions();
817747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
818fc05ee34SIgor Kudrin     emitSourceRegions(Filter);
819ee02499aSAlex Lorenz     gatherSkippedRegions();
820ee02499aSAlex Lorenz 
821efd319a2SVedant Kumar     if (MappingRegions.empty())
822efd319a2SVedant Kumar       return;
823efd319a2SVedant Kumar 
8244da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
8254da909b2SJustin Bogner                                  MappingRegions);
826ee02499aSAlex Lorenz     Writer.write(OS);
827ee02499aSAlex Lorenz   }
828ee02499aSAlex Lorenz 
829ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
830*f2ceec48SStephen Kelly     if (S->getBeginLoc().isValid())
831bf42cfd7SJustin Bogner       extendRegion(S);
832642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
833642f173aSBenjamin Kramer       if (Child)
834642f173aSBenjamin Kramer         this->Visit(Child);
835bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
836ee02499aSAlex Lorenz   }
837ee02499aSAlex Lorenz 
838ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
839747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
840747b0e29SVedant Kumar 
841bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
842efd319a2SVedant Kumar 
843efd319a2SVedant Kumar     // Do not propagate region counts into system headers.
844efd319a2SVedant Kumar     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
845efd319a2SVedant Kumar       return;
846efd319a2SVedant Kumar 
84761763b65SVedant Kumar     propagateCounts(getRegionCounter(Body), Body);
848747b0e29SVedant Kumar     assert(RegionStack.empty() && "Regions entered but never exited");
849747b0e29SVedant Kumar 
85061763b65SVedant Kumar     // Discard the last uncompleted deferred region in a decl, if one exists.
85161763b65SVedant Kumar     // This prevents lines at the end of a function containing only whitespace
85261763b65SVedant Kumar     // or closing braces from being marked as uncovered.
853ef8e05ffSVedant Kumar     DeferredRegion = None;
854341bf429SVedant Kumar   }
855ee02499aSAlex Lorenz 
856ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
857bf42cfd7SJustin Bogner     extendRegion(S);
858ee02499aSAlex Lorenz     if (S->getRetValue())
859ee02499aSAlex Lorenz       Visit(S->getRetValue());
860bf42cfd7SJustin Bogner     terminateRegion(S);
861ee02499aSAlex Lorenz   }
862ee02499aSAlex Lorenz 
863f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
864f959febfSJustin Bogner     extendRegion(E);
865f959febfSJustin Bogner     if (E->getSubExpr())
866f959febfSJustin Bogner       Visit(E->getSubExpr());
867f959febfSJustin Bogner     terminateRegion(E);
868f959febfSJustin Bogner   }
869f959febfSJustin Bogner 
870bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
871ee02499aSAlex Lorenz 
872ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
8738046d22aSVedant Kumar     Counter LabelCount = getRegionCounter(S);
874bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
8758046d22aSVedant Kumar     completeTopLevelDeferredRegion(LabelCount, Start);
876d781d97eSVedant Kumar     completeDeferred(LabelCount, Start);
877bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
878bf42cfd7SJustin Bogner     handleFileExit(Start);
8798046d22aSVedant Kumar     pushRegion(LabelCount, Start);
880ee02499aSAlex Lorenz     Visit(S->getSubStmt());
881ee02499aSAlex Lorenz   }
882ee02499aSAlex Lorenz 
883ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
884ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
885ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
886bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
8877f53fbfcSEli Friedman     // FIXME: a break in a switch should terminate regions for all preceding
8887f53fbfcSEli Friedman     // case statements, not just the most recent one.
889bf42cfd7SJustin Bogner     terminateRegion(S);
890ee02499aSAlex Lorenz   }
891ee02499aSAlex Lorenz 
892ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
893ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
894ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
895bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
896bf42cfd7SJustin Bogner     terminateRegion(S);
897ee02499aSAlex Lorenz   }
898ee02499aSAlex Lorenz 
899181dfe4cSEli Friedman   void VisitCallExpr(const CallExpr *E) {
900181dfe4cSEli Friedman     VisitStmt(E);
901181dfe4cSEli Friedman 
902181dfe4cSEli Friedman     // Terminate the region when we hit a noreturn function.
903181dfe4cSEli Friedman     // (This is helpful dealing with switch statements.)
904181dfe4cSEli Friedman     QualType CalleeType = E->getCallee()->getType();
905181dfe4cSEli Friedman     if (getFunctionExtInfo(*CalleeType).getNoReturn())
906181dfe4cSEli Friedman       terminateRegion(E);
907181dfe4cSEli Friedman   }
908181dfe4cSEli Friedman 
909ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
910bf42cfd7SJustin Bogner     extendRegion(S);
911ee02499aSAlex Lorenz 
912bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
913bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
914bf42cfd7SJustin Bogner 
915bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
916bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
917bf42cfd7SJustin Bogner     extendRegion(S->getBody());
918bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
919ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
920bf42cfd7SJustin Bogner 
921bf42cfd7SJustin Bogner     // Go back to handle the condition.
922bf42cfd7SJustin Bogner     Counter CondCount =
923bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
924bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
925bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
926bf42cfd7SJustin Bogner 
927fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
928fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
929fa8fa044SVedant Kumar     if (Gap)
930fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
931fa8fa044SVedant Kumar 
932bf42cfd7SJustin Bogner     Counter OutCount =
933bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
934bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
935bf42cfd7SJustin Bogner       pushRegion(OutCount);
936ee02499aSAlex Lorenz   }
937ee02499aSAlex Lorenz 
938ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
939bf42cfd7SJustin Bogner     extendRegion(S);
940ee02499aSAlex Lorenz 
941bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
942bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
943bf42cfd7SJustin Bogner 
944bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
945bf42cfd7SJustin Bogner     extendRegion(S->getBody());
946bf42cfd7SJustin Bogner     Counter BackedgeCount =
947bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
948ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
949bf42cfd7SJustin Bogner 
950bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
951bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
952bf42cfd7SJustin Bogner 
953bf42cfd7SJustin Bogner     Counter OutCount =
954bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
955bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
956bf42cfd7SJustin Bogner       pushRegion(OutCount);
957ee02499aSAlex Lorenz   }
958ee02499aSAlex Lorenz 
959ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
960bf42cfd7SJustin Bogner     extendRegion(S);
961ee02499aSAlex Lorenz     if (S->getInit())
962ee02499aSAlex Lorenz       Visit(S->getInit());
963ee02499aSAlex Lorenz 
964bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
965bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
966bf42cfd7SJustin Bogner 
9673e2ae49aSVedant Kumar     // The loop increment may contain a break or continue.
9683e2ae49aSVedant Kumar     if (S->getInc())
9693e2ae49aSVedant Kumar       BreakContinueStack.emplace_back();
9703e2ae49aSVedant Kumar 
971bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
9723e2ae49aSVedant Kumar     BreakContinueStack.emplace_back();
973bf42cfd7SJustin Bogner     extendRegion(S->getBody());
974bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
9753e2ae49aSVedant Kumar     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
976ee02499aSAlex Lorenz 
977ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
978ee02499aSAlex Lorenz     // the count for all the continue statements.
9793e2ae49aSVedant Kumar     BreakContinue IncrementBC;
9803e2ae49aSVedant Kumar     if (const Stmt *Inc = S->getInc()) {
9813e2ae49aSVedant Kumar       propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
9823e2ae49aSVedant Kumar       IncrementBC = BreakContinueStack.pop_back_val();
9833e2ae49aSVedant Kumar     }
984bf42cfd7SJustin Bogner 
985bf42cfd7SJustin Bogner     // Go back to handle the condition.
9863e2ae49aSVedant Kumar     Counter CondCount = addCounters(
9873e2ae49aSVedant Kumar         addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
9883e2ae49aSVedant Kumar         IncrementBC.ContinueCount);
989bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
990bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
991bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
992ee02499aSAlex Lorenz     }
993ee02499aSAlex Lorenz 
994fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
995fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
996fa8fa044SVedant Kumar                                   getStart(S->getBody()));
997fa8fa044SVedant Kumar     if (Gap)
998fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
999fa8fa044SVedant Kumar 
10003e2ae49aSVedant Kumar     Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
10013e2ae49aSVedant Kumar                                    subtractCounters(CondCount, BodyCount));
1002bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1003bf42cfd7SJustin Bogner       pushRegion(OutCount);
1004ee02499aSAlex Lorenz   }
1005ee02499aSAlex Lorenz 
1006ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1007bf42cfd7SJustin Bogner     extendRegion(S);
1008bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
1009ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
1010bf42cfd7SJustin Bogner 
1011bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1012bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1013bf42cfd7SJustin Bogner 
1014ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1015bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1016bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1017ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1018bf42cfd7SJustin Bogner 
1019fa8fa044SVedant Kumar     // The body count applies to the area immediately after the range.
1020fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1021fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1022fa8fa044SVedant Kumar     if (Gap)
1023fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1024fa8fa044SVedant Kumar 
10251587432dSJustin Bogner     Counter LoopCount =
10261587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
10271587432dSJustin Bogner     Counter OutCount =
10281587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1029bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1030bf42cfd7SJustin Bogner       pushRegion(OutCount);
1031ee02499aSAlex Lorenz   }
1032ee02499aSAlex Lorenz 
1033ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1034bf42cfd7SJustin Bogner     extendRegion(S);
1035ee02499aSAlex Lorenz     Visit(S->getElement());
1036bf42cfd7SJustin Bogner 
1037bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1038bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1039bf42cfd7SJustin Bogner 
1040ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1041bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1042bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1043ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1044bf42cfd7SJustin Bogner 
1045fa8fa044SVedant Kumar     // The body count applies to the area immediately after the collection.
1046fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1047fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1048fa8fa044SVedant Kumar     if (Gap)
1049fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1050fa8fa044SVedant Kumar 
10511587432dSJustin Bogner     Counter LoopCount =
10521587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
10531587432dSJustin Bogner     Counter OutCount =
10541587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1055bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1056bf42cfd7SJustin Bogner       pushRegion(OutCount);
1057ee02499aSAlex Lorenz   }
1058ee02499aSAlex Lorenz 
1059ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
1060bf42cfd7SJustin Bogner     extendRegion(S);
1061f2a6ec55SVedant Kumar     if (S->getInit())
1062f2a6ec55SVedant Kumar       Visit(S->getInit());
1063ee02499aSAlex Lorenz     Visit(S->getCond());
1064bf42cfd7SJustin Bogner 
1065ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1066bf42cfd7SJustin Bogner 
1067bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
1068bf42cfd7SJustin Bogner     extendRegion(Body);
1069bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1070bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
10717f53fbfcSEli Friedman         // Make a region for the body of the switch.  If the body starts with
10727f53fbfcSEli Friedman         // a case, that case will reuse this region; otherwise, this covers
10737f53fbfcSEli Friedman         // the unreachable code at the beginning of the switch body.
1074bf42cfd7SJustin Bogner         size_t Index =
10757f53fbfcSEli Friedman             pushRegion(Counter::getZero(), getStart(CS->body_front()));
1076b5841332SRichard Trieu         for (const auto *Child : CS->children())
1077bf42cfd7SJustin Bogner           Visit(Child);
10787f53fbfcSEli Friedman 
10797f53fbfcSEli Friedman         // Set the end for the body of the switch, if it isn't already set.
10807f53fbfcSEli Friedman         for (size_t i = RegionStack.size(); i != Index; --i) {
10817f53fbfcSEli Friedman           if (!RegionStack[i - 1].hasEndLoc())
10827f53fbfcSEli Friedman             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
10837f53fbfcSEli Friedman         }
10847f53fbfcSEli Friedman 
1085bf42cfd7SJustin Bogner         popRegions(Index);
1086ee02499aSAlex Lorenz       }
108787ea3b05SVedant Kumar     } else
1088bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
1089ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1090bf42cfd7SJustin Bogner 
1091ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
1092ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
1093ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1094bf42cfd7SJustin Bogner 
1095bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
10963836482aSVedant Kumar     SourceLocation ExitLoc = getEnd(S);
109708780529SAlex Lorenz     pushRegion(ExitCount);
109808780529SAlex Lorenz 
109908780529SAlex Lorenz     // Ensure that handleFileExit recognizes when the end location is located
110008780529SAlex Lorenz     // in a different file.
110108780529SAlex Lorenz     MostRecentLocation = getStart(S);
11023836482aSVedant Kumar     handleFileExit(ExitLoc);
1103ee02499aSAlex Lorenz   }
1104ee02499aSAlex Lorenz 
1105bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
1106bf42cfd7SJustin Bogner     extendRegion(S);
1107ee02499aSAlex Lorenz 
1108bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
1109bf42cfd7SJustin Bogner 
1110bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1111bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
1112bf42cfd7SJustin Bogner     // the first case in a switch.
1113a6e4358fSStephen Kelly     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1114bf42cfd7SJustin Bogner       Parent.setCounter(Count);
1115bf42cfd7SJustin Bogner     else
1116bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
1117bf42cfd7SJustin Bogner 
1118376c06c2SSanjay Patel     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1119bf42cfd7SJustin Bogner       Visit(CS->getLHS());
1120bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
1121bf42cfd7SJustin Bogner         Visit(RHS);
1122bf42cfd7SJustin Bogner     }
1123ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1124ee02499aSAlex Lorenz   }
1125ee02499aSAlex Lorenz 
1126ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
1127bf42cfd7SJustin Bogner     extendRegion(S);
11289d2a16b9SVedant Kumar     if (S->getInit())
11299d2a16b9SVedant Kumar       Visit(S->getInit());
11309d2a16b9SVedant Kumar 
1131055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
1132055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
1133055ebc34SJustin Bogner     extendRegion(S->getCond());
1134ee02499aSAlex Lorenz 
1135bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1136bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
1137ee02499aSAlex Lorenz 
113891f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
113991f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
114091f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
114191f2e3c9SJustin Bogner 
11422e8c8759SVedant Kumar     // The 'then' count applies to the area immediately after the condition.
1143fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1144fa8fa044SVedant Kumar     if (Gap)
1145fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
11462e8c8759SVedant Kumar 
1147bf42cfd7SJustin Bogner     extendRegion(S->getThen());
1148bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1149bf42cfd7SJustin Bogner 
1150bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1151bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
11522e8c8759SVedant Kumar       // The 'else' count applies to the area immediately after the 'then'.
1153fa8fa044SVedant Kumar       Gap = findGapAreaBetween(S->getThen(), Else);
1154fa8fa044SVedant Kumar       if (Gap)
1155fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
11562e8c8759SVedant Kumar       extendRegion(Else);
1157bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1158bf42cfd7SJustin Bogner     } else
1159bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
1160bf42cfd7SJustin Bogner 
1161bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1162bf42cfd7SJustin Bogner       pushRegion(OutCount);
1163ee02499aSAlex Lorenz   }
1164ee02499aSAlex Lorenz 
1165ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
1166bf42cfd7SJustin Bogner     extendRegion(S);
1167049908b2SVedant Kumar     // Handle macros that generate the "try" but not the rest.
1168049908b2SVedant Kumar     extendRegion(S->getTryBlock());
1169049908b2SVedant Kumar 
1170049908b2SVedant Kumar     Counter ParentCount = getRegion().getCounter();
1171049908b2SVedant Kumar     propagateCounts(ParentCount, S->getTryBlock());
1172049908b2SVedant Kumar 
1173ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1174ee02499aSAlex Lorenz       Visit(S->getHandler(I));
1175bf42cfd7SJustin Bogner 
1176bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
1177bf42cfd7SJustin Bogner     pushRegion(ExitCount);
1178ee02499aSAlex Lorenz   }
1179ee02499aSAlex Lorenz 
1180ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1181bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1182ee02499aSAlex Lorenz   }
1183ee02499aSAlex Lorenz 
1184ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1185bf42cfd7SJustin Bogner     extendRegion(E);
1186ee02499aSAlex Lorenz 
1187bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1188bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
1189ee02499aSAlex Lorenz 
1190e3654ce7SJustin Bogner     Visit(E->getCond());
1191e3654ce7SJustin Bogner 
1192e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
11932e8c8759SVedant Kumar       // The 'then' count applies to the area immediately after the condition.
1194fa8fa044SVedant Kumar       auto Gap =
1195fa8fa044SVedant Kumar           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1196fa8fa044SVedant Kumar       if (Gap)
1197fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
11982e8c8759SVedant Kumar 
1199e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
1200bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
1201e3654ce7SJustin Bogner     }
12022e8c8759SVedant Kumar 
1203e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
1204bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
1205bf42cfd7SJustin Bogner                     E->getFalseExpr());
1206ee02499aSAlex Lorenz   }
1207ee02499aSAlex Lorenz 
1208ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
1209e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1210e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1211e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1212bf42cfd7SJustin Bogner 
1213bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1214bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
1215ee02499aSAlex Lorenz   }
1216ee02499aSAlex Lorenz 
1217ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
1218e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1219e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1220e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1221ee02499aSAlex Lorenz 
1222bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1223bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
122401a0d062SAlex Lorenz   }
1225c109102eSJustin Bogner 
1226c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
1227c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
1228c109102eSJustin Bogner     // propagate counts into them.
1229c109102eSJustin Bogner   }
1230ee02499aSAlex Lorenz };
1231ee02499aSAlex Lorenz 
12321f39fcf2SXinliang David Li std::string getCoverageSection(const CodeGenModule &CGM) {
12338a767a43SVedant Kumar   return llvm::getInstrProfSectionName(
12348a767a43SVedant Kumar       llvm::IPSK_covmap,
12358a767a43SVedant Kumar       CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1236ee02499aSAlex Lorenz }
1237ee02499aSAlex Lorenz 
123814f8fb68SVedant Kumar std::string normalizeFilename(StringRef Filename) {
123914f8fb68SVedant Kumar   llvm::SmallString<256> Path(Filename);
124014f8fb68SVedant Kumar   llvm::sys::fs::make_absolute(Path);
1241d04929d8SVedant Kumar   llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
124214f8fb68SVedant Kumar   return Path.str().str();
124314f8fb68SVedant Kumar }
124414f8fb68SVedant Kumar 
124514f8fb68SVedant Kumar } // end anonymous namespace
124614f8fb68SVedant Kumar 
1247a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1248a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
1249a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
1250a432d176SJustin Bogner   OS << FunctionName << ":\n";
1251a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
1252a432d176SJustin Bogner   for (const auto &R : Regions) {
1253f2cf38e0SAlex Lorenz     OS.indent(2);
1254f2cf38e0SAlex Lorenz     switch (R.Kind) {
1255f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
1256f2cf38e0SAlex Lorenz       break;
1257f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
1258f2cf38e0SAlex Lorenz       OS << "Expansion,";
1259f2cf38e0SAlex Lorenz       break;
1260f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
1261f2cf38e0SAlex Lorenz       OS << "Skipped,";
1262f2cf38e0SAlex Lorenz       break;
1263a1c4deb7SVedant Kumar     case CounterMappingRegion::GapRegion:
1264a1c4deb7SVedant Kumar       OS << "Gap,";
1265a1c4deb7SVedant Kumar       break;
1266f2cf38e0SAlex Lorenz     }
1267f2cf38e0SAlex Lorenz 
12684da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
12694da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1270f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
1271f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
12724da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
12734da909b2SJustin Bogner     OS << "\n";
1274f2cf38e0SAlex Lorenz   }
1275f2cf38e0SAlex Lorenz }
1276f2cf38e0SAlex Lorenz 
1277ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord(
12782129ae53SXinliang David Li     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1279848da137SXinliang David Li     const std::string &CoverageMapping, bool IsUsed) {
1280ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1281ee02499aSAlex Lorenz   if (!FunctionRecordTy) {
1282a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1283a026a437SXinliang David Li     llvm::Type *FunctionRecordTypes[] = {
1284a026a437SXinliang David Li       #include "llvm/ProfileData/InstrProfData.inc"
1285a026a437SXinliang David Li     };
1286ee02499aSAlex Lorenz     FunctionRecordTy =
12874dc5adc7SJustin Bogner         llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
12884dc5adc7SJustin Bogner                               /*isPacked=*/true);
1289ee02499aSAlex Lorenz   }
1290ee02499aSAlex Lorenz 
1291a026a437SXinliang David Li   #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1292ee02499aSAlex Lorenz   llvm::Constant *FunctionRecordVals[] = {
1293a026a437SXinliang David Li       #include "llvm/ProfileData/InstrProfData.inc"
1294a026a437SXinliang David Li   };
1295ee02499aSAlex Lorenz   FunctionRecords.push_back(llvm::ConstantStruct::get(
1296ee02499aSAlex Lorenz       FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
1297848da137SXinliang David Li   if (!IsUsed)
12982129ae53SXinliang David Li     FunctionNames.push_back(
12992129ae53SXinliang David Li         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1300ca3326c0SVedant Kumar   CoverageMappings.push_back(CoverageMapping);
1301f2cf38e0SAlex Lorenz 
1302f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1303f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1304f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1305f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1306f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1307f2cf38e0SAlex Lorenz     // expressions.
1308f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1309f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1310f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
1311b31ee819SJordan Rose     llvm::SmallVector<std::string, 16> FilenameStrs;
1312f2cf38e0SAlex Lorenz     llvm::SmallVector<StringRef, 16> FilenameRefs;
1313b31ee819SJordan Rose     FilenameStrs.resize(FileEntries.size());
1314f2cf38e0SAlex Lorenz     FilenameRefs.resize(FileEntries.size());
1315b31ee819SJordan Rose     for (const auto &Entry : FileEntries) {
1316b31ee819SJordan Rose       auto I = Entry.second;
1317b31ee819SJordan Rose       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1318b31ee819SJordan Rose       FilenameRefs[I] = FilenameStrs[I];
1319b31ee819SJordan Rose     }
1320a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1321a432d176SJustin Bogner                                     Expressions, Regions);
1322a432d176SJustin Bogner     if (Reader.read())
1323f2cf38e0SAlex Lorenz       return;
1324a026a437SXinliang David Li     dump(llvm::outs(), NameValue, Expressions, Regions);
1325f2cf38e0SAlex Lorenz   }
1326ee02499aSAlex Lorenz }
1327ee02499aSAlex Lorenz 
1328ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1329ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1330ee02499aSAlex Lorenz     return;
1331ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1332ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1333ee02499aSAlex Lorenz 
1334ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1335ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
13369e324dd1SVedant Kumar   llvm::SmallVector<StringRef, 16> FilenameRefs;
1337ee02499aSAlex Lorenz   FilenameStrs.resize(FileEntries.size());
13389e324dd1SVedant Kumar   FilenameRefs.resize(FileEntries.size());
1339ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1340ee02499aSAlex Lorenz     auto I = Entry.second;
134114f8fb68SVedant Kumar     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
13429e324dd1SVedant Kumar     FilenameRefs[I] = FilenameStrs[I];
1343ee02499aSAlex Lorenz   }
1344ee02499aSAlex Lorenz 
13459e324dd1SVedant Kumar   std::string FilenamesAndCoverageMappings;
13469e324dd1SVedant Kumar   llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
13479e324dd1SVedant Kumar   CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
13489e324dd1SVedant Kumar   std::string RawCoverageMappings =
13499e324dd1SVedant Kumar       llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
13509e324dd1SVedant Kumar   OS << RawCoverageMappings;
13519e324dd1SVedant Kumar   size_t CoverageMappingSize = RawCoverageMappings.size();
13529e324dd1SVedant Kumar   size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
13539e324dd1SVedant Kumar   // Append extra zeroes if necessary to ensure that the size of the filenames
13549e324dd1SVedant Kumar   // and coverage mappings is a multiple of 8.
13559e324dd1SVedant Kumar   if (size_t Rem = OS.str().size() % 8) {
13569e324dd1SVedant Kumar     CoverageMappingSize += 8 - Rem;
1357070777dbSPeter Collingbourne     OS.write_zeros(8 - Rem);
1358ee02499aSAlex Lorenz   }
1359ee02499aSAlex Lorenz   auto *FilenamesAndMappingsVal =
13609e324dd1SVedant Kumar       llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
1361ee02499aSAlex Lorenz 
1362ee02499aSAlex Lorenz   // Create the deferred function records array
1363ee02499aSAlex Lorenz   auto RecordsTy =
1364ee02499aSAlex Lorenz       llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1365ee02499aSAlex Lorenz   auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1366ee02499aSAlex Lorenz 
136720b188c0SXinliang David Li   llvm::Type *CovDataHeaderTypes[] = {
136820b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
136920b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
137020b188c0SXinliang David Li   };
137120b188c0SXinliang David Li   auto CovDataHeaderTy =
137220b188c0SXinliang David Li       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
137320b188c0SXinliang David Li   llvm::Constant *CovDataHeaderVals[] = {
137420b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
137520b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
137620b188c0SXinliang David Li   };
137720b188c0SXinliang David Li   auto CovDataHeaderVal = llvm::ConstantStruct::get(
137820b188c0SXinliang David Li       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
137920b188c0SXinliang David Li 
1380ee02499aSAlex Lorenz   // Create the coverage data record
138120b188c0SXinliang David Li   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
138220b188c0SXinliang David Li                                 FilenamesAndMappingsVal->getType()};
1383ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
138420b188c0SXinliang David Li   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
138520b188c0SXinliang David Li                                   FilenamesAndMappingsVal};
1386ee02499aSAlex Lorenz   auto CovDataVal =
1387ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
138820b188c0SXinliang David Li   auto CovData = new llvm::GlobalVariable(
138920b188c0SXinliang David Li       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
139020b188c0SXinliang David Li       CovDataVal, llvm::getCoverageMappingVarName());
1391ee02499aSAlex Lorenz 
1392ee02499aSAlex Lorenz   CovData->setSection(getCoverageSection(CGM));
1393ee02499aSAlex Lorenz   CovData->setAlignment(8);
1394ee02499aSAlex Lorenz 
1395ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1396ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
13972129ae53SXinliang David Li   // Create the deferred function records array
13982129ae53SXinliang David Li   if (!FunctionNames.empty()) {
13992129ae53SXinliang David Li     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
14002129ae53SXinliang David Li                                            FunctionNames.size());
14012129ae53SXinliang David Li     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
14022129ae53SXinliang David Li     // This variable will *NOT* be emitted to the object file. It is used
14032129ae53SXinliang David Li     // to pass the list of names referenced to codegen.
14042129ae53SXinliang David Li     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
14052129ae53SXinliang David Li                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
14067077f0afSXinliang David Li                              llvm::getCoverageUnusedNamesVarName());
14072129ae53SXinliang David Li   }
1408ee02499aSAlex Lorenz }
1409ee02499aSAlex Lorenz 
1410ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1411ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1412ee02499aSAlex Lorenz   if (It != FileEntries.end())
1413ee02499aSAlex Lorenz     return It->second;
1414ee02499aSAlex Lorenz   unsigned FileID = FileEntries.size();
1415ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1416ee02499aSAlex Lorenz   return FileID;
1417ee02499aSAlex Lorenz }
1418ee02499aSAlex Lorenz 
1419ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1420ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1421ee02499aSAlex Lorenz   assert(CounterMap);
1422e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1423ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1424ee02499aSAlex Lorenz   Walker.write(OS);
1425ee02499aSAlex Lorenz }
1426ee02499aSAlex Lorenz 
1427ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1428ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1429ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1430ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1431ee02499aSAlex Lorenz   Walker.write(OS);
1432ee02499aSAlex Lorenz }
1433