blob: 0a7a4fe33ac2d2b45ff41085abb3678dfbef9429 [file] [log] [blame]
Alex Lorenzee024992014-08-04 18:41:51 +00001//===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alex Lorenzee024992014-08-04 18:41:51 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Instrumentation-based code coverage mapping generator
10//
11//===----------------------------------------------------------------------===//
12
13#include "CoverageMappingGen.h"
14#include "CodeGenFunction.h"
15#include "clang/AST/StmtVisitor.h"
16#include "clang/Lex/Lexer.h"
Vedant Kumarbc6b80a2016-01-28 17:52:18 +000017#include "llvm/ADT/SmallSet.h"
Vedant Kumarca3326c2016-01-21 19:25:35 +000018#include "llvm/ADT/StringExtras.h"
Justin Bognerbf42cfd2015-02-18 21:24:51 +000019#include "llvm/ADT/Optional.h"
Easwaran Ramanb014ee42016-04-29 18:53:16 +000020#include "llvm/ProfileData/Coverage/CoverageMapping.h"
21#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
22#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000023#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000024#include "llvm/Support/FileSystem.h"
Vedant Kumar14f8fb62016-07-18 21:01:27 +000025#include "llvm/Support/Path.h"
Alex Lorenzee024992014-08-04 18:41:51 +000026
27using namespace clang;
28using namespace CodeGen;
29using namespace llvm::coverage;
30
Vedant Kumar3919a502017-09-11 20:47:42 +000031void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
Alex Lorenzee024992014-08-04 18:41:51 +000032 SkippedRanges.push_back(Range);
33}
34
35namespace {
36
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037/// A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000038class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000039 Counter Count;
40
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000041 /// The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000042 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000043
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044 /// The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000045 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000046
Vedant Kumar747b0e22017-09-08 18:44:56 +000047 /// Whether this region should be emitted after its parent is emitted.
48 bool DeferRegion;
49
Vedant Kumara1c4deb2017-09-18 23:37:30 +000050 /// Whether this region is a gap region. The count from a gap region is set
51 /// as the line execution count if there are no other regions on the line.
52 bool GapRegion;
53
Justin Bogner09c71792014-10-01 03:33:49 +000054public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000055 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Vedant Kumara1c4deb2017-09-18 23:37:30 +000056 Optional<SourceLocation> LocEnd, bool DeferRegion = false,
57 bool GapRegion = false)
Vedant Kumar747b0e22017-09-08 18:44:56 +000058 : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
Vedant Kumara1c4deb2017-09-18 23:37:30 +000059 DeferRegion(DeferRegion), GapRegion(GapRegion) {}
Alex Lorenzee024992014-08-04 18:41:51 +000060
Justin Bogner09c71792014-10-01 03:33:49 +000061 const Counter &getCounter() const { return Count; }
62
Justin Bognerbf42cfd2015-02-18 21:24:51 +000063 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000064
Justin Bognerbf42cfd2015-02-18 21:24:51 +000065 bool hasStartLoc() const { return LocStart.hasValue(); }
66
67 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
68
Stephen Kelly3cffc4c2018-08-09 20:05:18 +000069 SourceLocation getBeginLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000070 assert(LocStart && "Region has no start location");
71 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000072 }
73
Justin Bognerbf42cfd2015-02-18 21:24:51 +000074 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000075
Vedant Kumara14a1f92018-01-17 18:53:51 +000076 void setEndLoc(SourceLocation Loc) {
77 assert(Loc.isValid() && "Setting an invalid end location");
78 LocEnd = Loc;
79 }
Alex Lorenzee024992014-08-04 18:41:51 +000080
Craig Topper462c77b2015-09-26 05:10:14 +000081 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000082 assert(LocEnd && "Region has no end location");
83 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000084 }
Vedant Kumar747b0e22017-09-08 18:44:56 +000085
86 bool isDeferred() const { return DeferRegion; }
87
88 void setDeferred(bool Deferred) { DeferRegion = Deferred; }
Vedant Kumara1c4deb2017-09-18 23:37:30 +000089
90 bool isGap() const { return GapRegion; }
91
92 void setGap(bool Gap) { GapRegion = Gap; }
Alex Lorenzee024992014-08-04 18:41:51 +000093};
94
Vedant Kumard7369642017-07-27 02:20:25 +000095/// Spelling locations for the start and end of a source region.
96struct SpellingRegion {
97 /// The line where the region starts.
98 unsigned LineStart;
99
100 /// The column where the region starts.
101 unsigned ColumnStart;
102
103 /// The line where the region ends.
104 unsigned LineEnd;
105
106 /// The column where the region ends.
107 unsigned ColumnEnd;
108
109 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
110 SourceLocation LocEnd) {
111 LineStart = SM.getSpellingLineNumber(LocStart);
112 ColumnStart = SM.getSpellingColumnNumber(LocStart);
113 LineEnd = SM.getSpellingLineNumber(LocEnd);
114 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
115 }
116
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000117 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
Stephen Kellya6e43582018-08-09 21:05:56 +0000118 : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000119
Vedant Kumard7369642017-07-27 02:20:25 +0000120 /// Check if the start and end locations appear in source order, i.e
121 /// top->bottom, left->right.
122 bool isInSourceOrder() const {
123 return (LineStart < LineEnd) ||
124 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
125 }
126};
127
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000128/// Provides the common functionality for the different
Alex Lorenzee024992014-08-04 18:41:51 +0000129/// coverage mapping region builders.
130class CoverageMappingBuilder {
131public:
132 CoverageMappingModuleGen &CVM;
133 SourceManager &SM;
134 const LangOptions &LangOpts;
135
136private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000137 /// Map of clang's FileIDs to IDs used for coverage mapping.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000138 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
139 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000140
141public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000142 /// The coverage mapping regions for this function
Alex Lorenzee024992014-08-04 18:41:51 +0000143 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000144 /// The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000145 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000146
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000147 /// A set of regions which can be used as a filter.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000148 ///
149 /// It is produced by emitExpansionRegions() and is used in
150 /// emitSourceRegions() to suppress producing code regions if
151 /// the same area is covered by expansion regions.
152 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
153 SourceRegionFilter;
154
Alex Lorenzee024992014-08-04 18:41:51 +0000155 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
156 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000157 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000158
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000159 /// Return the precise end location for the given token.
Alex Lorenzee024992014-08-04 18:41:51 +0000160 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000161 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
162 // macro locations, which we just treat as expanded files.
163 unsigned TokLen =
164 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
165 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000166 }
167
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000168 /// Return the start location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000169 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
170 if (Loc.isMacroID())
171 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
172 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000173 }
174
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000175 /// Return the end location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000176 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
177 if (Loc.isMacroID())
178 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000179 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000180 return SM.getLocForEndOfFile(SM.getFileID(Loc));
181 }
182
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000183 /// Find out where the current file is included or macro is expanded.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000184 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
Richard Smithb5f81712018-04-30 05:25:48 +0000185 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000186 : SM.getIncludeLoc(SM.getFileID(Loc));
187 }
188
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000189 /// Return true if \c Loc is a location in a built-in macro.
Justin Bogner682bfbf2015-05-14 22:14:10 +0000190 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000191 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000192 }
193
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000194 /// Check whether \c Loc is included or expanded from \c Parent.
Igor Kudrind9e1a612016-06-07 10:07:51 +0000195 bool isNestedIn(SourceLocation Loc, FileID Parent) {
196 do {
197 Loc = getIncludeOrExpansionLoc(Loc);
198 if (Loc.isInvalid())
199 return false;
200 } while (!SM.isInFileID(Loc, Parent));
201 return true;
202 }
203
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000204 /// Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000205 SourceLocation getStart(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000206 SourceLocation Loc = S->getBeginLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000207 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000208 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000209 return Loc;
210 }
211
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000212 /// Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000213 SourceLocation getEnd(const Stmt *S) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000214 SourceLocation Loc = S->getEndLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000215 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000216 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerf14b2072015-03-25 04:13:49 +0000217 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000218 }
219
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000220 /// Find the set of files we have regions for and assign IDs
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000221 ///
222 /// Fills \c Mapping with the virtual file mapping needed to write out
223 /// coverage and collects the necessary file information to emit source and
224 /// expansion regions.
225 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
226 FileIDMapping.clear();
227
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000228 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000229 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
230 for (const auto &Region : SourceRegions) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000231 SourceLocation Loc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000232 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000233 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000234 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000235
Vedant Kumar93205af2016-07-11 22:57:46 +0000236 // Do not map FileID's associated with system headers.
237 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
238 continue;
239
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000240 unsigned Depth = 0;
241 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000242 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000243 ++Depth;
244 FileLocs.push_back(std::make_pair(Loc, Depth));
245 }
Fangrui Song899d1392019-04-24 14:43:05 +0000246 llvm::stable_sort(FileLocs, llvm::less_second());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000247
248 for (const auto &FL : FileLocs) {
249 SourceLocation Loc = FL.first;
250 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
251 auto Entry = SM.getFileEntryForID(SpellingFile);
252 if (!Entry)
253 continue;
254
255 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
256 Mapping.push_back(CVM.getFileID(Entry));
257 }
258 }
259
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000260 /// Get the coverage mapping file ID for \c Loc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000261 ///
262 /// If such file id doesn't exist, return None.
263 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
264 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000265 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000266 return Mapping->second.first;
267 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000268 }
269
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000270 /// Gather all the regions that were skipped by the preprocessor
Alex Lorenzee024992014-08-04 18:41:51 +0000271 /// using the constructs like #if.
272 void gatherSkippedRegions() {
273 /// An array of the minimum lineStarts and the maximum lineEnds
274 /// for mapping regions from the appropriate source files.
275 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
276 FileLineRanges.resize(
277 FileIDMapping.size(),
278 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
279 for (const auto &R : MappingRegions) {
280 FileLineRanges[R.FileID].first =
281 std::min(FileLineRanges[R.FileID].first, R.LineStart);
282 FileLineRanges[R.FileID].second =
283 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
284 }
285
286 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
287 for (const auto &I : SkippedRanges) {
288 auto LocStart = I.getBegin();
289 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000290 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
291 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000292
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000293 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000294 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000295 continue;
Vedant Kumard7369642017-07-27 02:20:25 +0000296 SpellingRegion SR{SM, LocStart, LocEnd};
Justin Bognerfd34280b2015-02-03 23:59:48 +0000297 auto Region = CounterMappingRegion::makeSkipped(
Vedant Kumard7369642017-07-27 02:20:25 +0000298 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000299 // Make sure that we only collect the regions that are inside
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000300 // the source code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000301 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
302 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000303 MappingRegions.push_back(Region);
304 }
305 }
306
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000307 /// Generate the coverage counter mapping regions from collected
Alex Lorenzee024992014-08-04 18:41:51 +0000308 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000309 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000310 for (const auto &Region : SourceRegions) {
311 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000312
Stephen Kellya6e43582018-08-09 21:05:56 +0000313 SourceLocation LocStart = Region.getBeginLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000314 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000315
Vedant Kumar93205af2016-07-11 22:57:46 +0000316 // Ignore regions from system headers.
317 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
318 continue;
319
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000320 auto CovFileID = getCoverageFileID(LocStart);
321 // Ignore regions that don't have a file, such as builtin macros.
322 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000323 continue;
324
Justin Bognerf14b2072015-03-25 04:13:49 +0000325 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000326 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
327 "region spans multiple files");
328
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000329 // Don't add code regions for the area covered by expansion regions.
330 // This not only suppresses redundant regions, but sometimes prevents
331 // creating regions with wrong counters if, for example, a statement's
332 // body ends at the end of a nested macro.
333 if (Filter.count(std::make_pair(LocStart, LocEnd)))
334 continue;
335
Vedant Kumard7369642017-07-27 02:20:25 +0000336 // Find the spelling locations for the mapping region.
337 SpellingRegion SR{SM, LocStart, LocEnd};
338 assert(SR.isInSourceOrder() && "region start and end out of order");
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000339
340 if (Region.isGap()) {
341 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
342 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
343 SR.LineEnd, SR.ColumnEnd));
344 } else {
345 MappingRegions.push_back(CounterMappingRegion::makeRegion(
346 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
347 SR.LineEnd, SR.ColumnEnd));
348 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000349 }
350 }
351
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000352 /// Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000353 SourceRegionFilter emitExpansionRegions() {
354 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000355 for (const auto &FM : FileIDMapping) {
356 SourceLocation ExpandedLoc = FM.second.second;
357 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
358 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000359 continue;
360
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000361 auto ParentFileID = getCoverageFileID(ParentLoc);
362 if (!ParentFileID)
363 continue;
364 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
365 assert(ExpandedFileID && "expansion in uncovered file");
366
367 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
368 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
369 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000370 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000371
Vedant Kumard7369642017-07-27 02:20:25 +0000372 SpellingRegion SR{SM, ParentLoc, LocEnd};
373 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000374 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000375 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
376 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000377 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000378 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000379 }
380};
381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000382/// Creates unreachable coverage regions for the functions that
Alex Lorenzee024992014-08-04 18:41:51 +0000383/// are not emitted.
384struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
385 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
386 const LangOptions &LangOpts)
387 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
388
389 void VisitDecl(const Decl *D) {
390 if (!D->hasBody())
391 return;
392 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000393 SourceLocation Start = getStart(Body);
394 SourceLocation End = getEnd(Body);
395 if (!SM.isWrittenInSameFile(Start, End)) {
396 // Walk up to find the common ancestor.
397 // Correct the locations accordingly.
398 FileID StartFileID = SM.getFileID(Start);
399 FileID EndFileID = SM.getFileID(End);
400 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
401 Start = getIncludeOrExpansionLoc(Start);
402 assert(Start.isValid() &&
403 "Declaration start location not nested within a known region");
404 StartFileID = SM.getFileID(Start);
405 }
406 while (StartFileID != EndFileID) {
407 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
408 assert(End.isValid() &&
409 "Declaration end location not nested within a known region");
410 EndFileID = SM.getFileID(End);
411 }
412 }
413 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000414 }
415
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000416 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000417 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000418 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000419 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000420 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000421
Vedant Kumarefd319a2016-07-26 00:24:59 +0000422 if (MappingRegions.empty())
423 return;
424
Craig Topper5fc8fc22014-08-27 06:28:36 +0000425 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000426 Writer.write(OS);
427 }
428};
429
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000430/// A StmtVisitor that creates coverage mapping regions which map
Alex Lorenzee024992014-08-04 18:41:51 +0000431/// from the source code locations to the PGO counters.
432struct CounterCoverageMappingBuilder
433 : public CoverageMappingBuilder,
434 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000435 /// The map of statements to count values.
Alex Lorenzee024992014-08-04 18:41:51 +0000436 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
437
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000438 /// A stack of currently live regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000439 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000440
Vedant Kumar747b0e22017-09-08 18:44:56 +0000441 /// The currently deferred region: its end location and count can be set once
442 /// its parent has been popped from the region stack.
443 Optional<SourceMappingRegion> DeferredRegion;
444
Alex Lorenzee024992014-08-04 18:41:51 +0000445 CounterExpressionBuilder Builder;
446
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// A location in the most recently visited file or macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000448 ///
449 /// This is used to adjust the active source regions appropriately when
450 /// expressions cross file or macro boundaries.
451 SourceLocation MostRecentLocation;
452
Vedant Kumar8046d222017-11-09 02:33:39 +0000453 /// Location of the last terminated region.
454 Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
455
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000456 /// Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000457 Counter subtractCounters(Counter LHS, Counter RHS) {
458 return Builder.subtract(LHS, RHS);
459 }
460
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000461 /// Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000462 Counter addCounters(Counter LHS, Counter RHS) {
463 return Builder.add(LHS, RHS);
464 }
465
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000466 Counter addCounters(Counter C1, Counter C2, Counter C3) {
467 return addCounters(addCounters(C1, C2), C3);
468 }
469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000470 /// Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000471 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000472 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000473 Counter getRegionCounter(const Stmt *S) {
474 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000475 }
476
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000477 /// Push a region onto the stack.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000478 ///
479 /// Returns the index on the stack where the region was pushed. This can be
480 /// used with popRegions to exit a "scope", ending the region that was pushed.
481 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
482 Optional<SourceLocation> EndLoc = None) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000483 if (StartLoc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000484 MostRecentLocation = *StartLoc;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000485 completeDeferred(Count, MostRecentLocation);
486 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000487 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000488
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000489 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000490 }
491
Vedant Kumar747b0e22017-09-08 18:44:56 +0000492 /// Complete any pending deferred region by setting its end location and
493 /// count, and then pushing it onto the region stack.
494 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
495 size_t Index = RegionStack.size();
496 if (!DeferredRegion)
497 return Index;
498
499 // Consume the pending region.
500 SourceMappingRegion DR = DeferredRegion.getValue();
501 DeferredRegion = None;
502
503 // If the region ends in an expansion, find the expansion site.
Stephen Kellya6e43582018-08-09 21:05:56 +0000504 FileID StartFile = SM.getFileID(DR.getBeginLoc());
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000505 if (SM.getFileID(DeferredEndLoc) != StartFile) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000506 if (isNestedIn(DeferredEndLoc, StartFile)) {
507 do {
508 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
509 } while (StartFile != SM.getFileID(DeferredEndLoc));
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000510 } else {
511 return Index;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000512 }
513 }
514
515 // The parent of this deferred region ends where the containing decl ends,
516 // so the region isn't useful.
Stephen Kellya6e43582018-08-09 21:05:56 +0000517 if (DR.getBeginLoc() == DeferredEndLoc)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000518 return Index;
519
520 // If we're visiting statements in non-source order (e.g switch cases or
521 // a loop condition) we can't construct a sensible deferred region.
Stephen Kellya6e43582018-08-09 21:05:56 +0000522 if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000523 return Index;
524
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000525 DR.setGap(true);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000526 DR.setCounter(Count);
527 DR.setEndLoc(DeferredEndLoc);
528 handleFileExit(DeferredEndLoc);
529 RegionStack.push_back(DR);
530 return Index;
531 }
532
Vedant Kumar8046d222017-11-09 02:33:39 +0000533 /// Complete a deferred region created after a terminated region at the
534 /// top-level.
535 void completeTopLevelDeferredRegion(Counter Count,
536 SourceLocation DeferredEndLoc) {
537 if (DeferredRegion || !LastTerminatedRegion)
538 return;
539
540 if (LastTerminatedRegion->second != RegionStack.size())
541 return;
542
543 SourceLocation Start = LastTerminatedRegion->first;
544 if (SM.getFileID(Start) != SM.getMainFileID())
545 return;
546
547 SourceMappingRegion DR = RegionStack.back();
548 DR.setStartLoc(Start);
549 DR.setDeferred(false);
550 DeferredRegion = DR;
551 completeDeferred(Count, DeferredEndLoc);
552 }
553
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000554 size_t locationDepth(SourceLocation Loc) {
555 size_t Depth = 0;
556 while (Loc.isValid()) {
557 Loc = getIncludeOrExpansionLoc(Loc);
558 Depth++;
559 }
560 return Depth;
561 }
562
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000563 /// Pop regions from the stack into the function's list of regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000564 ///
565 /// Adds all regions from \c ParentIndex to the top of the stack to the
566 /// function's \c SourceRegions.
567 void popRegions(size_t ParentIndex) {
568 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
Vedant Kumar747b0e22017-09-08 18:44:56 +0000569 bool ParentOfDeferredRegion = false;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000570 while (RegionStack.size() > ParentIndex) {
571 SourceMappingRegion &Region = RegionStack.back();
572 if (Region.hasStartLoc()) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000573 SourceLocation StartLoc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000574 SourceLocation EndLoc = Region.hasEndLoc()
575 ? Region.getEndLoc()
576 : RegionStack[ParentIndex].getEndLoc();
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000577 size_t StartDepth = locationDepth(StartLoc);
578 size_t EndDepth = locationDepth(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000579 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000580 bool UnnestStart = StartDepth >= EndDepth;
581 bool UnnestEnd = EndDepth >= StartDepth;
582 if (UnnestEnd) {
583 // The region ends in a nested file or macro expansion. Create a
584 // separate region for each expansion.
585 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
586 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000587
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000588 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
589 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000590
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000591 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
592 if (EndLoc.isInvalid())
593 llvm::report_fatal_error("File exit not handled before popRegions");
594 EndDepth--;
595 }
596 if (UnnestStart) {
597 // The region begins in a nested file or macro expansion. Create a
598 // separate region for each expansion.
599 SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
600 assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
601
602 if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
603 SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
604
605 StartLoc = getIncludeOrExpansionLoc(StartLoc);
606 if (StartLoc.isInvalid())
607 llvm::report_fatal_error("File exit not handled before popRegions");
608 StartDepth--;
609 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000610 }
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000611 Region.setStartLoc(StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000612 Region.setEndLoc(EndLoc);
613
614 MostRecentLocation = EndLoc;
615 // If this region happens to span an entire expansion, we need to make
616 // sure we don't overlap the parent region with it.
617 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
618 EndLoc == getEndOfFileOrMacro(EndLoc))
619 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
620
Stephen Kellya6e43582018-08-09 21:05:56 +0000621 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000622 assert(SpellingRegion(SM, Region).isInSourceOrder());
Craig Topperf36a5c42015-09-26 05:10:16 +0000623 SourceRegions.push_back(Region);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000624
625 if (ParentOfDeferredRegion) {
626 ParentOfDeferredRegion = false;
627
628 // If there's an existing deferred region, keep the old one, because
629 // it means there are two consecutive returns (or a similar pattern).
630 if (!DeferredRegion.hasValue() &&
631 // File IDs aren't gathered within macro expansions, so it isn't
632 // useful to try and create a deferred region inside of one.
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000633 !EndLoc.isMacroID())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000634 DeferredRegion =
635 SourceMappingRegion(Counter::getZero(), EndLoc, None);
636 }
637 } else if (Region.isDeferred()) {
638 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
639 ParentOfDeferredRegion = true;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000640 }
641 RegionStack.pop_back();
Vedant Kumar8046d222017-11-09 02:33:39 +0000642
643 // If the zero region pushed after the last terminated region no longer
644 // exists, clear its cached information.
645 if (LastTerminatedRegion &&
646 RegionStack.size() < LastTerminatedRegion->second)
647 LastTerminatedRegion = None;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000648 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000649 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
Alex Lorenzee024992014-08-04 18:41:51 +0000650 }
651
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000652 /// Return the currently active region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000653 SourceMappingRegion &getRegion() {
654 assert(!RegionStack.empty() && "statement has no region");
655 return RegionStack.back();
656 }
Alex Lorenzee024992014-08-04 18:41:51 +0000657
Vedant Kumar7225a262018-11-28 20:48:07 +0000658 /// Propagate counts through the children of \p S if \p VisitChildren is true.
659 /// Otherwise, only emit a count for \p S itself.
660 Counter propagateCounts(Counter TopCount, const Stmt *S,
661 bool VisitChildren = true) {
Vedant Kumar78386962017-07-27 02:20:20 +0000662 SourceLocation StartLoc = getStart(S);
663 SourceLocation EndLoc = getEnd(S);
664 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Vedant Kumar7225a262018-11-28 20:48:07 +0000665 if (VisitChildren)
666 Visit(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000667 Counter ExitCount = getRegion().getCounter();
668 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000669
670 // The statement may be spanned by an expansion. Make sure we handle a file
671 // exit out of this expansion before moving to the next statement.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000672 if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
Vedant Kumar78386962017-07-27 02:20:20 +0000673 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000674
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000675 return ExitCount;
676 }
Alex Lorenzee024992014-08-04 18:41:51 +0000677
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000678 /// Check whether a region with bounds \c StartLoc and \c EndLoc
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000679 /// is already added to \c SourceRegions.
680 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
681 return SourceRegions.rend() !=
682 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
683 [&](const SourceMappingRegion &Region) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000684 return Region.getBeginLoc() == StartLoc &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000685 Region.getEndLoc() == EndLoc;
686 });
687 }
688
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000689 /// Adjust the most recently visited location to \c EndLoc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000690 ///
691 /// This should be used after visiting any statements in non-source order.
692 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
693 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000694 // The code region for a whole macro is created in handleFileExit() when
695 // it detects exiting of the virtual file of that macro. If we visited
696 // statements in non-source order, we might already have such a region
697 // added, for example, if a body of a loop is divided among multiple
698 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000699 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000700 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
701 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
702 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000703 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
704 }
Alex Lorenzee024992014-08-04 18:41:51 +0000705
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000706 /// Adjust regions and state when \c NewLoc exits a file.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000707 ///
708 /// If moving from our most recently tracked location to \c NewLoc exits any
709 /// files, this adjusts our current region stack and creates the file regions
710 /// for the exited file.
711 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000712 if (NewLoc.isInvalid() ||
713 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000714 return;
715
716 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
717 // find the common ancestor.
718 SourceLocation LCA = NewLoc;
719 FileID ParentFile = SM.getFileID(LCA);
720 while (!isNestedIn(MostRecentLocation, ParentFile)) {
721 LCA = getIncludeOrExpansionLoc(LCA);
722 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
723 // Since there isn't a common ancestor, no file was exited. We just need
724 // to adjust our location to the new file.
725 MostRecentLocation = NewLoc;
726 return;
727 }
728 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000729 }
730
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000731 llvm::SmallSet<SourceLocation, 8> StartLocs;
732 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000733 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
734 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000735 continue;
Stephen Kellya6e43582018-08-09 21:05:56 +0000736 SourceLocation Loc = I.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000737 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000738 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000739 break;
740 }
Alex Lorenzee024992014-08-04 18:41:51 +0000741
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000742 while (!SM.isInFileID(Loc, ParentFile)) {
743 // The most nested region for each start location is the one with the
744 // correct count. We avoid creating redundant regions by stopping once
745 // we've seen this region.
746 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000747 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000748 getEndOfFileOrMacro(Loc));
749 Loc = getIncludeOrExpansionLoc(Loc);
750 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000751 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000752 }
753
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000754 if (ParentCounter) {
755 // If the file is contained completely by another region and doesn't
756 // immediately start its own region, the whole file gets a region
757 // corresponding to the parent.
758 SourceLocation Loc = MostRecentLocation;
759 while (isNestedIn(Loc, ParentFile)) {
760 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000761 if (StartLocs.insert(FileStart).second) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000762 SourceRegions.emplace_back(*ParentCounter, FileStart,
763 getEndOfFileOrMacro(Loc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000764 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
765 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000766 Loc = getIncludeOrExpansionLoc(Loc);
767 }
Alex Lorenzee024992014-08-04 18:41:51 +0000768 }
769
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000770 MostRecentLocation = NewLoc;
771 }
Alex Lorenzee024992014-08-04 18:41:51 +0000772
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000773 /// Ensure that \c S is included in the current region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000774 void extendRegion(const Stmt *S) {
775 SourceMappingRegion &Region = getRegion();
776 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000777
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000778 handleFileExit(StartLoc);
779 if (!Region.hasStartLoc())
780 Region.setStartLoc(StartLoc);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000781
782 completeDeferred(Region.getCounter(), StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000783 }
784
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000785 /// Mark \c S as a terminator, starting a zero region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000786 void terminateRegion(const Stmt *S) {
787 extendRegion(S);
788 SourceMappingRegion &Region = getRegion();
Vedant Kumar8046d222017-11-09 02:33:39 +0000789 SourceLocation EndLoc = getEnd(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000790 if (!Region.hasEndLoc())
Vedant Kumar8046d222017-11-09 02:33:39 +0000791 Region.setEndLoc(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000792 pushRegion(Counter::getZero());
Vedant Kumar8046d222017-11-09 02:33:39 +0000793 auto &ZeroRegion = getRegion();
794 ZeroRegion.setDeferred(true);
795 LastTerminatedRegion = {EndLoc, RegionStack.size()};
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000796 }
Alex Lorenzee024992014-08-04 18:41:51 +0000797
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000798 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
799 Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
800 SourceLocation BeforeLoc) {
801 // If the start and end locations of the gap are both within the same macro
802 // file, the range may not be in source order.
803 if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
804 return None;
805 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
806 return None;
807 return {{AfterLoc, BeforeLoc}};
808 }
809
810 /// Find the source range after \p AfterStmt and before \p BeforeStmt.
811 Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
812 const Stmt *BeforeStmt) {
813 return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
814 getStart(BeforeStmt));
815 }
816
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000817 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
818 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
819 Counter Count) {
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000820 if (StartLoc == EndLoc)
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000821 return;
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000822 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000823 handleFileExit(StartLoc);
824 size_t Index = pushRegion(Count, StartLoc, EndLoc);
825 getRegion().setGap(true);
826 handleFileExit(EndLoc);
827 popRegions(Index);
828 }
829
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000830 /// Keep counts of breaks and continues inside loops.
Alex Lorenzee024992014-08-04 18:41:51 +0000831 struct BreakContinue {
832 Counter BreakCount;
833 Counter ContinueCount;
834 };
835 SmallVector<BreakContinue, 8> BreakContinueStack;
836
837 CounterCoverageMappingBuilder(
838 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000839 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000840 const LangOptions &LangOpts)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000841 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
842 DeferredRegion(None) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000844 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000845 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000846 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000847 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000848 SourceRegionFilter Filter = emitExpansionRegions();
Vedant Kumar747b0e22017-09-08 18:44:56 +0000849 assert(!DeferredRegion && "Deferred region never completed");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000850 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000851 gatherSkippedRegions();
852
Vedant Kumarefd319a2016-07-26 00:24:59 +0000853 if (MappingRegions.empty())
854 return;
855
Justin Bogner4da909b2015-02-03 21:35:49 +0000856 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
857 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000858 Writer.write(OS);
859 }
860
Alex Lorenzee024992014-08-04 18:41:51 +0000861 void VisitStmt(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000862 if (S->getBeginLoc().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000863 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000864 for (const Stmt *Child : S->children())
865 if (Child)
866 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000867 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000868 }
869
Alex Lorenzee024992014-08-04 18:41:51 +0000870 void VisitDecl(const Decl *D) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000871 assert(!DeferredRegion && "Deferred region never completed");
872
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000873 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000874
875 // Do not propagate region counts into system headers.
876 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
877 return;
878
Vedant Kumar7225a262018-11-28 20:48:07 +0000879 // Do not visit the artificial children nodes of defaulted methods. The
880 // lexer may not be able to report back precise token end locations for
881 // these children nodes (llvm.org/PR39822), and moreover users will not be
882 // able to see coverage for them.
883 bool Defaulted = false;
884 if (auto *Method = dyn_cast<CXXMethodDecl>(D))
885 Defaulted = Method->isDefaulted();
886
887 propagateCounts(getRegionCounter(Body), Body,
888 /*VisitChildren=*/!Defaulted);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000889 assert(RegionStack.empty() && "Regions entered but never exited");
890
Vedant Kumar61763b62018-05-30 23:35:44 +0000891 // Discard the last uncompleted deferred region in a decl, if one exists.
892 // This prevents lines at the end of a function containing only whitespace
893 // or closing braces from being marked as uncovered.
894 DeferredRegion = None;
Alex Lorenzee024992014-08-04 18:41:51 +0000895 }
896
897 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000898 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000899 if (S->getRetValue())
900 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000901 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000902 }
903
Justin Bognerf959feb2015-04-28 06:31:55 +0000904 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
905 extendRegion(E);
906 if (E->getSubExpr())
907 Visit(E->getSubExpr());
908 terminateRegion(E);
909 }
910
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000911 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000912
913 void VisitLabelStmt(const LabelStmt *S) {
Vedant Kumar8046d222017-11-09 02:33:39 +0000914 Counter LabelCount = getRegionCounter(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000915 SourceLocation Start = getStart(S);
Vedant Kumar8046d222017-11-09 02:33:39 +0000916 completeTopLevelDeferredRegion(LabelCount, Start);
Vedant Kumard781d972018-06-01 00:37:13 +0000917 completeDeferred(LabelCount, Start);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000918 // We can't extendRegion here or we risk overlapping with our new region.
919 handleFileExit(Start);
Vedant Kumar8046d222017-11-09 02:33:39 +0000920 pushRegion(LabelCount, Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000921 Visit(S->getSubStmt());
922 }
923
924 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000925 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
926 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000927 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000928 // FIXME: a break in a switch should terminate regions for all preceding
929 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000930 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000931 }
932
933 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000934 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
935 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000936 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
937 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000938 }
939
Eli Friedman181dfe42017-08-08 20:10:14 +0000940 void VisitCallExpr(const CallExpr *E) {
941 VisitStmt(E);
942
943 // Terminate the region when we hit a noreturn function.
944 // (This is helpful dealing with switch statements.)
945 QualType CalleeType = E->getCallee()->getType();
946 if (getFunctionExtInfo(*CalleeType).getNoReturn())
947 terminateRegion(E);
948 }
949
Alex Lorenzee024992014-08-04 18:41:51 +0000950 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000951 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000952
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000953 Counter ParentCount = getRegion().getCounter();
954 Counter BodyCount = getRegionCounter(S);
955
956 // Handle the body first so that we can get the backedge count.
957 BreakContinueStack.push_back(BreakContinue());
958 extendRegion(S->getBody());
959 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000960 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000961
962 // Go back to handle the condition.
963 Counter CondCount =
964 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
965 propagateCounts(CondCount, S->getCond());
966 adjustForOutOfOrderTraversal(getEnd(S));
967
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000968 // The body count applies to the area immediately after the increment.
969 auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
970 if (Gap)
971 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
972
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000973 Counter OutCount =
974 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
975 if (OutCount != ParentCount)
976 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000977 }
978
979 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000980 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000981
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000982 Counter ParentCount = getRegion().getCounter();
983 Counter BodyCount = getRegionCounter(S);
984
985 BreakContinueStack.push_back(BreakContinue());
986 extendRegion(S->getBody());
987 Counter BackedgeCount =
988 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000989 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000990
991 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
992 propagateCounts(CondCount, S->getCond());
993
994 Counter OutCount =
995 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
996 if (OutCount != ParentCount)
997 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000998 }
999
1000 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001001 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001002 if (S->getInit())
1003 Visit(S->getInit());
1004
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001005 Counter ParentCount = getRegion().getCounter();
1006 Counter BodyCount = getRegionCounter(S);
1007
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001008 // The loop increment may contain a break or continue.
1009 if (S->getInc())
1010 BreakContinueStack.emplace_back();
1011
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001012 // Handle the body first so that we can get the backedge count.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001013 BreakContinueStack.emplace_back();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001014 extendRegion(S->getBody());
1015 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001016 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +00001017
1018 // The increment is essentially part of the body but it needs to include
1019 // the count for all the continue statements.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001020 BreakContinue IncrementBC;
1021 if (const Stmt *Inc = S->getInc()) {
1022 propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1023 IncrementBC = BreakContinueStack.pop_back_val();
1024 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001025
1026 // Go back to handle the condition.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001027 Counter CondCount = addCounters(
1028 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1029 IncrementBC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001030 if (const Expr *Cond = S->getCond()) {
1031 propagateCounts(CondCount, Cond);
1032 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +00001033 }
1034
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001035 // The body count applies to the area immediately after the increment.
1036 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1037 getStart(S->getBody()));
1038 if (Gap)
1039 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1040
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001041 Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1042 subtractCounters(CondCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001043 if (OutCount != ParentCount)
1044 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001045 }
1046
1047 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001048 extendRegion(S);
Richard Smith8baa5002018-09-28 18:44:09 +00001049 if (S->getInit())
1050 Visit(S->getInit());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001051 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +00001052 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001053
1054 Counter ParentCount = getRegion().getCounter();
1055 Counter BodyCount = getRegionCounter(S);
1056
Alex Lorenzee024992014-08-04 18:41:51 +00001057 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001058 extendRegion(S->getBody());
1059 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001060 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001061
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001062 // The body count applies to the area immediately after the range.
1063 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1064 getStart(S->getBody()));
1065 if (Gap)
1066 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1067
Justin Bogner15874322015-04-30 21:31:02 +00001068 Counter LoopCount =
1069 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1070 Counter OutCount =
1071 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001072 if (OutCount != ParentCount)
1073 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001074 }
1075
1076 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001077 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001078 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001079
1080 Counter ParentCount = getRegion().getCounter();
1081 Counter BodyCount = getRegionCounter(S);
1082
Alex Lorenzee024992014-08-04 18:41:51 +00001083 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001084 extendRegion(S->getBody());
1085 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001086 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001087
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001088 // The body count applies to the area immediately after the collection.
1089 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1090 getStart(S->getBody()));
1091 if (Gap)
1092 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1093
Justin Bogner15874322015-04-30 21:31:02 +00001094 Counter LoopCount =
1095 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1096 Counter OutCount =
1097 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001098 if (OutCount != ParentCount)
1099 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001100 }
1101
1102 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001103 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +00001104 if (S->getInit())
1105 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +00001106 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001107
Alex Lorenzee024992014-08-04 18:41:51 +00001108 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001109
1110 const Stmt *Body = S->getBody();
1111 extendRegion(Body);
1112 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1113 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001114 // Make a region for the body of the switch. If the body starts with
1115 // a case, that case will reuse this region; otherwise, this covers
1116 // the unreachable code at the beginning of the switch body.
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001117 size_t Index =
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001118 pushRegion(Counter::getZero(), getStart(CS->body_front()));
Richard Trieub5841332015-04-15 01:21:42 +00001119 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001120 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001121
1122 // Set the end for the body of the switch, if it isn't already set.
1123 for (size_t i = RegionStack.size(); i != Index; --i) {
1124 if (!RegionStack[i - 1].hasEndLoc())
1125 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1126 }
1127
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001128 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +00001129 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +00001130 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001131 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +00001132 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001133
Alex Lorenzee024992014-08-04 18:41:51 +00001134 if (!BreakContinueStack.empty())
1135 BreakContinueStack.back().ContinueCount = addCounters(
1136 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001137
1138 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001139 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +00001140 pushRegion(ExitCount);
1141
1142 // Ensure that handleFileExit recognizes when the end location is located
1143 // in a different file.
1144 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001145 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +00001146 }
1147
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001148 void VisitSwitchCase(const SwitchCase *S) {
1149 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001150
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001151 SourceMappingRegion &Parent = getRegion();
1152
1153 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1154 // Reuse the existing region if it starts at our label. This is typical of
1155 // the first case in a switch.
Stephen Kellya6e43582018-08-09 21:05:56 +00001156 if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001157 Parent.setCounter(Count);
1158 else
1159 pushRegion(Count, getStart(S));
1160
Sanjay Patel376c06c2015-12-24 21:11:29 +00001161 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001162 Visit(CS->getLHS());
1163 if (const Expr *RHS = CS->getRHS())
1164 Visit(RHS);
1165 }
Alex Lorenzee024992014-08-04 18:41:51 +00001166 Visit(S->getSubStmt());
1167 }
1168
1169 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001170 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +00001171 if (S->getInit())
1172 Visit(S->getInit());
1173
Justin Bogner055ebc32015-06-16 06:24:15 +00001174 // Extend into the condition before we propagate through it below - this is
1175 // needed to handle macros that generate the "if" but not the condition.
1176 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +00001177
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001178 Counter ParentCount = getRegion().getCounter();
1179 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001180
Justin Bogner91f2e3c2015-02-19 03:10:30 +00001181 // Emitting a counter for the condition makes it easier to interpret the
1182 // counter for the body when looking at the coverage.
1183 propagateCounts(ParentCount, S->getCond());
1184
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001185 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001186 auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1187 if (Gap)
1188 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001189
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001190 extendRegion(S->getThen());
1191 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1192
1193 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1194 if (const Stmt *Else = S->getElse()) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001195 // The 'else' count applies to the area immediately after the 'then'.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001196 Gap = findGapAreaBetween(S->getThen(), Else);
1197 if (Gap)
1198 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001199 extendRegion(Else);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001200 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1201 } else
1202 OutCount = addCounters(OutCount, ElseCount);
1203
1204 if (OutCount != ParentCount)
1205 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001206 }
1207
1208 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001209 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +00001210 // Handle macros that generate the "try" but not the rest.
1211 extendRegion(S->getTryBlock());
1212
1213 Counter ParentCount = getRegion().getCounter();
1214 propagateCounts(ParentCount, S->getTryBlock());
1215
Alex Lorenzee024992014-08-04 18:41:51 +00001216 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1217 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001218
1219 Counter ExitCount = getRegionCounter(S);
1220 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001221 }
1222
1223 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001224 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +00001225 }
1226
1227 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001228 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001229
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001230 Counter ParentCount = getRegion().getCounter();
1231 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001232
Justin Bognere3654ce2015-04-24 23:37:57 +00001233 Visit(E->getCond());
1234
1235 if (!isa<BinaryConditionalOperator>(E)) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001236 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001237 auto Gap =
1238 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1239 if (Gap)
1240 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001241
Justin Bognere3654ce2015-04-24 23:37:57 +00001242 extendRegion(E->getTrueExpr());
1243 propagateCounts(TrueCount, E->getTrueExpr());
1244 }
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001245
Justin Bognere3654ce2015-04-24 23:37:57 +00001246 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001247 propagateCounts(subtractCounters(ParentCount, TrueCount),
1248 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +00001249 }
1250
1251 void VisitBinLAnd(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001252 extendRegion(E->getLHS());
1253 propagateCounts(getRegion().getCounter(), E->getLHS());
1254 handleFileExit(getEnd(E->getLHS()));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001255
1256 extendRegion(E->getRHS());
1257 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001258 }
1259
1260 void VisitBinLOr(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001261 extendRegion(E->getLHS());
1262 propagateCounts(getRegion().getCounter(), E->getLHS());
1263 handleFileExit(getEnd(E->getLHS()));
Alex Lorenzee024992014-08-04 18:41:51 +00001264
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001265 extendRegion(E->getRHS());
1266 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +00001267 }
Justin Bognerc1091022015-02-24 04:13:56 +00001268
1269 void VisitLambdaExpr(const LambdaExpr *LE) {
1270 // Lambdas are treated as their own functions for now, so we shouldn't
1271 // propagate counts into them.
1272 }
Alex Lorenzee024992014-08-04 18:41:51 +00001273};
Alex Lorenzee024992014-08-04 18:41:51 +00001274
Xinliang David Li1f39fcf2017-04-14 04:14:29 +00001275std::string getCoverageSection(const CodeGenModule &CGM) {
Vedant Kumar8a767a42017-04-15 00:10:05 +00001276 return llvm::getInstrProfSectionName(
1277 llvm::IPSK_covmap,
1278 CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
Alex Lorenzee024992014-08-04 18:41:51 +00001279}
1280
Reid Kleckner7cd595d2019-10-28 14:40:17 -07001281std::string normalizeFilename(StringRef Filename) {
1282 llvm::SmallString<256> Path(Filename);
1283 llvm::sys::fs::make_absolute(Path);
1284 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1285 return Path.str().str();
1286}
1287
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001288} // end anonymous namespace
1289
Justin Bognera432d172015-02-03 00:20:24 +00001290static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1291 ArrayRef<CounterExpression> Expressions,
1292 ArrayRef<CounterMappingRegion> Regions) {
1293 OS << FunctionName << ":\n";
1294 CounterMappingContext Ctx(Expressions);
1295 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001296 OS.indent(2);
1297 switch (R.Kind) {
1298 case CounterMappingRegion::CodeRegion:
1299 break;
1300 case CounterMappingRegion::ExpansionRegion:
1301 OS << "Expansion,";
1302 break;
1303 case CounterMappingRegion::SkippedRegion:
1304 OS << "Skipped,";
1305 break;
Vedant Kumara1c4deb2017-09-18 23:37:30 +00001306 case CounterMappingRegion::GapRegion:
1307 OS << "Gap,";
1308 break;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001309 }
1310
Justin Bogner4da909b2015-02-03 21:35:49 +00001311 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1312 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001313 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001314 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001315 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1316 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001317 }
1318}
1319
Alex Lorenzee024992014-08-04 18:41:51 +00001320void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001321 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001322 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001323 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Alex Lorenzee024992014-08-04 18:41:51 +00001324 if (!FunctionRecordTy) {
Xinliang David Li2129ae52016-01-07 20:05:55 +00001325#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
Xinliang David Lia026a432015-11-05 05:46:39 +00001326 llvm::Type *FunctionRecordTypes[] = {
1327 #include "llvm/ProfileData/InstrProfData.inc"
1328 };
Alex Lorenzee024992014-08-04 18:41:51 +00001329 FunctionRecordTy =
Justin Bogner4dc5adc2015-07-02 20:47:25 +00001330 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1331 /*isPacked=*/true);
Alex Lorenzee024992014-08-04 18:41:51 +00001332 }
1333
Xinliang David Lia026a432015-11-05 05:46:39 +00001334 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
Alex Lorenzee024992014-08-04 18:41:51 +00001335 llvm::Constant *FunctionRecordVals[] = {
Xinliang David Lia026a432015-11-05 05:46:39 +00001336 #include "llvm/ProfileData/InstrProfData.inc"
1337 };
Alex Lorenzee024992014-08-04 18:41:51 +00001338 FunctionRecords.push_back(llvm::ConstantStruct::get(
1339 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
Xinliang David Li848da132016-01-19 00:49:06 +00001340 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001341 FunctionNames.push_back(
1342 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Vedant Kumarca3326c2016-01-21 19:25:35 +00001343 CoverageMappings.push_back(CoverageMapping);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001344
1345 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1346 // Dump the coverage mapping data for this function by decoding the
1347 // encoded data. This allows us to dump the mapping regions which were
1348 // also processed by the CoverageMappingWriter which performs
1349 // additional minimization operations such as reducing the number of
1350 // expressions.
1351 std::vector<StringRef> Filenames;
1352 std::vector<CounterExpression> Expressions;
1353 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001354 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001355 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001356 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001357 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001358 for (const auto &Entry : FileEntries) {
1359 auto I = Entry.second;
1360 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1361 FilenameRefs[I] = FilenameStrs[I];
1362 }
Justin Bognera432d172015-02-03 00:20:24 +00001363 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1364 Expressions, Regions);
1365 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001366 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001367 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001368 }
Alex Lorenzee024992014-08-04 18:41:51 +00001369}
1370
1371void CoverageMappingModuleGen::emit() {
1372 if (FunctionRecords.empty())
1373 return;
1374 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1375 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1376
1377 // Create the filenames and merge them with coverage mappings
1378 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001379 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001380 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001381 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001382 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001383 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001384 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001385 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001386 }
1387
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001388 std::string FilenamesAndCoverageMappings;
1389 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1390 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
Serge Guelton4cd07db2019-06-05 06:35:10 +00001391
1392 // Stream the content of CoverageMappings to OS while keeping
1393 // memory consumption under control.
1394 size_t CoverageMappingSize = 0;
1395 for (auto &S : CoverageMappings) {
1396 CoverageMappingSize += S.size();
1397 OS << S;
1398 S.clear();
1399 S.shrink_to_fit();
1400 }
1401 CoverageMappings.clear();
1402 CoverageMappings.shrink_to_fit();
1403
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001404 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1405 // Append extra zeroes if necessary to ensure that the size of the filenames
1406 // and coverage mappings is a multiple of 8.
1407 if (size_t Rem = OS.str().size() % 8) {
1408 CoverageMappingSize += 8 - Rem;
Peter Collingbourne070777d2018-05-17 22:11:43 +00001409 OS.write_zeros(8 - Rem);
Alex Lorenzee024992014-08-04 18:41:51 +00001410 }
1411 auto *FilenamesAndMappingsVal =
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001412 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
Alex Lorenzee024992014-08-04 18:41:51 +00001413
1414 // Create the deferred function records array
1415 auto RecordsTy =
1416 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1417 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1418
Xinliang David Li20b188c2016-01-03 19:25:54 +00001419 llvm::Type *CovDataHeaderTypes[] = {
1420#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1421#include "llvm/ProfileData/InstrProfData.inc"
1422 };
1423 auto CovDataHeaderTy =
1424 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1425 llvm::Constant *CovDataHeaderVals[] = {
1426#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1427#include "llvm/ProfileData/InstrProfData.inc"
1428 };
1429 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1430 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1431
Alex Lorenzee024992014-08-04 18:41:51 +00001432 // Create the coverage data record
Xinliang David Li20b188c2016-01-03 19:25:54 +00001433 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1434 FilenamesAndMappingsVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001435 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001436 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1437 FilenamesAndMappingsVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001438 auto CovDataVal =
1439 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001440 auto CovData = new llvm::GlobalVariable(
1441 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1442 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001443
1444 CovData->setSection(getCoverageSection(CGM));
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001445 CovData->setAlignment(llvm::Align(8));
Alex Lorenzee024992014-08-04 18:41:51 +00001446
1447 // Make sure the data doesn't get deleted.
1448 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001449 // Create the deferred function records array
1450 if (!FunctionNames.empty()) {
1451 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1452 FunctionNames.size());
1453 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1454 // This variable will *NOT* be emitted to the object file. It is used
1455 // to pass the list of names referenced to codegen.
1456 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1457 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001458 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001459 }
Alex Lorenzee024992014-08-04 18:41:51 +00001460}
1461
1462unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1463 auto It = FileEntries.find(File);
1464 if (It != FileEntries.end())
1465 return It->second;
1466 unsigned FileID = FileEntries.size();
1467 FileEntries.insert(std::make_pair(File, FileID));
1468 return FileID;
1469}
1470
1471void CoverageMappingGen::emitCounterMapping(const Decl *D,
1472 llvm::raw_ostream &OS) {
1473 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001474 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001475 Walker.VisitDecl(D);
1476 Walker.write(OS);
1477}
1478
1479void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1480 llvm::raw_ostream &OS) {
1481 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1482 Walker.VisitDecl(D);
1483 Walker.write(OS);
1484}