blob: 35962c73d9a8254afba7162a15a2e45cb9ef7fd5 [file] [log] [blame]
Alex Lorenzee024992014-08-04 18:41:51 +00001//===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Instrumentation-based code coverage mapping generator
11//
12//===----------------------------------------------------------------------===//
13
14#include "CoverageMappingGen.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/Lex/Lexer.h"
Vedant Kumarbc6b80a2016-01-28 17:52:18 +000018#include "llvm/ADT/SmallSet.h"
Vedant Kumarca3326c2016-01-21 19:25:35 +000019#include "llvm/ADT/StringExtras.h"
Justin Bognerbf42cfd2015-02-18 21:24:51 +000020#include "llvm/ADT/Optional.h"
Easwaran Ramanb014ee42016-04-29 18:53:16 +000021#include "llvm/ProfileData/Coverage/CoverageMapping.h"
22#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000025#include "llvm/Support/FileSystem.h"
Vedant Kumar14f8fb62016-07-18 21:01:27 +000026#include "llvm/Support/Path.h"
Alex Lorenzee024992014-08-04 18:41:51 +000027
28using namespace clang;
29using namespace CodeGen;
30using namespace llvm::coverage;
31
Vedant Kumar3919a502017-09-11 20:47:42 +000032void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
Alex Lorenzee024992014-08-04 18:41:51 +000033 SkippedRanges.push_back(Range);
34}
35
36namespace {
37
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000038/// A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000039class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000040 Counter Count;
41
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000043 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000044
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000046 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000047
Vedant Kumar747b0e22017-09-08 18:44:56 +000048 /// Whether this region should be emitted after its parent is emitted.
49 bool DeferRegion;
50
Vedant Kumara1c4deb2017-09-18 23:37:30 +000051 /// Whether this region is a gap region. The count from a gap region is set
52 /// as the line execution count if there are no other regions on the line.
53 bool GapRegion;
54
Justin Bogner09c71792014-10-01 03:33:49 +000055public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000056 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Vedant Kumara1c4deb2017-09-18 23:37:30 +000057 Optional<SourceLocation> LocEnd, bool DeferRegion = false,
58 bool GapRegion = false)
Vedant Kumar747b0e22017-09-08 18:44:56 +000059 : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
Vedant Kumara1c4deb2017-09-18 23:37:30 +000060 DeferRegion(DeferRegion), GapRegion(GapRegion) {}
Alex Lorenzee024992014-08-04 18:41:51 +000061
Justin Bogner09c71792014-10-01 03:33:49 +000062 const Counter &getCounter() const { return Count; }
63
Justin Bognerbf42cfd2015-02-18 21:24:51 +000064 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000065
Justin Bognerbf42cfd2015-02-18 21:24:51 +000066 bool hasStartLoc() const { return LocStart.hasValue(); }
67
68 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
69
Stephen Kelly3cffc4c2018-08-09 20:05:18 +000070 SourceLocation getBeginLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000071 assert(LocStart && "Region has no start location");
72 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000073 }
74
Justin Bognerbf42cfd2015-02-18 21:24:51 +000075 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000076
Vedant Kumara14a1f92018-01-17 18:53:51 +000077 void setEndLoc(SourceLocation Loc) {
78 assert(Loc.isValid() && "Setting an invalid end location");
79 LocEnd = Loc;
80 }
Alex Lorenzee024992014-08-04 18:41:51 +000081
Craig Topper462c77b2015-09-26 05:10:14 +000082 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000083 assert(LocEnd && "Region has no end location");
84 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000085 }
Vedant Kumar747b0e22017-09-08 18:44:56 +000086
87 bool isDeferred() const { return DeferRegion; }
88
89 void setDeferred(bool Deferred) { DeferRegion = Deferred; }
Vedant Kumara1c4deb2017-09-18 23:37:30 +000090
91 bool isGap() const { return GapRegion; }
92
93 void setGap(bool Gap) { GapRegion = Gap; }
Alex Lorenzee024992014-08-04 18:41:51 +000094};
95
Vedant Kumard7369642017-07-27 02:20:25 +000096/// Spelling locations for the start and end of a source region.
97struct SpellingRegion {
98 /// The line where the region starts.
99 unsigned LineStart;
100
101 /// The column where the region starts.
102 unsigned ColumnStart;
103
104 /// The line where the region ends.
105 unsigned LineEnd;
106
107 /// The column where the region ends.
108 unsigned ColumnEnd;
109
110 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
111 SourceLocation LocEnd) {
112 LineStart = SM.getSpellingLineNumber(LocStart);
113 ColumnStart = SM.getSpellingColumnNumber(LocStart);
114 LineEnd = SM.getSpellingLineNumber(LocEnd);
115 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
116 }
117
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000118 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
Stephen Kellya6e43582018-08-09 21:05:56 +0000119 : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000120
Vedant Kumard7369642017-07-27 02:20:25 +0000121 /// Check if the start and end locations appear in source order, i.e
122 /// top->bottom, left->right.
123 bool isInSourceOrder() const {
124 return (LineStart < LineEnd) ||
125 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
126 }
127};
128
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000129/// Provides the common functionality for the different
Alex Lorenzee024992014-08-04 18:41:51 +0000130/// coverage mapping region builders.
131class CoverageMappingBuilder {
132public:
133 CoverageMappingModuleGen &CVM;
134 SourceManager &SM;
135 const LangOptions &LangOpts;
136
137private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000138 /// Map of clang's FileIDs to IDs used for coverage mapping.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000139 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
140 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000141
142public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000143 /// The coverage mapping regions for this function
Alex Lorenzee024992014-08-04 18:41:51 +0000144 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000145 /// The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000146 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000147
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000148 /// A set of regions which can be used as a filter.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000149 ///
150 /// It is produced by emitExpansionRegions() and is used in
151 /// emitSourceRegions() to suppress producing code regions if
152 /// the same area is covered by expansion regions.
153 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
154 SourceRegionFilter;
155
Alex Lorenzee024992014-08-04 18:41:51 +0000156 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
157 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000158 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000159
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000160 /// Return the precise end location for the given token.
Alex Lorenzee024992014-08-04 18:41:51 +0000161 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000162 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
163 // macro locations, which we just treat as expanded files.
164 unsigned TokLen =
165 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
166 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000167 }
168
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000169 /// Return the start location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000170 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
171 if (Loc.isMacroID())
172 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
173 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000174 }
175
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000176 /// Return the end location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000177 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
178 if (Loc.isMacroID())
179 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000180 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000181 return SM.getLocForEndOfFile(SM.getFileID(Loc));
182 }
183
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000184 /// Find out where the current file is included or macro is expanded.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000185 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
Richard Smithb5f81712018-04-30 05:25:48 +0000186 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000187 : SM.getIncludeLoc(SM.getFileID(Loc));
188 }
189
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000190 /// Return true if \c Loc is a location in a built-in macro.
Justin Bogner682bfbf2015-05-14 22:14:10 +0000191 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000192 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000193 }
194
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000195 /// Check whether \c Loc is included or expanded from \c Parent.
Igor Kudrind9e1a612016-06-07 10:07:51 +0000196 bool isNestedIn(SourceLocation Loc, FileID Parent) {
197 do {
198 Loc = getIncludeOrExpansionLoc(Loc);
199 if (Loc.isInvalid())
200 return false;
201 } while (!SM.isInFileID(Loc, Parent));
202 return true;
203 }
204
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000205 /// Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000206 SourceLocation getStart(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000207 SourceLocation Loc = S->getBeginLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000208 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000209 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000210 return Loc;
211 }
212
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000213 /// Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000214 SourceLocation getEnd(const Stmt *S) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000215 SourceLocation Loc = S->getEndLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000216 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000217 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerf14b2072015-03-25 04:13:49 +0000218 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000219 }
220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221 /// Find the set of files we have regions for and assign IDs
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000222 ///
223 /// Fills \c Mapping with the virtual file mapping needed to write out
224 /// coverage and collects the necessary file information to emit source and
225 /// expansion regions.
226 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
227 FileIDMapping.clear();
228
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000229 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000230 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
231 for (const auto &Region : SourceRegions) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000232 SourceLocation Loc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000233 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000234 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000235 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000236
Vedant Kumar93205af2016-07-11 22:57:46 +0000237 // Do not map FileID's associated with system headers.
238 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
239 continue;
240
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000241 unsigned Depth = 0;
242 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000243 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000244 ++Depth;
245 FileLocs.push_back(std::make_pair(Loc, Depth));
246 }
247 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
248
249 for (const auto &FL : FileLocs) {
250 SourceLocation Loc = FL.first;
251 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
252 auto Entry = SM.getFileEntryForID(SpellingFile);
253 if (!Entry)
254 continue;
255
256 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
257 Mapping.push_back(CVM.getFileID(Entry));
258 }
259 }
260
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000261 /// Get the coverage mapping file ID for \c Loc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000262 ///
263 /// If such file id doesn't exist, return None.
264 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
265 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000266 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000267 return Mapping->second.first;
268 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000269 }
270
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000271 /// Gather all the regions that were skipped by the preprocessor
Alex Lorenzee024992014-08-04 18:41:51 +0000272 /// using the constructs like #if.
273 void gatherSkippedRegions() {
274 /// An array of the minimum lineStarts and the maximum lineEnds
275 /// for mapping regions from the appropriate source files.
276 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
277 FileLineRanges.resize(
278 FileIDMapping.size(),
279 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
280 for (const auto &R : MappingRegions) {
281 FileLineRanges[R.FileID].first =
282 std::min(FileLineRanges[R.FileID].first, R.LineStart);
283 FileLineRanges[R.FileID].second =
284 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
285 }
286
287 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
288 for (const auto &I : SkippedRanges) {
289 auto LocStart = I.getBegin();
290 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000291 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
292 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000293
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000294 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000295 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000296 continue;
Vedant Kumard7369642017-07-27 02:20:25 +0000297 SpellingRegion SR{SM, LocStart, LocEnd};
Justin Bognerfd34280b2015-02-03 23:59:48 +0000298 auto Region = CounterMappingRegion::makeSkipped(
Vedant Kumard7369642017-07-27 02:20:25 +0000299 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000300 // Make sure that we only collect the regions that are inside
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000301 // the source code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000302 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
303 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000304 MappingRegions.push_back(Region);
305 }
306 }
307
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000308 /// Generate the coverage counter mapping regions from collected
Alex Lorenzee024992014-08-04 18:41:51 +0000309 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000310 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000311 for (const auto &Region : SourceRegions) {
312 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000313
Stephen Kellya6e43582018-08-09 21:05:56 +0000314 SourceLocation LocStart = Region.getBeginLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000315 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000316
Vedant Kumar93205af2016-07-11 22:57:46 +0000317 // Ignore regions from system headers.
318 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
319 continue;
320
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000321 auto CovFileID = getCoverageFileID(LocStart);
322 // Ignore regions that don't have a file, such as builtin macros.
323 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000324 continue;
325
Justin Bognerf14b2072015-03-25 04:13:49 +0000326 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000327 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
328 "region spans multiple files");
329
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000330 // Don't add code regions for the area covered by expansion regions.
331 // This not only suppresses redundant regions, but sometimes prevents
332 // creating regions with wrong counters if, for example, a statement's
333 // body ends at the end of a nested macro.
334 if (Filter.count(std::make_pair(LocStart, LocEnd)))
335 continue;
336
Vedant Kumard7369642017-07-27 02:20:25 +0000337 // Find the spelling locations for the mapping region.
338 SpellingRegion SR{SM, LocStart, LocEnd};
339 assert(SR.isInSourceOrder() && "region start and end out of order");
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000340
341 if (Region.isGap()) {
342 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
343 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
344 SR.LineEnd, SR.ColumnEnd));
345 } else {
346 MappingRegions.push_back(CounterMappingRegion::makeRegion(
347 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
348 SR.LineEnd, SR.ColumnEnd));
349 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000350 }
351 }
352
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000353 /// Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000354 SourceRegionFilter emitExpansionRegions() {
355 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000356 for (const auto &FM : FileIDMapping) {
357 SourceLocation ExpandedLoc = FM.second.second;
358 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
359 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000360 continue;
361
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000362 auto ParentFileID = getCoverageFileID(ParentLoc);
363 if (!ParentFileID)
364 continue;
365 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
366 assert(ExpandedFileID && "expansion in uncovered file");
367
368 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
369 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
370 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000371 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000372
Vedant Kumard7369642017-07-27 02:20:25 +0000373 SpellingRegion SR{SM, ParentLoc, LocEnd};
374 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000375 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000376 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
377 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000378 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000379 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000380 }
381};
382
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000383/// Creates unreachable coverage regions for the functions that
Alex Lorenzee024992014-08-04 18:41:51 +0000384/// are not emitted.
385struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
386 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
387 const LangOptions &LangOpts)
388 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
389
390 void VisitDecl(const Decl *D) {
391 if (!D->hasBody())
392 return;
393 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000394 SourceLocation Start = getStart(Body);
395 SourceLocation End = getEnd(Body);
396 if (!SM.isWrittenInSameFile(Start, End)) {
397 // Walk up to find the common ancestor.
398 // Correct the locations accordingly.
399 FileID StartFileID = SM.getFileID(Start);
400 FileID EndFileID = SM.getFileID(End);
401 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
402 Start = getIncludeOrExpansionLoc(Start);
403 assert(Start.isValid() &&
404 "Declaration start location not nested within a known region");
405 StartFileID = SM.getFileID(Start);
406 }
407 while (StartFileID != EndFileID) {
408 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
409 assert(End.isValid() &&
410 "Declaration end location not nested within a known region");
411 EndFileID = SM.getFileID(End);
412 }
413 }
414 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000415 }
416
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000417 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000418 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000419 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000420 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000421 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000422
Vedant Kumarefd319a2016-07-26 00:24:59 +0000423 if (MappingRegions.empty())
424 return;
425
Craig Topper5fc8fc22014-08-27 06:28:36 +0000426 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000427 Writer.write(OS);
428 }
429};
430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000431/// A StmtVisitor that creates coverage mapping regions which map
Alex Lorenzee024992014-08-04 18:41:51 +0000432/// from the source code locations to the PGO counters.
433struct CounterCoverageMappingBuilder
434 : public CoverageMappingBuilder,
435 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000436 /// The map of statements to count values.
Alex Lorenzee024992014-08-04 18:41:51 +0000437 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
438
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000439 /// A stack of currently live regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000440 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000441
Vedant Kumar747b0e22017-09-08 18:44:56 +0000442 /// The currently deferred region: its end location and count can be set once
443 /// its parent has been popped from the region stack.
444 Optional<SourceMappingRegion> DeferredRegion;
445
Alex Lorenzee024992014-08-04 18:41:51 +0000446 CounterExpressionBuilder Builder;
447
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000448 /// A location in the most recently visited file or macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000449 ///
450 /// This is used to adjust the active source regions appropriately when
451 /// expressions cross file or macro boundaries.
452 SourceLocation MostRecentLocation;
453
Vedant Kumar8046d222017-11-09 02:33:39 +0000454 /// Location of the last terminated region.
455 Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
456
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000457 /// Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000458 Counter subtractCounters(Counter LHS, Counter RHS) {
459 return Builder.subtract(LHS, RHS);
460 }
461
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000462 /// Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000463 Counter addCounters(Counter LHS, Counter RHS) {
464 return Builder.add(LHS, RHS);
465 }
466
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000467 Counter addCounters(Counter C1, Counter C2, Counter C3) {
468 return addCounters(addCounters(C1, C2), C3);
469 }
470
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000471 /// Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000472 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000473 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000474 Counter getRegionCounter(const Stmt *S) {
475 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000476 }
477
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000478 /// Push a region onto the stack.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000479 ///
480 /// Returns the index on the stack where the region was pushed. This can be
481 /// used with popRegions to exit a "scope", ending the region that was pushed.
482 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
483 Optional<SourceLocation> EndLoc = None) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000484 if (StartLoc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000485 MostRecentLocation = *StartLoc;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000486 completeDeferred(Count, MostRecentLocation);
487 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000488 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000489
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000490 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000491 }
492
Vedant Kumar747b0e22017-09-08 18:44:56 +0000493 /// Complete any pending deferred region by setting its end location and
494 /// count, and then pushing it onto the region stack.
495 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
496 size_t Index = RegionStack.size();
497 if (!DeferredRegion)
498 return Index;
499
500 // Consume the pending region.
501 SourceMappingRegion DR = DeferredRegion.getValue();
502 DeferredRegion = None;
503
504 // If the region ends in an expansion, find the expansion site.
Stephen Kellya6e43582018-08-09 21:05:56 +0000505 FileID StartFile = SM.getFileID(DR.getBeginLoc());
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000506 if (SM.getFileID(DeferredEndLoc) != StartFile) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000507 if (isNestedIn(DeferredEndLoc, StartFile)) {
508 do {
509 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
510 } while (StartFile != SM.getFileID(DeferredEndLoc));
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000511 } else {
512 return Index;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000513 }
514 }
515
516 // The parent of this deferred region ends where the containing decl ends,
517 // so the region isn't useful.
Stephen Kellya6e43582018-08-09 21:05:56 +0000518 if (DR.getBeginLoc() == DeferredEndLoc)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000519 return Index;
520
521 // If we're visiting statements in non-source order (e.g switch cases or
522 // a loop condition) we can't construct a sensible deferred region.
Stephen Kellya6e43582018-08-09 21:05:56 +0000523 if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000524 return Index;
525
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000526 DR.setGap(true);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000527 DR.setCounter(Count);
528 DR.setEndLoc(DeferredEndLoc);
529 handleFileExit(DeferredEndLoc);
530 RegionStack.push_back(DR);
531 return Index;
532 }
533
Vedant Kumar8046d222017-11-09 02:33:39 +0000534 /// Complete a deferred region created after a terminated region at the
535 /// top-level.
536 void completeTopLevelDeferredRegion(Counter Count,
537 SourceLocation DeferredEndLoc) {
538 if (DeferredRegion || !LastTerminatedRegion)
539 return;
540
541 if (LastTerminatedRegion->second != RegionStack.size())
542 return;
543
544 SourceLocation Start = LastTerminatedRegion->first;
545 if (SM.getFileID(Start) != SM.getMainFileID())
546 return;
547
548 SourceMappingRegion DR = RegionStack.back();
549 DR.setStartLoc(Start);
550 DR.setDeferred(false);
551 DeferredRegion = DR;
552 completeDeferred(Count, DeferredEndLoc);
553 }
554
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000555 size_t locationDepth(SourceLocation Loc) {
556 size_t Depth = 0;
557 while (Loc.isValid()) {
558 Loc = getIncludeOrExpansionLoc(Loc);
559 Depth++;
560 }
561 return Depth;
562 }
563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000564 /// Pop regions from the stack into the function's list of regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000565 ///
566 /// Adds all regions from \c ParentIndex to the top of the stack to the
567 /// function's \c SourceRegions.
568 void popRegions(size_t ParentIndex) {
569 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
Vedant Kumar747b0e22017-09-08 18:44:56 +0000570 bool ParentOfDeferredRegion = false;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000571 while (RegionStack.size() > ParentIndex) {
572 SourceMappingRegion &Region = RegionStack.back();
573 if (Region.hasStartLoc()) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000574 SourceLocation StartLoc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000575 SourceLocation EndLoc = Region.hasEndLoc()
576 ? Region.getEndLoc()
577 : RegionStack[ParentIndex].getEndLoc();
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000578 size_t StartDepth = locationDepth(StartLoc);
579 size_t EndDepth = locationDepth(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000580 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000581 bool UnnestStart = StartDepth >= EndDepth;
582 bool UnnestEnd = EndDepth >= StartDepth;
583 if (UnnestEnd) {
584 // The region ends in a nested file or macro expansion. Create a
585 // separate region for each expansion.
586 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
587 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000588
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000589 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
590 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000591
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000592 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
593 if (EndLoc.isInvalid())
594 llvm::report_fatal_error("File exit not handled before popRegions");
595 EndDepth--;
596 }
597 if (UnnestStart) {
598 // The region begins in a nested file or macro expansion. Create a
599 // separate region for each expansion.
600 SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
601 assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
602
603 if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
604 SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
605
606 StartLoc = getIncludeOrExpansionLoc(StartLoc);
607 if (StartLoc.isInvalid())
608 llvm::report_fatal_error("File exit not handled before popRegions");
609 StartDepth--;
610 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000611 }
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000612 Region.setStartLoc(StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000613 Region.setEndLoc(EndLoc);
614
615 MostRecentLocation = EndLoc;
616 // If this region happens to span an entire expansion, we need to make
617 // sure we don't overlap the parent region with it.
618 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
619 EndLoc == getEndOfFileOrMacro(EndLoc))
620 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
621
Stephen Kellya6e43582018-08-09 21:05:56 +0000622 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000623 assert(SpellingRegion(SM, Region).isInSourceOrder());
Craig Topperf36a5c42015-09-26 05:10:16 +0000624 SourceRegions.push_back(Region);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000625
626 if (ParentOfDeferredRegion) {
627 ParentOfDeferredRegion = false;
628
629 // If there's an existing deferred region, keep the old one, because
630 // it means there are two consecutive returns (or a similar pattern).
631 if (!DeferredRegion.hasValue() &&
632 // File IDs aren't gathered within macro expansions, so it isn't
633 // useful to try and create a deferred region inside of one.
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000634 !EndLoc.isMacroID())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000635 DeferredRegion =
636 SourceMappingRegion(Counter::getZero(), EndLoc, None);
637 }
638 } else if (Region.isDeferred()) {
639 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
640 ParentOfDeferredRegion = true;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000641 }
642 RegionStack.pop_back();
Vedant Kumar8046d222017-11-09 02:33:39 +0000643
644 // If the zero region pushed after the last terminated region no longer
645 // exists, clear its cached information.
646 if (LastTerminatedRegion &&
647 RegionStack.size() < LastTerminatedRegion->second)
648 LastTerminatedRegion = None;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000649 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000650 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
Alex Lorenzee024992014-08-04 18:41:51 +0000651 }
652
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000653 /// Return the currently active region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000654 SourceMappingRegion &getRegion() {
655 assert(!RegionStack.empty() && "statement has no region");
656 return RegionStack.back();
657 }
Alex Lorenzee024992014-08-04 18:41:51 +0000658
Vedant Kumar7225a262018-11-28 20:48:07 +0000659 /// Propagate counts through the children of \p S if \p VisitChildren is true.
660 /// Otherwise, only emit a count for \p S itself.
661 Counter propagateCounts(Counter TopCount, const Stmt *S,
662 bool VisitChildren = true) {
Vedant Kumar78386962017-07-27 02:20:20 +0000663 SourceLocation StartLoc = getStart(S);
664 SourceLocation EndLoc = getEnd(S);
665 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Vedant Kumar7225a262018-11-28 20:48:07 +0000666 if (VisitChildren)
667 Visit(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000668 Counter ExitCount = getRegion().getCounter();
669 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000670
671 // The statement may be spanned by an expansion. Make sure we handle a file
672 // exit out of this expansion before moving to the next statement.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000673 if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
Vedant Kumar78386962017-07-27 02:20:20 +0000674 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000675
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000676 return ExitCount;
677 }
Alex Lorenzee024992014-08-04 18:41:51 +0000678
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000679 /// Check whether a region with bounds \c StartLoc and \c EndLoc
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000680 /// is already added to \c SourceRegions.
681 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
682 return SourceRegions.rend() !=
683 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
684 [&](const SourceMappingRegion &Region) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000685 return Region.getBeginLoc() == StartLoc &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000686 Region.getEndLoc() == EndLoc;
687 });
688 }
689
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000690 /// Adjust the most recently visited location to \c EndLoc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000691 ///
692 /// This should be used after visiting any statements in non-source order.
693 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
694 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000695 // The code region for a whole macro is created in handleFileExit() when
696 // it detects exiting of the virtual file of that macro. If we visited
697 // statements in non-source order, we might already have such a region
698 // added, for example, if a body of a loop is divided among multiple
699 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000700 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000701 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
702 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
703 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000704 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
705 }
Alex Lorenzee024992014-08-04 18:41:51 +0000706
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000707 /// Adjust regions and state when \c NewLoc exits a file.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000708 ///
709 /// If moving from our most recently tracked location to \c NewLoc exits any
710 /// files, this adjusts our current region stack and creates the file regions
711 /// for the exited file.
712 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000713 if (NewLoc.isInvalid() ||
714 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000715 return;
716
717 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
718 // find the common ancestor.
719 SourceLocation LCA = NewLoc;
720 FileID ParentFile = SM.getFileID(LCA);
721 while (!isNestedIn(MostRecentLocation, ParentFile)) {
722 LCA = getIncludeOrExpansionLoc(LCA);
723 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
724 // Since there isn't a common ancestor, no file was exited. We just need
725 // to adjust our location to the new file.
726 MostRecentLocation = NewLoc;
727 return;
728 }
729 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000730 }
731
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000732 llvm::SmallSet<SourceLocation, 8> StartLocs;
733 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000734 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
735 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000736 continue;
Stephen Kellya6e43582018-08-09 21:05:56 +0000737 SourceLocation Loc = I.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000738 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000739 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000740 break;
741 }
Alex Lorenzee024992014-08-04 18:41:51 +0000742
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000743 while (!SM.isInFileID(Loc, ParentFile)) {
744 // The most nested region for each start location is the one with the
745 // correct count. We avoid creating redundant regions by stopping once
746 // we've seen this region.
747 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000748 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000749 getEndOfFileOrMacro(Loc));
750 Loc = getIncludeOrExpansionLoc(Loc);
751 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000752 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000753 }
754
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000755 if (ParentCounter) {
756 // If the file is contained completely by another region and doesn't
757 // immediately start its own region, the whole file gets a region
758 // corresponding to the parent.
759 SourceLocation Loc = MostRecentLocation;
760 while (isNestedIn(Loc, ParentFile)) {
761 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000762 if (StartLocs.insert(FileStart).second) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000763 SourceRegions.emplace_back(*ParentCounter, FileStart,
764 getEndOfFileOrMacro(Loc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000765 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
766 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000767 Loc = getIncludeOrExpansionLoc(Loc);
768 }
Alex Lorenzee024992014-08-04 18:41:51 +0000769 }
770
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000771 MostRecentLocation = NewLoc;
772 }
Alex Lorenzee024992014-08-04 18:41:51 +0000773
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000774 /// Ensure that \c S is included in the current region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000775 void extendRegion(const Stmt *S) {
776 SourceMappingRegion &Region = getRegion();
777 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000778
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000779 handleFileExit(StartLoc);
780 if (!Region.hasStartLoc())
781 Region.setStartLoc(StartLoc);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000782
783 completeDeferred(Region.getCounter(), StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000784 }
785
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000786 /// Mark \c S as a terminator, starting a zero region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000787 void terminateRegion(const Stmt *S) {
788 extendRegion(S);
789 SourceMappingRegion &Region = getRegion();
Vedant Kumar8046d222017-11-09 02:33:39 +0000790 SourceLocation EndLoc = getEnd(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000791 if (!Region.hasEndLoc())
Vedant Kumar8046d222017-11-09 02:33:39 +0000792 Region.setEndLoc(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000793 pushRegion(Counter::getZero());
Vedant Kumar8046d222017-11-09 02:33:39 +0000794 auto &ZeroRegion = getRegion();
795 ZeroRegion.setDeferred(true);
796 LastTerminatedRegion = {EndLoc, RegionStack.size()};
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000797 }
Alex Lorenzee024992014-08-04 18:41:51 +0000798
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000799 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
800 Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
801 SourceLocation BeforeLoc) {
802 // If the start and end locations of the gap are both within the same macro
803 // file, the range may not be in source order.
804 if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
805 return None;
806 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
807 return None;
808 return {{AfterLoc, BeforeLoc}};
809 }
810
811 /// Find the source range after \p AfterStmt and before \p BeforeStmt.
812 Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
813 const Stmt *BeforeStmt) {
814 return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
815 getStart(BeforeStmt));
816 }
817
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000818 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
819 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
820 Counter Count) {
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000821 if (StartLoc == EndLoc)
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000822 return;
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000823 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000824 handleFileExit(StartLoc);
825 size_t Index = pushRegion(Count, StartLoc, EndLoc);
826 getRegion().setGap(true);
827 handleFileExit(EndLoc);
828 popRegions(Index);
829 }
830
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000831 /// Keep counts of breaks and continues inside loops.
Alex Lorenzee024992014-08-04 18:41:51 +0000832 struct BreakContinue {
833 Counter BreakCount;
834 Counter ContinueCount;
835 };
836 SmallVector<BreakContinue, 8> BreakContinueStack;
837
838 CounterCoverageMappingBuilder(
839 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000840 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000841 const LangOptions &LangOpts)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000842 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
843 DeferredRegion(None) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000844
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000845 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000846 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000847 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000848 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000849 SourceRegionFilter Filter = emitExpansionRegions();
Vedant Kumar747b0e22017-09-08 18:44:56 +0000850 assert(!DeferredRegion && "Deferred region never completed");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000851 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000852 gatherSkippedRegions();
853
Vedant Kumarefd319a2016-07-26 00:24:59 +0000854 if (MappingRegions.empty())
855 return;
856
Justin Bogner4da909b2015-02-03 21:35:49 +0000857 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
858 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000859 Writer.write(OS);
860 }
861
Alex Lorenzee024992014-08-04 18:41:51 +0000862 void VisitStmt(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000863 if (S->getBeginLoc().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000864 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000865 for (const Stmt *Child : S->children())
866 if (Child)
867 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000868 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000869 }
870
Alex Lorenzee024992014-08-04 18:41:51 +0000871 void VisitDecl(const Decl *D) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000872 assert(!DeferredRegion && "Deferred region never completed");
873
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000874 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000875
876 // Do not propagate region counts into system headers.
877 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
878 return;
879
Vedant Kumar7225a262018-11-28 20:48:07 +0000880 // Do not visit the artificial children nodes of defaulted methods. The
881 // lexer may not be able to report back precise token end locations for
882 // these children nodes (llvm.org/PR39822), and moreover users will not be
883 // able to see coverage for them.
884 bool Defaulted = false;
885 if (auto *Method = dyn_cast<CXXMethodDecl>(D))
886 Defaulted = Method->isDefaulted();
887
888 propagateCounts(getRegionCounter(Body), Body,
889 /*VisitChildren=*/!Defaulted);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000890 assert(RegionStack.empty() && "Regions entered but never exited");
891
Vedant Kumar61763b62018-05-30 23:35:44 +0000892 // Discard the last uncompleted deferred region in a decl, if one exists.
893 // This prevents lines at the end of a function containing only whitespace
894 // or closing braces from being marked as uncovered.
895 DeferredRegion = None;
Alex Lorenzee024992014-08-04 18:41:51 +0000896 }
897
898 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000899 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000900 if (S->getRetValue())
901 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000902 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000903 }
904
Justin Bognerf959feb2015-04-28 06:31:55 +0000905 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
906 extendRegion(E);
907 if (E->getSubExpr())
908 Visit(E->getSubExpr());
909 terminateRegion(E);
910 }
911
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000912 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000913
914 void VisitLabelStmt(const LabelStmt *S) {
Vedant Kumar8046d222017-11-09 02:33:39 +0000915 Counter LabelCount = getRegionCounter(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000916 SourceLocation Start = getStart(S);
Vedant Kumar8046d222017-11-09 02:33:39 +0000917 completeTopLevelDeferredRegion(LabelCount, Start);
Vedant Kumard781d972018-06-01 00:37:13 +0000918 completeDeferred(LabelCount, Start);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000919 // We can't extendRegion here or we risk overlapping with our new region.
920 handleFileExit(Start);
Vedant Kumar8046d222017-11-09 02:33:39 +0000921 pushRegion(LabelCount, Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000922 Visit(S->getSubStmt());
923 }
924
925 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000926 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
927 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000928 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000929 // FIXME: a break in a switch should terminate regions for all preceding
930 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000931 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000932 }
933
934 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000935 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
936 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000937 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
938 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000939 }
940
Eli Friedman181dfe42017-08-08 20:10:14 +0000941 void VisitCallExpr(const CallExpr *E) {
942 VisitStmt(E);
943
944 // Terminate the region when we hit a noreturn function.
945 // (This is helpful dealing with switch statements.)
946 QualType CalleeType = E->getCallee()->getType();
947 if (getFunctionExtInfo(*CalleeType).getNoReturn())
948 terminateRegion(E);
949 }
950
Alex Lorenzee024992014-08-04 18:41:51 +0000951 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000952 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000953
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000954 Counter ParentCount = getRegion().getCounter();
955 Counter BodyCount = getRegionCounter(S);
956
957 // Handle the body first so that we can get the backedge count.
958 BreakContinueStack.push_back(BreakContinue());
959 extendRegion(S->getBody());
960 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000961 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000962
963 // Go back to handle the condition.
964 Counter CondCount =
965 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
966 propagateCounts(CondCount, S->getCond());
967 adjustForOutOfOrderTraversal(getEnd(S));
968
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000969 // The body count applies to the area immediately after the increment.
970 auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
971 if (Gap)
972 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
973
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000974 Counter OutCount =
975 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
976 if (OutCount != ParentCount)
977 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000978 }
979
980 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000981 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000982
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000983 Counter ParentCount = getRegion().getCounter();
984 Counter BodyCount = getRegionCounter(S);
985
986 BreakContinueStack.push_back(BreakContinue());
987 extendRegion(S->getBody());
988 Counter BackedgeCount =
989 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000990 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000991
992 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
993 propagateCounts(CondCount, S->getCond());
994
995 Counter OutCount =
996 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
997 if (OutCount != ParentCount)
998 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000999 }
1000
1001 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001002 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001003 if (S->getInit())
1004 Visit(S->getInit());
1005
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001006 Counter ParentCount = getRegion().getCounter();
1007 Counter BodyCount = getRegionCounter(S);
1008
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001009 // The loop increment may contain a break or continue.
1010 if (S->getInc())
1011 BreakContinueStack.emplace_back();
1012
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001013 // Handle the body first so that we can get the backedge count.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001014 BreakContinueStack.emplace_back();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001015 extendRegion(S->getBody());
1016 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001017 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +00001018
1019 // The increment is essentially part of the body but it needs to include
1020 // the count for all the continue statements.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001021 BreakContinue IncrementBC;
1022 if (const Stmt *Inc = S->getInc()) {
1023 propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1024 IncrementBC = BreakContinueStack.pop_back_val();
1025 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001026
1027 // Go back to handle the condition.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001028 Counter CondCount = addCounters(
1029 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1030 IncrementBC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001031 if (const Expr *Cond = S->getCond()) {
1032 propagateCounts(CondCount, Cond);
1033 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +00001034 }
1035
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001036 // The body count applies to the area immediately after the increment.
1037 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1038 getStart(S->getBody()));
1039 if (Gap)
1040 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1041
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001042 Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1043 subtractCounters(CondCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001044 if (OutCount != ParentCount)
1045 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001046 }
1047
1048 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001049 extendRegion(S);
Richard Smith8baa5002018-09-28 18:44:09 +00001050 if (S->getInit())
1051 Visit(S->getInit());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001052 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +00001053 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001054
1055 Counter ParentCount = getRegion().getCounter();
1056 Counter BodyCount = getRegionCounter(S);
1057
Alex Lorenzee024992014-08-04 18:41:51 +00001058 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001059 extendRegion(S->getBody());
1060 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001061 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001062
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001063 // The body count applies to the area immediately after the range.
1064 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1065 getStart(S->getBody()));
1066 if (Gap)
1067 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1068
Justin Bogner15874322015-04-30 21:31:02 +00001069 Counter LoopCount =
1070 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1071 Counter OutCount =
1072 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001073 if (OutCount != ParentCount)
1074 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001075 }
1076
1077 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001078 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001079 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001080
1081 Counter ParentCount = getRegion().getCounter();
1082 Counter BodyCount = getRegionCounter(S);
1083
Alex Lorenzee024992014-08-04 18:41:51 +00001084 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001085 extendRegion(S->getBody());
1086 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001087 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001088
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001089 // The body count applies to the area immediately after the collection.
1090 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1091 getStart(S->getBody()));
1092 if (Gap)
1093 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1094
Justin Bogner15874322015-04-30 21:31:02 +00001095 Counter LoopCount =
1096 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1097 Counter OutCount =
1098 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001099 if (OutCount != ParentCount)
1100 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001101 }
1102
1103 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001104 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +00001105 if (S->getInit())
1106 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +00001107 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001108
Alex Lorenzee024992014-08-04 18:41:51 +00001109 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001110
1111 const Stmt *Body = S->getBody();
1112 extendRegion(Body);
1113 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1114 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001115 // Make a region for the body of the switch. If the body starts with
1116 // a case, that case will reuse this region; otherwise, this covers
1117 // the unreachable code at the beginning of the switch body.
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001118 size_t Index =
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001119 pushRegion(Counter::getZero(), getStart(CS->body_front()));
Richard Trieub5841332015-04-15 01:21:42 +00001120 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001121 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001122
1123 // Set the end for the body of the switch, if it isn't already set.
1124 for (size_t i = RegionStack.size(); i != Index; --i) {
1125 if (!RegionStack[i - 1].hasEndLoc())
1126 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1127 }
1128
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001129 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +00001130 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +00001131 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001132 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +00001133 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001134
Alex Lorenzee024992014-08-04 18:41:51 +00001135 if (!BreakContinueStack.empty())
1136 BreakContinueStack.back().ContinueCount = addCounters(
1137 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001138
1139 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001140 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +00001141 pushRegion(ExitCount);
1142
1143 // Ensure that handleFileExit recognizes when the end location is located
1144 // in a different file.
1145 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001146 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +00001147 }
1148
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001149 void VisitSwitchCase(const SwitchCase *S) {
1150 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001151
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001152 SourceMappingRegion &Parent = getRegion();
1153
1154 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1155 // Reuse the existing region if it starts at our label. This is typical of
1156 // the first case in a switch.
Stephen Kellya6e43582018-08-09 21:05:56 +00001157 if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001158 Parent.setCounter(Count);
1159 else
1160 pushRegion(Count, getStart(S));
1161
Sanjay Patel376c06c2015-12-24 21:11:29 +00001162 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001163 Visit(CS->getLHS());
1164 if (const Expr *RHS = CS->getRHS())
1165 Visit(RHS);
1166 }
Alex Lorenzee024992014-08-04 18:41:51 +00001167 Visit(S->getSubStmt());
1168 }
1169
1170 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001171 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +00001172 if (S->getInit())
1173 Visit(S->getInit());
1174
Justin Bogner055ebc32015-06-16 06:24:15 +00001175 // Extend into the condition before we propagate through it below - this is
1176 // needed to handle macros that generate the "if" but not the condition.
1177 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +00001178
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001179 Counter ParentCount = getRegion().getCounter();
1180 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001181
Justin Bogner91f2e3c2015-02-19 03:10:30 +00001182 // Emitting a counter for the condition makes it easier to interpret the
1183 // counter for the body when looking at the coverage.
1184 propagateCounts(ParentCount, S->getCond());
1185
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001186 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001187 auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1188 if (Gap)
1189 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001190
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001191 extendRegion(S->getThen());
1192 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1193
1194 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1195 if (const Stmt *Else = S->getElse()) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001196 // The 'else' count applies to the area immediately after the 'then'.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001197 Gap = findGapAreaBetween(S->getThen(), Else);
1198 if (Gap)
1199 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001200 extendRegion(Else);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001201 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1202 } else
1203 OutCount = addCounters(OutCount, ElseCount);
1204
1205 if (OutCount != ParentCount)
1206 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001207 }
1208
1209 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001210 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +00001211 // Handle macros that generate the "try" but not the rest.
1212 extendRegion(S->getTryBlock());
1213
1214 Counter ParentCount = getRegion().getCounter();
1215 propagateCounts(ParentCount, S->getTryBlock());
1216
Alex Lorenzee024992014-08-04 18:41:51 +00001217 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1218 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001219
1220 Counter ExitCount = getRegionCounter(S);
1221 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001222 }
1223
1224 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001225 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +00001226 }
1227
1228 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001229 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001230
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001231 Counter ParentCount = getRegion().getCounter();
1232 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001233
Justin Bognere3654ce2015-04-24 23:37:57 +00001234 Visit(E->getCond());
1235
1236 if (!isa<BinaryConditionalOperator>(E)) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001237 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001238 auto Gap =
1239 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1240 if (Gap)
1241 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001242
Justin Bognere3654ce2015-04-24 23:37:57 +00001243 extendRegion(E->getTrueExpr());
1244 propagateCounts(TrueCount, E->getTrueExpr());
1245 }
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001246
Justin Bognere3654ce2015-04-24 23:37:57 +00001247 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001248 propagateCounts(subtractCounters(ParentCount, TrueCount),
1249 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +00001250 }
1251
1252 void VisitBinLAnd(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001253 extendRegion(E->getLHS());
1254 propagateCounts(getRegion().getCounter(), E->getLHS());
1255 handleFileExit(getEnd(E->getLHS()));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001256
1257 extendRegion(E->getRHS());
1258 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001259 }
1260
1261 void VisitBinLOr(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001262 extendRegion(E->getLHS());
1263 propagateCounts(getRegion().getCounter(), E->getLHS());
1264 handleFileExit(getEnd(E->getLHS()));
Alex Lorenzee024992014-08-04 18:41:51 +00001265
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001266 extendRegion(E->getRHS());
1267 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +00001268 }
Justin Bognerc1091022015-02-24 04:13:56 +00001269
1270 void VisitLambdaExpr(const LambdaExpr *LE) {
1271 // Lambdas are treated as their own functions for now, so we shouldn't
1272 // propagate counts into them.
1273 }
Alex Lorenzee024992014-08-04 18:41:51 +00001274};
Alex Lorenzee024992014-08-04 18:41:51 +00001275
Xinliang David Li1f39fcf2017-04-14 04:14:29 +00001276std::string getCoverageSection(const CodeGenModule &CGM) {
Vedant Kumar8a767a42017-04-15 00:10:05 +00001277 return llvm::getInstrProfSectionName(
1278 llvm::IPSK_covmap,
1279 CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
Alex Lorenzee024992014-08-04 18:41:51 +00001280}
1281
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001282std::string normalizeFilename(StringRef Filename) {
1283 llvm::SmallString<256> Path(Filename);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001284 llvm::sys::fs::make_absolute(Path);
Vedant Kumard04929d2016-07-18 22:32:02 +00001285 llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001286 return Path.str().str();
1287}
1288
1289} // end anonymous namespace
1290
Justin Bognera432d172015-02-03 00:20:24 +00001291static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1292 ArrayRef<CounterExpression> Expressions,
1293 ArrayRef<CounterMappingRegion> Regions) {
1294 OS << FunctionName << ":\n";
1295 CounterMappingContext Ctx(Expressions);
1296 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001297 OS.indent(2);
1298 switch (R.Kind) {
1299 case CounterMappingRegion::CodeRegion:
1300 break;
1301 case CounterMappingRegion::ExpansionRegion:
1302 OS << "Expansion,";
1303 break;
1304 case CounterMappingRegion::SkippedRegion:
1305 OS << "Skipped,";
1306 break;
Vedant Kumara1c4deb2017-09-18 23:37:30 +00001307 case CounterMappingRegion::GapRegion:
1308 OS << "Gap,";
1309 break;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001310 }
1311
Justin Bogner4da909b2015-02-03 21:35:49 +00001312 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1313 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001314 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001315 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001316 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1317 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001318 }
1319}
1320
Alex Lorenzee024992014-08-04 18:41:51 +00001321void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001322 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001323 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001324 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Alex Lorenzee024992014-08-04 18:41:51 +00001325 if (!FunctionRecordTy) {
Xinliang David Li2129ae52016-01-07 20:05:55 +00001326#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
Xinliang David Lia026a432015-11-05 05:46:39 +00001327 llvm::Type *FunctionRecordTypes[] = {
1328 #include "llvm/ProfileData/InstrProfData.inc"
1329 };
Alex Lorenzee024992014-08-04 18:41:51 +00001330 FunctionRecordTy =
Justin Bogner4dc5adc2015-07-02 20:47:25 +00001331 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1332 /*isPacked=*/true);
Alex Lorenzee024992014-08-04 18:41:51 +00001333 }
1334
Xinliang David Lia026a432015-11-05 05:46:39 +00001335 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
Alex Lorenzee024992014-08-04 18:41:51 +00001336 llvm::Constant *FunctionRecordVals[] = {
Xinliang David Lia026a432015-11-05 05:46:39 +00001337 #include "llvm/ProfileData/InstrProfData.inc"
1338 };
Alex Lorenzee024992014-08-04 18:41:51 +00001339 FunctionRecords.push_back(llvm::ConstantStruct::get(
1340 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
Xinliang David Li848da132016-01-19 00:49:06 +00001341 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001342 FunctionNames.push_back(
1343 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Vedant Kumarca3326c2016-01-21 19:25:35 +00001344 CoverageMappings.push_back(CoverageMapping);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001345
1346 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1347 // Dump the coverage mapping data for this function by decoding the
1348 // encoded data. This allows us to dump the mapping regions which were
1349 // also processed by the CoverageMappingWriter which performs
1350 // additional minimization operations such as reducing the number of
1351 // expressions.
1352 std::vector<StringRef> Filenames;
1353 std::vector<CounterExpression> Expressions;
1354 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001355 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001356 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001357 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001358 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001359 for (const auto &Entry : FileEntries) {
1360 auto I = Entry.second;
1361 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1362 FilenameRefs[I] = FilenameStrs[I];
1363 }
Justin Bognera432d172015-02-03 00:20:24 +00001364 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1365 Expressions, Regions);
1366 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001367 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001368 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001369 }
Alex Lorenzee024992014-08-04 18:41:51 +00001370}
1371
1372void CoverageMappingModuleGen::emit() {
1373 if (FunctionRecords.empty())
1374 return;
1375 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1376 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1377
1378 // Create the filenames and merge them with coverage mappings
1379 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001380 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001381 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001382 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001383 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001384 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001385 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001386 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001387 }
1388
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001389 std::string FilenamesAndCoverageMappings;
1390 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1391 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1392 std::string RawCoverageMappings =
1393 llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
1394 OS << RawCoverageMappings;
1395 size_t CoverageMappingSize = RawCoverageMappings.size();
1396 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1397 // Append extra zeroes if necessary to ensure that the size of the filenames
1398 // and coverage mappings is a multiple of 8.
1399 if (size_t Rem = OS.str().size() % 8) {
1400 CoverageMappingSize += 8 - Rem;
Peter Collingbourne070777d2018-05-17 22:11:43 +00001401 OS.write_zeros(8 - Rem);
Alex Lorenzee024992014-08-04 18:41:51 +00001402 }
1403 auto *FilenamesAndMappingsVal =
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001404 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
Alex Lorenzee024992014-08-04 18:41:51 +00001405
1406 // Create the deferred function records array
1407 auto RecordsTy =
1408 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1409 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1410
Xinliang David Li20b188c2016-01-03 19:25:54 +00001411 llvm::Type *CovDataHeaderTypes[] = {
1412#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1413#include "llvm/ProfileData/InstrProfData.inc"
1414 };
1415 auto CovDataHeaderTy =
1416 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1417 llvm::Constant *CovDataHeaderVals[] = {
1418#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1419#include "llvm/ProfileData/InstrProfData.inc"
1420 };
1421 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1422 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1423
Alex Lorenzee024992014-08-04 18:41:51 +00001424 // Create the coverage data record
Xinliang David Li20b188c2016-01-03 19:25:54 +00001425 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1426 FilenamesAndMappingsVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001427 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001428 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1429 FilenamesAndMappingsVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001430 auto CovDataVal =
1431 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001432 auto CovData = new llvm::GlobalVariable(
1433 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1434 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001435
1436 CovData->setSection(getCoverageSection(CGM));
1437 CovData->setAlignment(8);
1438
1439 // Make sure the data doesn't get deleted.
1440 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001441 // Create the deferred function records array
1442 if (!FunctionNames.empty()) {
1443 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1444 FunctionNames.size());
1445 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1446 // This variable will *NOT* be emitted to the object file. It is used
1447 // to pass the list of names referenced to codegen.
1448 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1449 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001450 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001451 }
Alex Lorenzee024992014-08-04 18:41:51 +00001452}
1453
1454unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1455 auto It = FileEntries.find(File);
1456 if (It != FileEntries.end())
1457 return It->second;
1458 unsigned FileID = FileEntries.size();
1459 FileEntries.insert(std::make_pair(File, FileID));
1460 return FileID;
1461}
1462
1463void CoverageMappingGen::emitCounterMapping(const Decl *D,
1464 llvm::raw_ostream &OS) {
1465 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001466 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001467 Walker.VisitDecl(D);
1468 Walker.write(OS);
1469}
1470
1471void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1472 llvm::raw_ostream &OS) {
1473 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1474 Walker.VisitDecl(D);
1475 Walker.write(OS);
1476}